From 965fd14be6b38b5eee630740eec4a09a8819b7d5 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 4 Dec 2026 05:01:29 +0000 Subject: [PATCH 1/3] feat(server): add M0 inbound admission cap and runtime decision log (CLO-1368) Implement M0 Items 2 and 3 from the Bot Runtime Plan (CLO-1368): - Add pure Inbound Cap v0 in packages/shared/src/inboundAdmission.ts: status and routine PR events never wake a thread; authenticated system pr_actionable wakes only on a PR opened/linked by a founder-mission thread or covered by a seat's active watch; remaining events on founder-mission threads accept only founders and own children, and seats accept founders, their reportsTo chain, and own children; all other deliveries cap at digest. - Wire inbound admission into Orchestrator.dispatchMessage (fail-safe to digest on error) and surface the effective deliveryClass and deliveryReason back to senders via ThreadManagementService and t3_thread_send. - Add migration 125_RuntimeDecisions.ts and append-only RuntimeDecisionStore (with SQLite CHECK constraints, update/delete abort triggers, and fail-closed audience filtering before write) supporting both inbound and placement decision records. - Add runtimeEnforcement server setting defaulting to observe (logs decisions with enforced=0 without capping) with a clean switch to enforce or off. - Add conformance unit tests for M0 exact checks 1 and 2 across shared, persistence, orchestrator, and MCP layers. Refs: CLO-1368 Model: gemini-4-neon Task: implementation Agent: Builder Harness: t3/antigravity Model-family: Gemini Model-generation: 4 Neon Skills-SHA: nullStack65/closura-agent-config@da5f66450f9d69207369395f7a30686834767453; skills/github-repository-ops/SKILL.md (sha256:e3778c3a953bfa9e7bf5c9b9609b6d6c947cffa03366b3bc0f75bbb722b76784, installed matches source) --- .../OrchestratorMcpService.activity.test.ts | 17 +- apps/server/src/mcp/OrchestratorMcpService.ts | 10 +- .../orchestration-v2/InboundAdmission.test.ts | 479 ++++++++++++++++++ .../src/orchestration-v2/InboundAdmission.ts | 392 ++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 111 +++- .../ThreadManagementService.ts | 13 +- .../src/orchestration-v2/runtimeLayer.ts | 2 + .../testkit/ProviderReplayHarness.ts | 31 +- .../server/src/persistence/Migrations.test.ts | 5 +- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/125_RuntimeDecisions.ts | 53 ++ .../src/persistence/RuntimeDecisions.test.ts | 157 ++++++ .../src/persistence/RuntimeDecisions.ts | 194 +++++++ apps/server/src/server.ts | 2 + packages/contracts/src/orchestrationV2.ts | 18 + packages/contracts/src/orchestratorMcp.ts | 1 + packages/contracts/src/settings.ts | 12 + packages/shared/package.json | 4 + packages/shared/src/inboundAdmission.test.ts | 358 +++++++++++++ packages/shared/src/inboundAdmission.ts | 458 +++++++++++++++++ 20 files changed, 2298 insertions(+), 21 deletions(-) create mode 100644 apps/server/src/orchestration-v2/InboundAdmission.test.ts create mode 100644 apps/server/src/orchestration-v2/InboundAdmission.ts create mode 100644 apps/server/src/persistence/Migrations/125_RuntimeDecisions.ts create mode 100644 apps/server/src/persistence/RuntimeDecisions.test.ts create mode 100644 apps/server/src/persistence/RuntimeDecisions.ts create mode 100644 packages/shared/src/inboundAdmission.test.ts create mode 100644 packages/shared/src/inboundAdmission.ts diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 6804c2e3f6dd0..9026133520828 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -1163,8 +1163,16 @@ it("readThread and sendToThread reach threads in other projects", async () => { ), sendToThread: () => Effect.succeed({ - run: { id: "run-foreign", status: "queued" }, - delivery: "started", + run: { id: "run-foreign", status: "queued", delivery: { class: "digest" } }, + delivery: "queued", + inboundAdmission: { + deliverAs: "digest", + requestedAs: "next_turn", + capped: true, + wakesThread: false, + enforced: true, + reason: "recipient holds a founder mission; status never starts a turn", + }, } as unknown as ThreadManagementService.ThreadManagementSendResult), } satisfies Partial), ServerSettings.layerTest(), @@ -1205,8 +1213,13 @@ it("readThread and sendToThread reach threads in other projects", async () => { const sent = yield* service.sendToThread(makeScope(), { threadId: foreignThreadId, message: "hi", + deliveryClass: "next_turn", }); expect(sent.threadId).toBe(foreignThreadId); + expect(sent.deliveryClass).toBe("digest"); + expect(sent.deliveryReason).toBe( + "recipient holds a founder mission; status never starts a turn", + ); parentRuns = []; yield* service.readThread(makeScope(), { threadId: foreignThreadId }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 69abe7d9c68de..16dd0df33162c 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -4075,6 +4075,13 @@ const make = Effect.gen(function* () { ), ); } + const effectiveDeliveryClass = + result.run.delivery?.class ?? + (result.inboundAdmission?.enforced === true && + result.inboundAdmission.deliverAs !== "log_only" + ? result.inboundAdmission.deliverAs + : deliveryClass); + const deliveryReason = result.inboundAdmission?.reason; return { threadId: liveThreadId, link: threadLinkFor(scope, liveThreadId, target.thread.title), @@ -4083,7 +4090,8 @@ const make = Effect.gen(function* () { ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }), status: result.run.status, delivery: result.delivery, - ...(deliveryClass === undefined ? {} : { deliveryClass }), + ...(effectiveDeliveryClass === undefined ? {} : { deliveryClass: effectiveDeliveryClass }), + ...(deliveryReason === undefined ? {} : { deliveryReason }), } satisfies OrchestratorMcpThreadSendResult; }), askAgent: Effect.fn("OrchestratorMcpService.askAgent")(function* (scope, input) { diff --git a/apps/server/src/orchestration-v2/InboundAdmission.test.ts b/apps/server/src/orchestration-v2/InboundAdmission.test.ts new file mode 100644 index 0000000000000..9d6d2a15bc270 --- /dev/null +++ b/apps/server/src/orchestration-v2/InboundAdmission.test.ts @@ -0,0 +1,479 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as RuntimeDecisions from "../persistence/RuntimeDecisions.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("InboundAdmission tests run with runEffectWorker: false"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; + +const layerDatabase = SqlitePersistence.layerMemory; +const layerServerSettings = ServerSettings.layerTest({ responseStreamingMode: "turn" }).pipe( + Layer.orDie, +); +const layerTest = Layer.mergeAll( + layerDatabase, + layerServerSettings, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + RuntimeDecisions.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "inbound-admission" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { + databaseLayer: layerDatabase, + serverSettingsLayer: layerServerSettings, + runEffectWorker: false, + }, + ), +); + +const createThread = (input: { + readonly threadId: ThreadId; + readonly title: string; + readonly createdBy: "user" | "agent"; + readonly standing?: { + readonly name: string; + readonly role: string; + readonly avatarId: "bolt" | "sprout" | "visor"; + readonly accent: "sky" | "violet" | "indigo"; + }; + readonly audience?: "kameron" | "shared" | "agent-only"; +}) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${input.threadId}`), + threadId: input.threadId, + projectId: ProjectId.make("project:inbound-admission"), + title: input.title, + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: input.createdBy, + creationSource: input.createdBy === "user" ? "web" : "mcp", + }); + if (input.standing !== undefined) { + yield* orchestrator.dispatch({ + type: "thread.standing.set", + commandId: CommandId.make(`standing:${input.threadId}`), + threadId: input.threadId, + standing: input.standing, + }); + } + if (input.audience !== undefined) { + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`inbox:${input.threadId}`), + threadId: input.threadId, + inboxRouting: { + owner: input.audience === "kameron" ? "kameron" : null, + assignee: null, + audience: input.audience, + attentionKind: input.audience === "agent-only" ? "background" : "FYI", + reason: "conversation", + }, + }); + } + }); + +const startedRunsCount = (threadId: ThreadId) => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const projection = yield* projections.getThreadProjection(threadId); + return projection.runs.filter((run) => run.status !== "queued" && run.status !== "cancelled") + .length; + }); + +it.layer(layerTest)("M0 inbound admission and runtime_decisions", (it) => { + it.effect( + "defaults to observe mode (logs enforced=0 without capping) and enforces when switched", + () => + Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const decisions = yield* RuntimeDecisions.RuntimeDecisionStore; + + assert.strictEqual((yield* settings.getSettings).runtimeEnforcement, "observe"); + + const factoryId = ThreadId.make("thread:observe-factory"); + const ctoId = ThreadId.make("thread:observe-cto"); + yield* createThread({ + threadId: factoryId, + title: "Software Factory", + createdBy: "user", + audience: "kameron", + }); + yield* createThread({ + threadId: ctoId, + title: "CTO", + createdBy: "agent", + standing: { + name: "CTO", + role: "Engineering", + avatarId: "bolt", + accent: "sky", + }, + audience: "shared", + }); + + const observed = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("observe:cto-send-1"), + threadId: factoryId, + senderThreadId: ctoId, + messageId: MessageId.make("msg:observe-1"), + text: "Interim PR 1681 status update", + attachments: [], + delivery: { class: "next_turn" }, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + + assert.strictEqual(observed.inboundAdmission?.enforced, false); + assert.strictEqual(observed.inboundAdmission?.deliverAs, "digest"); + assert.strictEqual(observed.inboundAdmission?.capped, true); + // Observe mode does NOT cap delivery yet. + assert.strictEqual(yield* startedRunsCount(factoryId), 1); + + const rows = yield* decisions.listForThread(factoryId); + assert.strictEqual(rows.length, 1); + assert.strictEqual(rows[0]?.kind, "inbound"); + assert.strictEqual(rows[0]?.eventKind, "status"); + assert.strictEqual(rows[0]?.recipientFounderMission, true); + assert.strictEqual(rows[0]?.decision, "digest"); + assert.strictEqual(rows[0]?.enforced, false); + }), + ); + + it.effect( + "M0 exact checks 1 & 2: Factory sequence yields 0 turns, covered watch wakes seat, chain wakes idle seat", + () => + Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const decisions = yield* RuntimeDecisions.RuntimeDecisionStore; + const sql = yield* SqlClient.SqlClient; + + yield* settings.updateSettings({ runtimeEnforcement: "enforce" }); + + // 1. Software Factory sequence (CTO sends at 21:34:05, 21:45:29, 22:11:32) -> 0 turns. + const factoryId = ThreadId.make("thread:enforce-factory"); + const ctoId = ThreadId.make("thread:enforce-cto"); + yield* createThread({ + threadId: factoryId, + title: "Software Factory", + createdBy: "user", + audience: "kameron", + }); + yield* createThread({ + threadId: ctoId, + title: "CTO", + createdBy: "agent", + standing: { + name: "CTO", + role: "Engineering", + avatarId: "bolt", + accent: "sky", + }, + audience: "shared", + }); + + const factorySends = [ + { tag: "213405", requested: "next_turn" as const }, + { tag: "214529", requested: "when_idle" as const }, + { tag: "221132", requested: "steer_at_tool_boundary" as const }, + ]; + for (const send of factorySends) { + const result = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`factory:cto:${send.tag}`), + threadId: factoryId, + senderThreadId: ctoId, + messageId: MessageId.make(`msg:factory:cto:${send.tag}`), + text: `CTO status update ${send.tag}`, + attachments: [], + delivery: { class: send.requested }, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + assert.strictEqual(result.inboundAdmission?.deliverAs, "digest"); + assert.strictEqual(result.inboundAdmission?.capped, true); + assert.strictEqual(result.inboundAdmission?.wakesThread, false); + assert.strictEqual(result.inboundAdmission?.enforced, true); + assert.include(result.inboundAdmission?.reason ?? "", "status"); + } + assert.strictEqual(yield* startedRunsCount(factoryId), 0); + + // Idempotent replay of the last command must not append a duplicate runtime_decisions row. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("factory:cto:221132"), + threadId: factoryId, + senderThreadId: ctoId, + messageId: MessageId.make("msg:factory:cto:221132"), + text: "CTO status update 221132", + attachments: [], + delivery: { class: "steer_at_tool_boundary" }, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + assert.strictEqual((yield* decisions.listForThread(factoryId)).length, 3); + + // Routine PR event on the founder-mission thread yields 0 turns and logs log_only. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("factory:pr-routine"), + threadId: factoryId, + messageId: MessageId.make("msg:factory:pr-routine"), + text: "Update on pull request #1681: required checks passed", + notification: { + source: { + kind: "monitor", + pullRequest: { + host: "github.com", + repository: "nullStack65/closura-agent-config", + number: 1681, + watchStartedAt: "2026-12-01T21:00:00.000Z", + headSha: "abcdef1", + }, + }, + outcome: "completed", + summary: "#1681: required checks passed", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.strictEqual(yield* startedRunsCount(factoryId), 0); + + // 2. Product Designer run 481: covered watch wakes seat; uncovered & routine yield 0 turns. + const designerId = ThreadId.make("thread:enforce-designer"); + yield* createThread({ + threadId: designerId, + title: "Product Designer", + createdBy: "agent", + standing: { + name: "Product Designer", + role: "Design & Craft", + avatarId: "sprout", + accent: "violet", + }, + audience: "shared", + }); + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("designer:watch-481"), + threadId: designerId, + host: "github.com", + repository: "nullStack65/Closura", + number: 481, + watching: true, + link: { + url: "https://github.com/nullStack65/Closura/pull/481", + source: "manual", + }, + }); + + // Uncovered PR actionable -> 0 turns. + const uncoveredPr = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("designer:uncovered-pr"), + threadId: designerId, + messageId: MessageId.make("msg:designer:uncovered-pr"), + text: "Update on pull request #999: checks failed", + notification: { + source: { + kind: "monitor", + pullRequest: { + host: "github.com", + repository: "nullStack65/Closura", + number: 999, + watchStartedAt: "2026-12-01T20:00:00.000Z", + headSha: "9999999", + }, + }, + outcome: "failed", + summary: "#999: checks failed", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.strictEqual(uncoveredPr.inboundAdmission?.deliverAs, "log_only"); + assert.strictEqual(yield* startedRunsCount(designerId), 0); + + // Routine PR event on the seat's own watched PR yields 0 turns. + const routinePr = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("designer:routine-481"), + threadId: designerId, + messageId: MessageId.make("msg:designer:routine-481"), + text: "Update on pull request #481: checks passed", + notification: { + source: { + kind: "monitor", + pullRequest: { + host: "github.com", + repository: "nullStack65/Closura", + number: 481, + watchStartedAt: "2026-12-01T20:00:00.000Z", + headSha: "1111111", + }, + }, + outcome: "completed", + summary: "#481: checks passed", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.strictEqual(routinePr.inboundAdmission?.deliverAs, "log_only"); + assert.strictEqual(yield* startedRunsCount(designerId), 0); + + // Actionable PR event on the seat's watched PR wakes the seat. + const coveredActionable = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("designer:actionable-481"), + threadId: designerId, + messageId: MessageId.make("msg:designer:actionable-481"), + text: "Update on pull request #481: checks failed", + notification: { + source: { + kind: "monitor", + pullRequest: { + host: "github.com", + repository: "nullStack65/Closura", + number: 481, + watchStartedAt: "2026-12-01T20:00:00.000Z", + headSha: "1111111", + }, + }, + outcome: "failed", + summary: "#481: checks failed", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.strictEqual(coveredActionable.inboundAdmission?.deliverAs, "next_turn"); + assert.strictEqual(coveredActionable.inboundAdmission?.wakesThread, true); + assert.strictEqual(yield* startedRunsCount(designerId), 1); + + // 3. Chain send to idle seat -> yields a turn; peer send -> capped at digest (0 turns). + const platformId = ThreadId.make("thread:enforce-platform"); + const cosId = ThreadId.make("thread:enforce-cos"); + yield* createThread({ + threadId: platformId, + title: "Platform", + createdBy: "agent", + standing: { + name: "Platform", + role: "Platform Engineering", + avatarId: "bolt", + accent: "sky", + }, + audience: "agent-only", + }); + yield* createThread({ + threadId: cosId, + title: "CoS", + createdBy: "agent", + standing: { + name: "CoS", + role: "Chief of Staff", + avatarId: "visor", + accent: "indigo", + }, + audience: "kameron", + }); + + const peerSend = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("platform:cos-peer"), + threadId: platformId, + senderThreadId: cosId, + messageId: MessageId.make("msg:platform:cos-peer"), + text: "FYI status note from CoS", + attachments: [], + delivery: { class: "next_turn" }, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + assert.strictEqual(peerSend.inboundAdmission?.deliverAs, "digest"); + assert.strictEqual(peerSend.inboundAdmission?.wakesThread, false); + assert.strictEqual(yield* startedRunsCount(platformId), 0); + + const chainSend = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("platform:cto-chain"), + threadId: platformId, + senderThreadId: ctoId, + messageId: MessageId.make("msg:platform:cto-chain"), + text: "Assign CLO-1368 M0 item 2", + attachments: [], + delivery: { class: "next_turn" }, + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + assert.strictEqual(chainSend.inboundAdmission?.deliverAs, "next_turn"); + assert.strictEqual(chainSend.inboundAdmission?.wakesThread, true); + assert.strictEqual(yield* startedRunsCount(platformId), 1); + + // Verify the capped Factory runs stayed queued as digest. + const factoryProjection = yield* projections.getThreadProjection(factoryId); + assert.isTrue( + factoryProjection.runs.every( + (run) => run.status === "queued" && run.delivery?.class === "digest", + ), + ); + + // Exact Check 2 SQL query from Bot Runtime Plan Section 11 must return 0. + const [exactCheck2] = yield* sql<{ readonly count: number }>` + SELECT count(*) AS count + FROM runtime_decisions + WHERE kind = 'inbound' + AND enforced = 1 + AND decision IN ('next_turn', 'when_idle', 'steer') + AND recipient_founder_mission = 1 + AND event_kind IN ('status', 'pr_routine') + `; + assert.strictEqual(exactCheck2?.count, 0); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/InboundAdmission.ts b/apps/server/src/orchestration-v2/InboundAdmission.ts new file mode 100644 index 0000000000000..fa3873ba3c0d8 --- /dev/null +++ b/apps/server/src/orchestration-v2/InboundAdmission.ts @@ -0,0 +1,392 @@ +import { + isStandingThreadRoot, + type OrchestrationV2AppThread, + type OrchestrationV2Command, + type OrchestrationV2DeliveryClass, + type OrchestrationV2Notification, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; +import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts"; +import { + admitInbound, + computeRuntimeDecisionInputDigest, + isInReportsToChain, + normalizeSeatRoleKey, + type InboundAdmissionResult, + type InboundEvent, + type InboundEventKind, + type InboundRecipient, + type InboundSenderRelation, + type RuntimeDecisionAudienceContext, + type RuntimeDecisionRecord, +} from "@t3tools/shared/inboundAdmission"; + +export type MessageDispatchCommand = Extract< + OrchestrationV2Command, + { readonly type: "message.dispatch" } +>; + +export interface PlannedInboundDecision { + readonly admission: InboundAdmissionResult; + readonly enforced: boolean; + readonly record: Extract; + readonly audienceContext: RuntimeDecisionAudienceContext; +} + +export interface OrchestratorV2InboundAdmissionOutcome { + readonly deliverAs: InboundAdmissionResult["deliverAs"]; + readonly requestedAs: OrchestrationV2DeliveryClass; + readonly capped: boolean; + readonly wakesThread: boolean; + readonly enforced: boolean; + readonly reason: string; +} + +export function isInternalDispatchCommand(command: MessageDispatchCommand): boolean { + return ( + command.humanNote === true || + command.idleCompaction !== undefined || + command.restartContinuationOfRunId !== undefined || + command.usageLimitContinuationOfRunId !== undefined || + command.manualContinuationOfRunId !== undefined || + command.providerFailover !== undefined || + command.steerFollowUpOfRunId !== undefined || + (command.senderThreadId !== undefined && command.senderThreadId === command.threadId) + ); +} + +function classifyInboundRecipient( + projection: Pick, +): InboundRecipient { + const { thread, messages } = projection; + if (isStandingThreadRoot(thread)) { + const profile = normalizeSeatRoleKey(thread.standing?.name) ?? undefined; + return { + kind: "seat", + ...(profile === undefined ? {} : { profile }), + founderMission: false, + }; + } + if (thread.lineage.parentThreadId !== null || thread.delegatedFrom !== undefined) { + return { kind: "worker", founderMission: false }; + } + const active = thread.settledOverride !== "settled" && thread.archivedAt === null; + const audience = thread.inbox?.audience; + const humanAudience = audience === "kameron" || audience === "jeff" || audience === "shared"; + const founderOrigin = + thread.createdBy === "user" || + thread.inbox?.origin?.kind === "human" || + (humanAudience && + messages.some((message) => message.role === "user" && message.createdBy === "user")); + if (active && founderOrigin) { + return { kind: "founder_mission", founderMission: true }; + } + return { kind: "ordinary", founderMission: false }; +} + +const ACTIONABLE_PR_SUMMARY_RE = + /\b(merged|closed|changes requested|comment|conflict|rebase|failed|failing|removed from merge queue|stopped watching|no observed progress|awaiting approval)\b/i; + +function classifyMonitorPullRequestEvent( + notification: OrchestrationV2Notification, +): "pr_actionable" | "pr_routine" { + if (notification.outcome === "failed") return "pr_actionable"; + if (ACTIONABLE_PR_SUMMARY_RE.test(notification.summary)) return "pr_actionable"; + return "pr_routine"; +} + +function threadPullRequestKey(pr: { + readonly host?: string | undefined; + readonly repository: string; + readonly number: number; + readonly url?: string | undefined; +}): string { + const normalized = normalizeThreadPullRequestKey({ + host: pr.host ?? "github.com", + repository: pr.repository, + number: pr.number, + ...(pr.url === undefined ? {} : { url: pr.url }), + }); + return `${normalized.host}:${normalized.repository.toLowerCase()}#${normalized.number}`; +} + +function isPullRequestCoveredByThread( + thread: Pick< + OrchestrationV2AppThread, + "pullRequests" | "linkedPullRequest" | "branchPullRequest" + >, + source: Extract, + founderMission: boolean, +): boolean { + const stamps = [ + ...(source.pullRequest === undefined ? [] : [source.pullRequest]), + ...(source.otherPullRequests ?? []), + ]; + if (stamps.length === 0) return false; + + const linksByKey = new Map( + (thread.pullRequests ?? []).map((link) => [threadPullRequestKey(link), link] as const), + ); + const directKeys = new Set(); + if (thread.linkedPullRequest != null) { + directKeys.add(threadPullRequestKey(thread.linkedPullRequest)); + } + if (thread.branchPullRequest != null) { + directKeys.add(threadPullRequestKey(thread.branchPullRequest)); + } + + return stamps.every((stamp) => { + const key = threadPullRequestKey(stamp); + const link = linksByKey.get(key); + if (founderMission) { + return link !== undefined || directKeys.has(key); + } + if (link === undefined) return false; + return link.watch != null || stamp.watchEnded === true; + }); +} + +function requestedClassOf(command: MessageDispatchCommand): OrchestrationV2DeliveryClass { + if (command.delivery?.class !== undefined) return command.delivery.class; + if (command.dispatchMode.type === "restart_active" || command.deliveryIntent === "restart") { + return "interrupt"; + } + if (command.dispatchMode.type === "steer_active" || command.deliveryIntent === "steer") { + return "steer_at_tool_boundary"; + } + return "next_turn"; +} + +type SenderThreadInfo = Pick; + +function resolveCrossThreadSender( + command: MessageDispatchCommand, + thread: OrchestrationV2AppThread, + recipient: InboundRecipient, + senderShell: SenderThreadInfo | null, +): InboundSenderRelation { + if ( + senderShell !== null && + (senderShell.lineage.parentThreadId === command.threadId || + senderShell.delegatedFrom?.threadId === command.threadId) + ) { + return "child"; + } + if ( + command.senderThreadId !== undefined && + (thread.lineage.parentThreadId === command.senderThreadId || + thread.delegatedFrom?.threadId === command.senderThreadId) + ) { + return "delegator"; + } + if (recipient.kind === "seat" && thread.standing != null) { + const senderName = senderShell?.standing?.name ?? command.linkedSender?.title; + if (isInReportsToChain(senderName, thread.standing.name)) { + return "chain"; + } + } + return "peer"; +} + +function evaluateInboundDispatch(input: { + readonly command: MessageDispatchCommand; + readonly projection: Pick; + readonly senderShell: SenderThreadInfo | null; + readonly env: string; + readonly at: string; + readonly enforced: boolean; +}): PlannedInboundDecision { + const { command, projection, senderShell, env, at, enforced } = input; + const recipient = classifyInboundRecipient(projection); + const requestedClass = requestedClassOf(command); + const authenticatedSystem = command.creationSource === "server"; + + let sender: InboundSenderRelation; + let kind: InboundEventKind; + let prCovered: boolean | undefined; + let itemKey: string | undefined; + + if ( + command.createdBy === "user" && + command.scheduledTaskId === undefined && + command.notification === undefined && + command.delegatedCompletion === undefined + ) { + sender = "founder"; + kind = command.inboundEventKind ?? "founder_message"; + } else if ( + command.delegatedCompletion !== undefined || + command.notification?.source.kind === "delegated_task" || + command.notification?.source.kind === "subagent" || + command.notification?.source.kind === "command" || + (command.notification?.source.kind === "monitor" && + command.notification.source.staleWaits !== undefined) + ) { + sender = "child"; + kind = command.inboundEventKind ?? "child_result"; + } else if (command.notification?.source.kind === "monitor") { + sender = "system"; + kind = command.inboundEventKind ?? classifyMonitorPullRequestEvent(command.notification); + prCovered = isPullRequestCoveredByThread( + projection.thread, + command.notification.source, + recipient.founderMission, + ); + const pr = command.notification.source.pullRequest; + if (pr !== undefined) { + itemKey = `pr:${pr.repository}#${pr.number}`; + } + } else if (command.notification !== undefined) { + sender = "system"; + kind = + command.inboundEventKind ?? + (command.messageId.startsWith("message:delegation-nudge:") + ? "system_nudge" + : command.delivery?.category === "fyi" + ? "status" + : "alert"); + } else if (command.scheduledTaskId !== undefined) { + sender = "system"; + kind = command.inboundEventKind ?? "schedule"; + } else { + sender = resolveCrossThreadSender(command, projection.thread, recipient, senderShell); + if (command.inboundEventKind !== undefined) { + kind = command.inboundEventKind; + } else if (sender === "child") { + kind = "child_result"; + } else if (sender === "chain" || sender === "delegator") { + kind = + command.delivery?.category === "fyi" && command.delivery.class === "digest" + ? "status" + : "handoff"; + } else { + kind = "status"; + } + } + + const event: InboundEvent = { + kind, + requestedClass, + ...(command.delivery?.coalesceKey === undefined + ? {} + : { coalesceKey: command.delivery.coalesceKey }), + ...(itemKey === undefined ? {} : { itemKey }), + ...(sender === "system" ? { authenticatedSystem } : {}), + ...(prCovered === undefined ? {} : { prCovered }), + }; + + const admission = admitInbound(event, sender, recipient); + const inputDigest = computeRuntimeDecisionInputDigest({ + commandId: command.commandId, + threadId: command.threadId, + messageId: command.messageId, + sender, + senderThreadId: command.senderThreadId ?? command.linkedSender?.threadId ?? null, + eventKind: kind, + requestedClass, + recipientKind: recipient.kind ?? "ordinary", + recipientProfile: recipient.profile ?? null, + recipientFounderMission: recipient.founderMission, + authenticatedSystem: sender === "system" ? authenticatedSystem : null, + prCovered: prCovered ?? null, + itemKey: itemKey ?? null, + }); + + return { + admission, + enforced, + record: { + at, + env, + thread: command.threadId, + kind: "inbound", + eventKind: kind, + recipientFounderMission: recipient.founderMission, + inputDigest, + decision: admission.deliverAs, + reason: admission.reason, + enforced, + }, + audienceContext: { + audience: projection.thread.inbox?.audience ?? null, + }, + }; +} + +export function evaluateInboundDispatchSafe( + input: Parameters[0], +): + | { readonly ok: true; readonly planned: PlannedInboundDecision } + | { readonly ok: false; readonly cause: unknown; readonly planned: PlannedInboundDecision } { + try { + return { ok: true, planned: evaluateInboundDispatch(input) }; + } catch (cause) { + return { + ok: false, + cause, + planned: { + admission: { + deliverAs: "digest", + requestedAs: input.command.delivery?.class ?? "next_turn", + capped: true, + wakesThread: false, + reason: "inbound admission failed; defaulted to digest", + }, + enforced: input.enforced, + record: { + at: input.at, + env: input.env, + thread: input.command.threadId, + kind: "inbound", + eventKind: input.command.inboundEventKind ?? "status", + recipientFounderMission: false, + inputDigest: "error", + decision: "digest", + reason: "inbound admission failed; defaulted to digest", + enforced: input.enforced, + }, + audienceContext: { audience: input.projection.thread.inbox?.audience ?? null }, + }, + }; + } +} + +export function applyInboundAdmissionToCommand( + command: MessageDispatchCommand, + admission: InboundAdmissionResult, +): MessageDispatchCommand { + if (!admission.capped || admission.deliverAs === "log_only") { + return command; + } + const delivery = { + ...command.delivery, + class: admission.deliverAs, + ...(command.delivery?.coalesceKey === undefined && admission.coalesceKey !== undefined + ? { coalesceKey: admission.coalesceKey } + : {}), + }; + const { deliveryIntent: _droppedIntent, ...withoutIntent } = command; + return { + ...withoutIntent, + delivery, + dispatchMode: + admission.deliverAs === "digest" || + admission.deliverAs === "next_turn" || + admission.deliverAs === "when_idle" + ? { type: "queue_after_active" as const } + : command.dispatchMode, + }; +} + +export function toInboundAdmissionOutcome( + planned: PlannedInboundDecision, +): OrchestratorV2InboundAdmissionOutcome { + return { + deliverAs: planned.admission.deliverAs, + requestedAs: planned.admission.requestedAs, + capped: planned.admission.capped, + wakesThread: planned.admission.wakesThread, + enforced: planned.enforced, + reason: planned.admission.reason, + }; +} diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8e958e4c47a92..90a95ebe3b07b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -21,6 +21,15 @@ import { type ThreadInbox, } from "@t3tools/contracts"; import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; +import * as RuntimeDecisionStore from "../persistence/RuntimeDecisions.ts"; +import { + applyInboundAdmissionToCommand, + evaluateInboundDispatchSafe, + isInternalDispatchCommand, + toInboundAdmissionOutcome, + type OrchestratorV2InboundAdmissionOutcome, + type PlannedInboundDecision, +} from "./InboundAdmission.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -438,6 +447,8 @@ export interface OrchestratorV2DispatchResult { readonly storedEvents: ReadonlyArray; /** The command id was already accepted; analytics skip it. */ readonly replayed?: true; + /** Closura: inbound admission decision applied or observed for a message.dispatch (CLO-1368). */ + readonly inboundAdmission?: OrchestratorV2InboundAdmissionOutcome; } export interface OrchestratorV2Shape { @@ -1933,6 +1944,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const providerSessions = yield* ProviderSessionManagerV2; const providerSwitchService = yield* ProviderSwitchServiceV2; const serverSettings = yield* ServerSettings.ServerSettingsService; + const runtimeDecisions = yield* Effect.serviceOption(RuntimeDecisionStore.RuntimeDecisionStore); + const serverEnvironment = yield* Effect.serviceOption(ServerEnvironmentIdentity); const runtimePolicy = yield* RuntimePolicyV2; const threadForkService = yield* ThreadForkServiceV2; const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor; @@ -5117,6 +5130,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio >, events: Ref.Ref>, effects: Ref.Ref>, + inboundDecisions?: Ref.Ref>, ) { const thread = yield* projectionStore .getThread(command.threadId) @@ -5258,6 +5272,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, events, effects, + inboundDecisions, ); }, ); @@ -8304,10 +8319,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* ( - command: Extract, + rawCommand: Extract, events: Ref.Ref>, effects: Ref.Ref>, + inboundDecisions?: Ref.Ref>, ) { + let command = rawCommand; // A compacted thread reads every run, but attempts, nodes, messages, provider turns and prompts // only for its recent runs and the runs this command names. An idle compaction reads in full: // its busy check below looks for a delegated result's message under any old run. @@ -8577,6 +8594,55 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; } + // Closura: M0 Inbound Cap v0 + runtime decision log (CLO-1368). + if (inboundDecisions !== undefined && !isInternalDispatchCommand(command)) { + const enforcementMode = (yield* serverSettings.getSettings.pipe(Effect.orDie)) + .runtimeEnforcement; + if (enforcementMode !== "off") { + const enforced = enforcementMode === "enforce"; + const now = yield* DateTime.now; + const env = Option.isSome(serverEnvironment) + ? yield* serverEnvironment.value.getEnvironmentId + : "local"; + const senderShell = + command.senderThreadId === undefined + ? null + : yield* findThread(command.senderThreadId).pipe(Effect.orElseSucceed(() => null)); + const evaluated = evaluateInboundDispatchSafe({ + command, + projection, + senderShell, + env, + at: DateTime.formatIso(now), + enforced, + }); + if (!evaluated.ok) { + yield* Effect.logWarning("inbound admission threw; defaulting to digest", { + threadId: command.threadId, + commandId: command.commandId, + cause: evaluated.cause, + }); + } + const { planned } = evaluated; + yield* Ref.update(inboundDecisions, (existing) => [...existing, planned]); + if (enforced) { + if (planned.admission.deliverAs === "log_only") { + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: now, + payload: projection.thread, + }); + return; + } + command = applyInboundAdmissionToCommand(command, planned.admission); + } + } + } + if (projection.thread.lastVisitedAt === null && !isNativeMaintenanceCommand(command)) { const now = yield* DateTime.now; // Null keeps imported history read. The first fresh dispatch establishes @@ -17621,6 +17687,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly reason: string; }; readonly updateDelegatedCompletionOnlyRunId?: RunId; + readonly inboundDecisions?: ReadonlyArray; }, OrchestratorV2Error > { @@ -17632,6 +17699,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const events = yield* Ref.make>([]); const effects = yield* Ref.make>([]); + const inboundDecisions = yield* Ref.make>([]); let cancelUnsettledEffects: | { readonly effectTypes: ReadonlyArray; @@ -17834,7 +17902,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (continuation !== undefined) yield* refuseNativeSubagentMessage(command); yield* dispatchThreadMutation(command, events, effects); if (continuation !== undefined) { - cancelUnsettledEffects = yield* dispatchMessage(continuation, events, effects); + cancelUnsettledEffects = yield* dispatchMessage( + continuation, + events, + effects, + inboundDecisions, + ); yield* recordSubagentFollowup(continuation, events).pipe(mapDispatchError(command)); } break; @@ -17846,7 +17919,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* updateWaitStaleness(command, events, effects); break; case "thread.pull-request-watch.sync": - yield* dispatchPullRequestWatchSync(command, events, effects); + yield* dispatchPullRequestWatchSync(command, events, effects, inboundDecisions); break; case "thread.guest-share.open": case "thread.guest-share.redeem": @@ -17928,7 +18001,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio text: guestSend.text, context: { version: 1 as const, records: [], guest: guestSend.guest }, }; - cancelUnsettledEffects = yield* dispatchMessage(dispatched, events, effects); + cancelUnsettledEffects = yield* dispatchMessage( + dispatched, + events, + effects, + inboundDecisions, + ); yield* recordSubagentFollowup(dispatched, events).pipe(mapDispatchError(command)); break; } @@ -18161,6 +18239,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return { events: yield* Ref.get(events), effects: yield* Ref.get(effects), + inboundDecisions: yield* Ref.get(inboundDecisions), ...(cancelUnsettledEffects === undefined ? {} : { cancelUnsettledEffects }), ...(updateDelegatedCompletionOnlyRunId === undefined ? {} @@ -18535,10 +18614,34 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); } + const plannedInboundDecisions = plan.inboundDecisions ?? []; + if ( + committed.committed && + Option.isSome(runtimeDecisions) && + plannedInboundDecisions.length > 0 + ) { + for (const decision of plannedInboundDecisions) { + yield* runtimeDecisions.value.append(decision.record, decision.audienceContext).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to append inbound runtime decision", { + threadId: commandThreadId(command), + commandId: command.commandId, + cause, + }), + ), + ); + } + } + + const lastInboundDecision = plannedInboundDecisions.at(-1); + return { sequence: committed.receipt.resultSequence, storedEvents: committed.storedEvents, ...(committed.committed ? {} : { replayed: true as const }), + ...(lastInboundDecision === undefined + ? {} + : { inboundAdmission: toInboundAdmissionOutcome(lastInboundDecision) }), } satisfies OrchestratorV2DispatchResult; }, withCommandMetrics); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index aa5473a9cbbe8..5683dc1b3b733 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -233,6 +233,7 @@ export interface ThreadManagementSendResult { readonly run: OrchestrationV2Run; readonly turnItem: Extract | null; readonly delivery: "started" | "queued" | "steered" | "restarted"; + readonly inboundAdmission?: Orchestrator.OrchestratorV2DispatchResult["inboundAdmission"]; } export interface ThreadManagementWaitInput { @@ -1233,7 +1234,17 @@ const make = Effect.gen(function* () { : mode === "restart" ? "restarted" : "steered"; - return { dispatch: dispatched, projection, message, run, turnItem, delivery }; + return { + dispatch: dispatched, + projection, + message, + run, + turnItem, + delivery, + ...(dispatched.inboundAdmission === undefined + ? {} + : { inboundAdmission: dispatched.inboundAdmission }), + }; }); const submitRunOutput: ThreadManagementServiceShape["submitRunOutput"] = Effect.fn( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 241dbd21e51dc..1b5c186512811 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -6,6 +6,7 @@ import * as Layer from "effect/Layer"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as OrchestrationCommandReceipts from "../persistence/OrchestrationCommandReceipts.ts"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; +import * as RuntimeDecisionStore from "../persistence/RuntimeDecisions.ts"; import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; import * as PreviewAgentActivity from "../preview/PreviewAgentActivity.ts"; import * as McpAppRequests from "../mcpApps/McpAppRequests.ts"; @@ -263,6 +264,7 @@ const layerOrchestratorProvided = Orchestrator.layer.pipe( layerProviderSessionManagerProvided, layerProviderSwitchServiceProvided, layerRunExecutionServiceProvided, + RuntimeDecisionStore.layer, ThreadForkService.layer, ), ), diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 1859e9faed5f3..4e741e206e49c 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -21,6 +21,7 @@ import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts"; import * as ServerConfig from "../../config.ts"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; +import * as RuntimeDecisionStore from "../../persistence/RuntimeDecisions.ts"; import * as ServerSettings from "../../serverSettings.ts"; import * as ManagedPolicy from "../../policy/ManagedPolicy.ts"; import * as ThreadManagementService from "../ThreadManagementService.ts"; @@ -210,6 +211,7 @@ export function runOrchestratorV2ProviderReplayScenario< SqlClient.SqlClient, MigrationError | PlatformError.PlatformError | SqlError >; + readonly serverSettingsLayer?: Layer.Layer; readonly runEffectWorker?: boolean; readonly runContinuationWorker?: boolean; readonly recoverOnStartup?: boolean; @@ -256,6 +258,7 @@ export function layerProviderReplay; + readonly serverSettingsLayer?: Layer.Layer; readonly runEffectWorker?: boolean; readonly runContinuationWorker?: boolean; readonly recoverOnStartup?: boolean; @@ -293,6 +296,7 @@ export function layerWithRegistry( SqlClient.SqlClient, MigrationError | PlatformError.PlatformError | SqlError >; + readonly serverSettingsLayer?: Layer.Layer; readonly runEffectWorker?: boolean; readonly runContinuationWorker?: boolean; readonly recoverOnStartup?: boolean; @@ -352,19 +356,21 @@ export function layerWithRegistry( const layerProvidedRegistry = registryLayer.pipe( Layer.provide(Layer.merge(layerContinuationRequests, McpProviderSessions.layer)), ); - const layerServerSettings = Layer.unwrap( - Effect.map(ManagedPolicy.fromDocument("/test/policy.json", options.managedPolicy), (policy) => - ServerSettings.layerTest( - { - responseStreamingMode: "turn", - ...(options.continueThreadsAfterServerUpdate === undefined - ? {} - : { continueThreadsAfterServerUpdate: options.continueThreadsAfterServerUpdate }), - }, - policy.summary, + const layerServerSettings = + options.serverSettingsLayer ?? + Layer.unwrap( + Effect.map(ManagedPolicy.fromDocument("/test/policy.json", options.managedPolicy), (policy) => + ServerSettings.layerTest( + { + responseStreamingMode: "turn", + ...(options.continueThreadsAfterServerUpdate === undefined + ? {} + : { continueThreadsAfterServerUpdate: options.continueThreadsAfterServerUpdate }), + }, + policy.summary, + ), ), - ), - ).pipe(Layer.orDie); + ).pipe(Layer.orDie); const layerEffectOutboxProvided = EffectOutbox.layer.pipe(Layer.provide(layerDatabase)); const wrapProjectionStore = options.wrapProjectionStore; const layerProjectionStore = @@ -562,6 +568,7 @@ export function layerWithRegistry( layerProviderSwitchServiceProvided, layerRunExecutionServiceProvided, layerServerSettings, + RuntimeDecisionStore.layer.pipe(Layer.provide(layerDatabase)), TaskFolderStore.layer.pipe(Layer.provide(layerDatabase)), ThreadForkService.layer, ), diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index f37c06e1e63ff..b9956cf831094 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -290,7 +290,9 @@ it.effect("registers every migration file", () => // history and must be refused, not skipped past. describe("the fork's migration ledger", () => { const forkIds = [97, 98, 99, 100, 101, 102] as const; - const upstreamLater = migrationManifest.filter(([id]) => id > 102); + const upstreamLater = migrationManifest.filter( + ([id]) => id > 102 && id <= 118 + UPSTREAM_MIGRATION_ID_OFFSET, + ); const columns = (table: string) => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -338,6 +340,7 @@ describe("the fork's migration ledger", () => { const present = yield* tables; assert.isTrue(present.has("scheduled_task_occurrences"), "the fork's last migration ran"); assert.isTrue(present.has("issue_tracker_bindings"), "upstream's first later one ran"); + assert.isTrue(present.has("runtime_decisions"), "post-offset fork migration ran"); assert.deepStrictEqual(yield* runMigrations(), []); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 3f2d825909db6..1d82e57327437 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -135,6 +135,7 @@ import Migration0115 from "./Migrations/115_WorkflowRunTags.ts"; import Migration0116 from "./Migrations/116_ForkHistoryMembership.ts"; import Migration0117 from "./Migrations/117_WorkflowMailSender.ts"; import Migration0118 from "./Migrations/118_WorkflowPools.ts"; +import ForkMigration0125 from "./Migrations/125_RuntimeDecisions.ts"; /** * Closura: deployed fork databases record the fork's own migrations at ledger ids 97 to 102. @@ -269,6 +270,7 @@ const migrationEntries = [ [116 + UPSTREAM_MIGRATION_ID_OFFSET, "ForkHistoryMembership", Migration0116], [117 + UPSTREAM_MIGRATION_ID_OFFSET, "WorkflowMailSender", Migration0117], [118 + UPSTREAM_MIGRATION_ID_OFFSET, "WorkflowPools", Migration0118], + [125, "RuntimeDecisions", ForkMigration0125], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/125_RuntimeDecisions.ts b/apps/server/src/persistence/Migrations/125_RuntimeDecisions.ts new file mode 100644 index 0000000000000..a3ff77251b07e --- /dev/null +++ b/apps/server/src/persistence/Migrations/125_RuntimeDecisions.ts @@ -0,0 +1,53 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * Closura: append-only bot runtime decision log for inbound admission and placement (CLO-1368). + * Enforces the inbound-field shape and prevents updates or deletes at the database layer. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS runtime_decisions ( + at TEXT NOT NULL, + env TEXT NOT NULL, + thread TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('inbound', 'placement')), + event_kind TEXT, + recipient_founder_mission INTEGER CHECK ( + recipient_founder_mission IS NULL OR recipient_founder_mission IN (0, 1) + ), + input_digest TEXT NOT NULL, + decision TEXT NOT NULL, + reason TEXT NOT NULL, + enforced INTEGER NOT NULL CHECK (enforced IN (0, 1)), + CHECK ( + (kind = 'inbound' AND event_kind IS NOT NULL AND recipient_founder_mission IS NOT NULL) OR + (kind = 'placement' AND event_kind IS NULL AND recipient_founder_mission IS NULL) + ) + ) + `; + yield* sql` + CREATE INDEX IF NOT EXISTS runtime_decisions_kind_at + ON runtime_decisions (kind, at) + `; + yield* sql` + CREATE INDEX IF NOT EXISTS runtime_decisions_thread_at + ON runtime_decisions (thread, at) + `; + yield* sql` + CREATE TRIGGER IF NOT EXISTS runtime_decisions_no_update + BEFORE UPDATE ON runtime_decisions + BEGIN + SELECT RAISE(ABORT, 'runtime_decisions is append-only'); + END + `; + yield* sql` + CREATE TRIGGER IF NOT EXISTS runtime_decisions_no_delete + BEFORE DELETE ON runtime_decisions + BEGIN + SELECT RAISE(ABORT, 'runtime_decisions is append-only'); + END + `; +}); diff --git a/apps/server/src/persistence/RuntimeDecisions.test.ts b/apps/server/src/persistence/RuntimeDecisions.test.ts new file mode 100644 index 0000000000000..286a880ed4b12 --- /dev/null +++ b/apps/server/src/persistence/RuntimeDecisions.test.ts @@ -0,0 +1,157 @@ +import { assert, describe, it } from "@effect/vitest"; +import { computeRuntimeDecisionInputDigest } from "@t3tools/shared/inboundAdmission"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "./Migrations.ts"; +import * as RuntimeDecisions from "./RuntimeDecisions.ts"; + +const layerTest = RuntimeDecisions.layer.pipe( + Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })), +); + +describe("RuntimeDecisionStore", () => { + it.effect("appends inbound and placement decisions after audience filtering", () => + Effect.gen(function* () { + yield* runMigrations(); + const store = yield* RuntimeDecisions.RuntimeDecisionStore; + + const inboundWritten = yield* store.append( + { + at: "2026-12-04T04:00:00.000Z", + env: "env-r720", + thread: "thread-factory", + kind: "inbound", + eventKind: "status", + recipientFounderMission: true, + inputDigest: computeRuntimeDecisionInputDigest({ kind: "status", sender: "peer" }), + decision: "digest", + reason: "recipient holds a founder mission; status never starts a turn", + enforced: true, + }, + { audience: "kameron" }, + ); + assert.deepStrictEqual(inboundWritten, { written: true }); + + const placementWritten = yield* store.append( + { + at: "2026-12-04T04:00:01.000Z", + env: "env-r720", + thread: "thread-child-1", + kind: "placement", + eventKind: null, + recipientFounderMission: null, + inputDigest: computeRuntimeDecisionInputDigest({ placement: "auto" }), + decision: "placed:r720", + reason: "auto placed on headless executor", + enforced: false, + }, + { audience: "agent-only" }, + ); + assert.deepStrictEqual(placementWritten, { written: true }); + + const filteredAudience = yield* store.append( + { + at: "2026-12-04T04:00:02.000Z", + env: "env-r720", + thread: "thread-unknown", + kind: "inbound", + eventKind: "status", + recipientFounderMission: false, + inputDigest: computeRuntimeDecisionInputDigest({ kind: "status" }), + decision: "digest", + reason: "status never starts a turn", + enforced: true, + }, + { audience: "unrecognized-external" }, + ); + assert.deepStrictEqual(filteredAudience, { + written: false, + filteredReason: "unclassifiable_audience", + }); + + const forFactory = yield* store.listForThread("thread-factory"); + assert.strictEqual(forFactory.length, 1); + assert.strictEqual(forFactory[0]?.kind, "inbound"); + assert.strictEqual(forFactory[0]?.decision, "digest"); + assert.strictEqual(forFactory[0]?.enforced, true); + + const recentPlacement = yield* store.listRecent({ kind: "placement" }); + assert.strictEqual(recentPlacement.length, 1); + assert.strictEqual(recentPlacement[0]?.eventKind, null); + assert.strictEqual(recentPlacement[0]?.recipientFounderMission, null); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("enforces append-only triggers and M0 exact check 2 SQL query", () => + Effect.gen(function* () { + yield* runMigrations(); + const sql = yield* SqlClient.SqlClient; + const store = yield* RuntimeDecisions.RuntimeDecisionStore; + + yield* store.append({ + at: "2026-12-04T04:00:00.000Z", + env: "env-laptop", + thread: "thread-factory", + kind: "inbound", + eventKind: "status", + recipientFounderMission: true, + inputDigest: computeRuntimeDecisionInputDigest({ seq: 1 }), + decision: "digest", + reason: "recipient holds a founder mission; status never starts a turn", + enforced: true, + }); + yield* store.append({ + at: "2026-12-04T04:00:01.000Z", + env: "env-laptop", + thread: "thread-factory", + kind: "inbound", + eventKind: "pr_routine", + recipientFounderMission: true, + inputDigest: computeRuntimeDecisionInputDigest({ seq: 2 }), + decision: "log_only", + reason: "routine PR events never wake a thread", + enforced: true, + }); + + // Exact Check 2 query from Bot Runtime Plan Section 11. + const [check2] = yield* sql<{ readonly count: number }>` + SELECT count(*) AS count + FROM runtime_decisions + WHERE kind = 'inbound' + AND enforced = 1 + AND decision IN ('next_turn', 'when_idle', 'steer') + AND recipient_founder_mission = 1 + AND event_kind IN ('status', 'pr_routine') + `; + assert.strictEqual(check2?.count, 0); + + const updateExit = yield* Effect.exit( + sql`UPDATE runtime_decisions SET decision = 'next_turn' WHERE thread = 'thread-factory'`, + ); + assert.isTrue(Exit.isFailure(updateExit)); + + const deleteExit = yield* Effect.exit( + sql`DELETE FROM runtime_decisions WHERE thread = 'thread-factory'`, + ); + assert.isTrue(Exit.isFailure(deleteExit)); + + const invalidPlacementExit = yield* Effect.exit( + sql` + INSERT INTO runtime_decisions ( + at, env, thread, kind, event_kind, recipient_founder_mission, + input_digest, decision, reason, enforced + ) + VALUES ( + '2026-12-04T04:00:02.000Z', 'env-1', 't-1', 'placement', 'status', 1, + 'abc', 'placed:r720', 'bad', 1 + ) + `, + ); + assert.isTrue(Exit.isFailure(invalidPlacementExit)); + }).pipe(Effect.provide(layerTest)), + ); +}); diff --git a/apps/server/src/persistence/RuntimeDecisions.ts b/apps/server/src/persistence/RuntimeDecisions.ts new file mode 100644 index 0000000000000..d566bfcf19da5 --- /dev/null +++ b/apps/server/src/persistence/RuntimeDecisions.ts @@ -0,0 +1,194 @@ +import { + filterRuntimeDecisionForAudience, + type InboundDeliveryDecision, + type InboundEventKind, + type RuntimeDecisionAudienceContext, + type RuntimeDecisionKind, + type RuntimeDecisionRecord, +} from "@t3tools/shared/inboundAdmission"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { PersistenceSqlError } from "./Errors.ts"; + +export type RuntimeDecisionAppendResult = + | { readonly written: true } + | { readonly written: false; readonly filteredReason: string }; + +interface RuntimeDecisionRow { + readonly at: string; + readonly env: string; + readonly thread: string; + readonly kind: string; + readonly event_kind: string | null; + readonly recipient_founder_mission: number | null; + readonly input_digest: string; + readonly decision: string; + readonly reason: string; + readonly enforced: number; +} + +function toRecord(row: RuntimeDecisionRow): RuntimeDecisionRecord { + if (row.kind === "inbound") { + return { + at: row.at, + env: row.env, + thread: row.thread, + kind: "inbound", + eventKind: row.event_kind as InboundEventKind, + recipientFounderMission: row.recipient_founder_mission === 1, + inputDigest: row.input_digest, + decision: row.decision as InboundDeliveryDecision, + reason: row.reason, + enforced: row.enforced === 1, + }; + } + return { + at: row.at, + env: row.env, + thread: row.thread, + kind: "placement", + eventKind: null, + recipientFounderMission: null, + inputDigest: row.input_digest, + decision: row.decision, + reason: row.reason, + enforced: row.enforced === 1, + }; +} + +export class RuntimeDecisionStore extends Context.Service< + RuntimeDecisionStore, + { + readonly append: ( + record: RuntimeDecisionRecord, + audienceContext?: RuntimeDecisionAudienceContext, + ) => Effect.Effect; + readonly listForThread: ( + thread: string, + limit?: number, + ) => Effect.Effect, PersistenceSqlError>; + readonly listRecent: (options?: { + readonly kind?: RuntimeDecisionKind | undefined; + readonly limit?: number | undefined; + }) => Effect.Effect, PersistenceSqlError>; + } +>()("t3/persistence/RuntimeDecisions/RuntimeDecisionStore") {} + +function toSqlError(operation: string) { + return (cause: unknown) => new PersistenceSqlError({ operation, cause }); +} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + return RuntimeDecisionStore.of({ + append: Effect.fn("RuntimeDecisionStore.append")(function* (record, audienceContext) { + const filtered = filterRuntimeDecisionForAudience(record, audienceContext); + if (!filtered.allowed) { + return { written: false as const, filteredReason: filtered.reason }; + } + const row = filtered.record; + const eventKind = row.kind === "inbound" ? row.eventKind : null; + const recipientFounderMission = + row.kind === "inbound" ? (row.recipientFounderMission ? 1 : 0) : null; + const enforced = row.enforced ? 1 : 0; + yield* sql` + INSERT INTO runtime_decisions ( + at, + env, + thread, + kind, + event_kind, + recipient_founder_mission, + input_digest, + decision, + reason, + enforced + ) + VALUES ( + ${row.at}, + ${row.env}, + ${row.thread}, + ${row.kind}, + ${eventKind}, + ${recipientFounderMission}, + ${row.inputDigest}, + ${row.decision}, + ${row.reason}, + ${enforced} + ) + `.pipe(Effect.mapError(toSqlError("appendRuntimeDecision"))); + return { written: true as const }; + }), + listForThread: Effect.fn("RuntimeDecisionStore.listForThread")(function* (thread, limit = 100) { + const rows = yield* sql` + SELECT + at, + env, + thread, + kind, + event_kind, + recipient_founder_mission, + input_digest, + decision, + reason, + enforced + FROM runtime_decisions + WHERE thread = ${thread} + ORDER BY rowid ASC + LIMIT ${limit} + `.pipe( + NodeSqliteClient.readOnly, + Effect.mapError(toSqlError("listRuntimeDecisionsForThread")), + ); + return rows.map(toRecord); + }), + listRecent: Effect.fn("RuntimeDecisionStore.listRecent")(function* (options) { + const limit = options?.limit ?? 100; + const kind = options?.kind; + const rows = yield* ( + kind === undefined + ? sql` + SELECT + at, + env, + thread, + kind, + event_kind, + recipient_founder_mission, + input_digest, + decision, + reason, + enforced + FROM runtime_decisions + ORDER BY rowid DESC + LIMIT ${limit} + ` + : sql` + SELECT + at, + env, + thread, + kind, + event_kind, + recipient_founder_mission, + input_digest, + decision, + reason, + enforced + FROM runtime_decisions + WHERE kind = ${kind} + ORDER BY rowid DESC + LIMIT ${limit} + ` + ).pipe(NodeSqliteClient.readOnly, Effect.mapError(toSqlError("listRecentRuntimeDecisions"))); + return rows.map(toRecord); + }), + }); +}); + +export const layer = Layer.effect(RuntimeDecisionStore, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index b1927fab540bf..9da4a511baa0f 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -7,6 +7,7 @@ import * as AssetSigner from "./assets/AssetSigner.ts"; import * as WorkspacePreviewRevisions from "./assets/WorkspacePreviewRevisions.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; import * as EventSubscriptionStore from "./persistence/EventSubscriptions.ts"; +import * as RuntimeDecisionStore from "./persistence/RuntimeDecisions.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; @@ -991,6 +992,7 @@ const layerMakeRoutes = Layer.mergeAll( ), McpHttpServer.layer.pipe( Layer.provide(EventSubscriptionStore.layer), + Layer.provide(RuntimeDecisionStore.layer), Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry), Layer.provide(McpOAuth.layerMcpClientAuthenticator), Layer.provide(ProjectionStoreV2.layer), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 35182de25b9d4..e45c0f0ff5ff5 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -963,6 +963,22 @@ export const OrchestrationV2DeliveryClass = Schema.Literals([ ]); export type OrchestrationV2DeliveryClass = typeof OrchestrationV2DeliveryClass.Type; +export const OrchestrationV2InboundEventKind = Schema.Literals([ + "founder_message", + "decision_answer", + "handoff", + "child_result", + "review_finding", + "question", + "status", + "pr_actionable", + "pr_routine", + "alert", + "schedule", + "system_nudge", +]); +export type OrchestrationV2InboundEventKind = typeof OrchestrationV2InboundEventKind.Type; + export const OrchestrationV2DigestCategory = Schema.Literals([ "alert", "lane_result", @@ -4112,6 +4128,8 @@ export const OrchestrationV2Command = Schema.Union([ usageLimitRecoveryRequestId: Schema.optional(CommandId), deliveryIntent: Schema.optional(Schema.Literals(["auto", "steer", "restart"])), delivery: Schema.optional(OrchestrationV2MessageDelivery), + /** Closura: optional inbound admission event classification (CLO-1368). */ + inboundEventKind: Schema.optional(OrchestrationV2InboundEventKind), delegatedCompletion: Schema.optional( Schema.Struct({ parentRunId: RunId, diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 75a1a45550027..015294775c733 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -639,6 +639,7 @@ export const OrchestratorMcpThreadSendResult = Schema.Struct({ status: OrchestrationV2RunStatus, delivery: Schema.Literals(["started", "queued", "steered", "restarted"]), deliveryClass: Schema.optional(OrchestrationV2DeliveryClass), + deliveryReason: Schema.optional(Schema.String), }); export type OrchestratorMcpThreadSendResult = typeof OrchestratorMcpThreadSendResult.Type; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 64b6152aef34a..e1507933972d6 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1484,6 +1484,9 @@ export const CloudSpeechCredentials = Schema.Struct({ export const MachinePlacementRole = Schema.Literals(["auto", "headless", "interactive"]); export type MachinePlacementRole = typeof MachinePlacementRole.Type; +export const RuntimeEnforcementMode = Schema.Literals(["off", "observe", "enforce"]); +export type RuntimeEnforcementMode = typeof RuntimeEnforcementMode.Type; + export const AutomaticPlacementHost = Schema.Struct({ environmentId: EnvironmentId, maxLanes: NonNegativeInt, @@ -1693,6 +1696,14 @@ export const ServerSettings = Schema.Struct({ automaticPlacementHosts: Schema.Array(AutomaticPlacementHost).pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_AUTOMATIC_PLACEMENT_HOSTS)), ), + /** + * Closura: bot runtime enforcement mode for inbound admission and placement decisions (CLO-1368). + * `observe` (default) computes and logs audience-filtered decisions without capping delivery; + * `enforce` applies the inbound cap; `off` disables both logging and capping. + */ + runtimeEnforcement: RuntimeEnforcementMode.pipe( + Schema.withDecodingDefault(Effect.succeed("observe" as const)), + ), /** * The watcher thread. It hears a run that ran another model than selected, hit a provider * safeguard fallback or a usage limit. A failed unsettled top-level thread with no launcher @@ -2179,6 +2190,7 @@ export const ServerSettingsPatch = Schema.Struct({ machinePlacementRole: Schema.optionalKey(MachinePlacementRole), automaticPlacementByDefault: Schema.optionalKey(Schema.Boolean), automaticPlacementHosts: Schema.optionalKey(Schema.Array(AutomaticPlacementHost)), + runtimeEnforcement: Schema.optionalKey(RuntimeEnforcementMode), modelAlertWatcher: Schema.optionalKey(Schema.NullOr(ModelAlertWatcher)), modelAlertWebhookUrl: Schema.optionalKey(TrimmedString), watcherStuckMinutes: Schema.optionalKey( diff --git a/packages/shared/package.json b/packages/shared/package.json index 43f7248999b7c..b627f68862dd4 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -710,6 +710,10 @@ "./assistantInsights": { "types": "./src/assistantInsights.ts", "import": "./src/assistantInsights.ts" + }, + "./inboundAdmission": { + "types": "./src/inboundAdmission.ts", + "import": "./src/inboundAdmission.ts" } }, "scripts": { diff --git a/packages/shared/src/inboundAdmission.test.ts b/packages/shared/src/inboundAdmission.test.ts new file mode 100644 index 0000000000000..419a78b7ce7d0 --- /dev/null +++ b/packages/shared/src/inboundAdmission.test.ts @@ -0,0 +1,358 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { + admitInbound, + computeRuntimeDecisionInputDigest, + filterRuntimeDecisionForAudience, + isInReportsToChain, + normalizeSeatRoleKey, + type InboundEvent, + type InboundRecipient, + type InboundSenderRelation, +} from "./inboundAdmission.ts"; + +describe("admitInbound (M0 Inbound Cap v0)", () => { + describe("M0 exact check 1: Factory hijack sequence yields 0 turns", () => { + const factoryThread: InboundRecipient = { + kind: "founder_mission", + founderMission: true, + }; + + const ctoSends: ReadonlyArray<{ + readonly at: string; + readonly event: InboundEvent; + readonly sender: InboundSenderRelation; + }> = [ + { + at: "2026-12-01T21:34:05Z", + sender: "peer", + event: { + kind: "status", + itemKey: "pr:home:1681", + requestedClass: "next_turn", + }, + }, + { + at: "2026-12-01T21:45:29Z", + sender: "peer", + event: { + kind: "status", + itemKey: "pr:home:1681", + requestedClass: "when_idle", + }, + }, + { + at: "2026-12-01T22:11:32Z", + sender: "peer", + event: { + kind: "status", + itemKey: "pr:home:1681", + requestedClass: "steer_at_tool_boundary", + }, + }, + ]; + + it("caps all three CTO sends to the Software Factory founder thread at digest with 0 turns", () => { + const results = ctoSends.map(({ event, sender }) => + admitInbound(event, sender, factoryThread), + ); + + expect(results.filter((result) => result.wakesThread)).toHaveLength(0); + for (const result of results) { + expect(result.deliverAs).toBe("digest"); + expect(result.capped).toBe(true); + expect(result.coalesceKey).toBe("status:pr:home:1681"); + expect(result.reason).toContain("founder mission"); + expect(result.reason).toContain("status"); + } + }); + + it("also yields 0 turns for foreign PR events and manager handoffs on a founder-mission thread", () => { + const foreignPr = admitInbound( + { + kind: "pr_actionable", + itemKey: "pr:home:1681", + requestedClass: "next_turn", + authenticatedSystem: true, + prCovered: false, + }, + "system", + factoryThread, + ); + expect(foreignPr.wakesThread).toBe(false); + expect(foreignPr.deliverAs).toBe("log_only"); + + const managerHandoff = admitInbound( + { kind: "handoff", requestedClass: "steer_at_tool_boundary" }, + "chain", + factoryThread, + ); + expect(managerHandoff.wakesThread).toBe(false); + expect(managerHandoff.deliverAs).toBe("digest"); + expect(managerHandoff.capped).toBe(true); + }); + + it("still wakes a founder-mission thread for the founder, its own children, and its own PR", () => { + expect( + admitInbound( + { kind: "founder_message", requestedClass: "steer_at_tool_boundary" }, + "founder", + factoryThread, + ), + ).toMatchObject({ + deliverAs: "steer_at_tool_boundary", + wakesThread: true, + capped: false, + }); + + expect( + admitInbound({ kind: "child_result", requestedClass: "next_turn" }, "child", factoryThread), + ).toMatchObject({ + deliverAs: "next_turn", + wakesThread: true, + capped: false, + }); + + expect( + admitInbound( + { + kind: "pr_actionable", + itemKey: "pr:home:2001", + requestedClass: "next_turn", + authenticatedSystem: true, + prCovered: true, + }, + "system", + factoryThread, + ), + ).toMatchObject({ + deliverAs: "next_turn", + wakesThread: true, + capped: false, + coalesceKey: "pr:pr:home:2001", + }); + }); + }); + + describe("M0 exact check 1: Product Designer run 481 covered vs uncovered/routine PR watches", () => { + const productDesignerSeat: InboundRecipient = { + kind: "seat", + profile: "product-designer", + founderMission: false, + }; + + it("wakes the seat on an authenticated covered pr_actionable watch event", () => { + const result = admitInbound( + { + kind: "pr_actionable", + itemKey: "pr:product:481", + requestedClass: "next_turn", + authenticatedSystem: true, + prCovered: true, + }, + "system", + productDesignerSeat, + ); + + expect(result.wakesThread).toBe(true); + expect(result.deliverAs).toBe("next_turn"); + expect(result.capped).toBe(false); + }); + + it("yields 0 turns for an uncovered pr_actionable event and for pr_routine on its own PR", () => { + const uncovered = admitInbound( + { + kind: "pr_actionable", + itemKey: "pr:product:999", + requestedClass: "next_turn", + authenticatedSystem: true, + prCovered: false, + }, + "system", + productDesignerSeat, + ); + expect(uncovered.wakesThread).toBe(false); + expect(uncovered.deliverAs).toBe("log_only"); + + const routineOnOwnPr = admitInbound( + { + kind: "pr_routine", + itemKey: "pr:product:481", + requestedClass: "next_turn", + authenticatedSystem: true, + prCovered: true, + }, + "system", + productDesignerSeat, + ); + expect(routineOnOwnPr.wakesThread).toBe(false); + expect(routineOnOwnPr.deliverAs).toBe("log_only"); + + const unauthenticated = admitInbound( + { + kind: "pr_actionable", + itemKey: "pr:product:481", + requestedClass: "next_turn", + authenticatedSystem: false, + prCovered: true, + }, + "system", + productDesignerSeat, + ); + expect(unauthenticated.wakesThread).toBe(false); + expect(unauthenticated.deliverAs).toBe("log_only"); + + const spoofedByPeer = admitInbound( + { + kind: "pr_actionable", + itemKey: "pr:product:481", + requestedClass: "next_turn", + authenticatedSystem: true, + prCovered: true, + }, + "peer", + productDesignerSeat, + ); + expect(spoofedByPeer.wakesThread).toBe(false); + expect(spoofedByPeer.deliverAs).toBe("digest"); + }); + }); + + describe("M0 exact check 1: chain send to idle seat yields a turn", () => { + const platformSeat: InboundRecipient = { + kind: "seat", + profile: "platform-cto", + founderMission: false, + }; + + it("allows a reportsTo chain handoff to wake an idle seat", () => { + const result = admitInbound( + { kind: "handoff", requestedClass: "next_turn" }, + "chain", + platformSeat, + ); + expect(result.wakesThread).toBe(true); + expect(result.deliverAs).toBe("next_turn"); + expect(result.capped).toBe(false); + }); + + it("caps peer sends and even chain status messages at digest", () => { + const peerHandoff = admitInbound( + { kind: "handoff", requestedClass: "next_turn" }, + "peer", + platformSeat, + ); + expect(peerHandoff.wakesThread).toBe(false); + expect(peerHandoff.deliverAs).toBe("digest"); + expect(peerHandoff.capped).toBe(true); + + const chainStatus = admitInbound( + { kind: "status", requestedClass: "next_turn" }, + "chain", + platformSeat, + ); + expect(chainStatus.wakesThread).toBe(false); + expect(chainStatus.deliverAs).toBe("digest"); + expect(chainStatus.capped).toBe(true); + }); + + it("never upgrades a sender who already requested digest", () => { + const quietChain = admitInbound( + { kind: "handoff", requestedClass: "digest" }, + "chain", + platformSeat, + ); + expect(quietChain.deliverAs).toBe("digest"); + expect(quietChain.wakesThread).toBe(false); + expect(quietChain.capped).toBe(false); + }); + }); +}); + +describe("reportsTo chain resolution", () => { + it("resolves direct and transitive standing seat managers", () => { + expect(normalizeSeatRoleKey("Platform")).toBe("platform-cto"); + expect(isInReportsToChain("CTO", "Platform")).toBe(true); + expect(isInReportsToChain("CEO", "Platform")).toBe(true); + expect(isInReportsToChain("CEO", "CTO")).toBe(true); + expect(isInReportsToChain("Product / Site", "Product Designer")).toBe(true); + expect(isInReportsToChain("CEO", "Product Designer")).toBe(true); + }); + + it("rejects peers, subordinates, self, and cyclic maps", () => { + expect(isInReportsToChain("Platform", "CTO")).toBe(false); + expect(isInReportsToChain("CoS", "CTO")).toBe(false); + expect(isInReportsToChain("Ops Bus", "CTO")).toBe(false); + expect(isInReportsToChain("CTO", "CTO")).toBe(false); + expect(isInReportsToChain("a", "b", { a: "b", b: "a" })).toBe(true); + expect(isInReportsToChain("c", "b", { a: "b", b: "a" })).toBe(false); + }); +}); + +describe("runtime decision audience filter and digest", () => { + const baseInbound = { + at: "2026-12-04T04:00:00.000Z", + env: "env-1", + thread: "thread-1", + kind: "inbound" as const, + eventKind: "status" as const, + recipientFounderMission: true, + inputDigest: computeRuntimeDecisionInputDigest({ b: 2, a: 1 }), + decision: "digest" as const, + reason: "recipient holds a founder mission; status never starts a turn", + enforced: true, + }; + + it("allows known company audiences including both founders and agent-only", () => { + for (const audience of ["kameron", "jeff", "shared", "agent-only", null, undefined] as const) { + expect(filterRuntimeDecisionForAudience(baseInbound, { audience }).allowed).toBe(true); + } + }); + + it("fails closed on unknown audiences, secret markers, and malformed placement rows", () => { + expect( + filterRuntimeDecisionForAudience(baseInbound, { audience: "external-customer" }), + ).toEqual({ + allowed: false, + reason: "unclassifiable_audience", + }); + + expect( + filterRuntimeDecisionForAudience(baseInbound, { + audience: "shared", + containsSecretOrCustomerData: true, + }), + ).toEqual({ + allowed: false, + reason: "contains_secret_or_customer_data", + }); + + expect( + filterRuntimeDecisionForAudience({ + ...baseInbound, + reason: "leaked Bearer abcdefghijklmnop12345", + }), + ).toEqual({ + allowed: false, + reason: "sensitive_pattern_in_reason", + }); + + expect( + filterRuntimeDecisionForAudience({ + ...baseInbound, + kind: "placement", + eventKind: null, + recipientFounderMission: null, + decision: "placed:r720", + reason: "auto placed on headless executor", + }).allowed, + ).toBe(true); + }); + + it("produces deterministic SHA-256 hex digests independent of key order", () => { + const d1 = computeRuntimeDecisionInputDigest({ a: 1, b: "two" }); + const d2 = computeRuntimeDecisionInputDigest({ b: "two", a: 1 }); + expect(d1).toBe(d2); + expect(d1).toMatch(/^[0-9a-f]{64}$/); + }); +}); diff --git a/packages/shared/src/inboundAdmission.ts b/packages/shared/src/inboundAdmission.ts new file mode 100644 index 0000000000000..7eedece7e7159 --- /dev/null +++ b/packages/shared/src/inboundAdmission.ts @@ -0,0 +1,458 @@ +import { sha256 } from "@noble/hashes/sha2"; +import type { OrchestrationV2DeliveryClass } from "@t3tools/contracts"; + +const INBOUND_EVENT_KINDS = [ + "founder_message", + "decision_answer", + "handoff", + "child_result", + "review_finding", + "question", + "status", + "pr_actionable", + "pr_routine", + "alert", + "schedule", + "system_nudge", +] as const; +export type InboundEventKind = (typeof INBOUND_EVENT_KINDS)[number]; + +const INBOUND_SENDER_RELATIONS = [ + "founder", + "chain", + "delegator", + "child", + "reviewer", + "peer", + "system", +] as const; +export type InboundSenderRelation = (typeof INBOUND_SENDER_RELATIONS)[number]; + +export type InboundDeliveryDecision = OrchestrationV2DeliveryClass | "log_only"; + +export type RuntimeDecisionKind = "inbound" | "placement"; + +export type RuntimeEnforcementMode = "off" | "observe" | "enforce"; + +export type InboundRecipientKind = "founder_mission" | "seat" | "worker" | "ordinary"; + +export interface InboundEvent { + readonly kind: InboundEventKind; + readonly itemKey?: string | undefined; + readonly severity?: "low" | "normal" | "high" | "critical" | undefined; + readonly requestedClass?: OrchestrationV2DeliveryClass | undefined; + readonly coalesceKey?: string | undefined; + /** True only when authenticated by T3 server/system code, never from a peer sender. */ + readonly authenticatedSystem?: boolean | undefined; + /** True when the PR was opened/linked by the founder thread or covered by the seat's active watch. */ + readonly prCovered?: boolean | undefined; +} + +export interface InboundRecipient { + readonly kind?: InboundRecipientKind | undefined; + readonly profile?: string | undefined; + readonly focus?: string | undefined; + readonly parked?: ReadonlyArray | undefined; + readonly founderMission: boolean; +} + +export interface InboundAdmissionResult { + readonly deliverAs: InboundDeliveryDecision; + readonly requestedAs: OrchestrationV2DeliveryClass; + readonly capped: boolean; + readonly wakesThread: boolean; + readonly coalesceKey?: string | undefined; + readonly reason: string; +} + +const DELIVERY_CLASS_RANK: Readonly> = { + log_only: 0, + digest: 1, + when_idle: 2, + next_turn: 3, + steer_at_tool_boundary: 4, + interrupt: 5, +}; + +/** + * Closura: default standing-seat reporting chain mirrored from `config/standing-threads.json`. + * Used by M0 Inbound Cap v0 to distinguish `chain` senders from `peer` senders on standing seats. + */ +const DEFAULT_SEAT_REPORTS_TO: Readonly> = { + cos: "kameron", + ceo: "kameron", + cto: "ceo", + cfo: "ceo", + growth: "ceo", + "product-site": "ceo", + "product-designer": "product-site", + "arc-ops": "cto", + "platform-cto": "cto", + "ops-bus": "cto", + "release-engineer": "cto", + "pr-reviewer": "cto", +}; + +const SEAT_ROLE_ALIASES: Readonly> = { + cos: "cos", + "chief of staff": "cos", + "chief-of-staff": "cos", + cto: "cto", + ceo: "ceo", + cfo: "cfo", + "product designer": "product-designer", + "product-designer": "product-designer", + designer: "product-designer", + "arc ops": "arc-ops", + "arc-ops": "arc-ops", + infra: "arc-ops", + "infra / arc ops": "arc-ops", + "infra/arc ops": "arc-ops", + "cos (jeff)": "cos-jeff", + "jeff-cos": "cos-jeff", + "cos-jeff": "cos-jeff", + "personal finance": "personal-finance", + "personal-finance": "personal-finance", + growth: "growth", + gardening: "gardening", + "product / site": "product-site", + "product site": "product-site", + "product-site": "product-site", + platform: "platform-cto", + "platform / cto": "platform-cto", + "platform cto": "platform-cto", + "platform-cto": "platform-cto", + "ops bus": "ops-bus", + "ops-bus": "ops-bus", + "status bus": "ops-bus", + "release engineer": "release-engineer", + "release-engineer": "release-engineer", + "pr reviewer": "pr-reviewer", + "pr-reviewer": "pr-reviewer", +}; + +export function normalizeSeatRoleKey(nameOrRole: string | null | undefined): string | null { + if (nameOrRole == null) return null; + const normalized = nameOrRole.trim().toLowerCase().replace(/\s+/g, " "); + if (normalized.length === 0) return null; + return SEAT_ROLE_ALIASES[normalized] ?? normalized.replace(/\s+/g, "-"); +} + +/** + * Walk `reportsTo` upward from `recipientRole` (with cycle guard) and report whether `senderRole` + * sits above the recipient in its reporting chain. + */ +export function isInReportsToChain( + senderNameOrRole: string | null | undefined, + recipientNameOrRole: string | null | undefined, + reportsToMap: Readonly> = DEFAULT_SEAT_REPORTS_TO, +): boolean { + const sender = normalizeSeatRoleKey(senderNameOrRole); + const recipient = normalizeSeatRoleKey(recipientNameOrRole); + if (sender === null || recipient === null || sender === recipient) return false; + const visited = new Set([recipient]); + let current: string | undefined = reportsToMap[recipient]; + while (current !== undefined) { + const manager = normalizeSeatRoleKey(current); + if (manager === null || visited.has(manager)) return false; + if (manager === sender) return true; + visited.add(manager); + current = reportsToMap[manager]; + } + return false; +} + +function wakesThreadForDecision(decision: InboundDeliveryDecision): boolean { + return decision !== "digest" && decision !== "log_only"; +} + +function capDeliveryClass( + requested: OrchestrationV2DeliveryClass, + maxAllowed: InboundDeliveryDecision, +): InboundDeliveryDecision { + return DELIVERY_CLASS_RANK[requested] <= DELIVERY_CLASS_RANK[maxAllowed] ? requested : maxAllowed; +} + +function resolveDecision( + requestedAs: OrchestrationV2DeliveryClass, + maxAllowed: InboundDeliveryDecision, + reason: string, + coalesceKey?: string, +): InboundAdmissionResult { + const deliverAs = capDeliveryClass(requestedAs, maxAllowed); + const capped = DELIVERY_CLASS_RANK[deliverAs] < DELIVERY_CLASS_RANK[requestedAs]; + return { + deliverAs, + requestedAs, + capped, + wakesThread: wakesThreadForDecision(deliverAs), + ...(coalesceKey === undefined ? {} : { coalesceKey }), + reason, + }; +} + +/** + * Inbound Cap v0: recipient-side delivery admission. + * Status and routine PR events never wake; covered system `pr_actionable` evaluates before generic + * seat/founder-mission caps; all other non-allowlisted senders cap at `digest`. + */ +export function admitInbound( + event: InboundEvent, + sender: InboundSenderRelation, + recipient: InboundRecipient, +): InboundAdmissionResult { + const requestedAs = event.requestedClass ?? "next_turn"; + const isFounderMission = recipient.founderMission || recipient.kind === "founder_mission"; + const isSeat = !isFounderMission && recipient.kind === "seat"; + + if (event.kind === "status") { + const coalesceKey = + event.coalesceKey ?? (event.itemKey ? `status:${event.itemKey}` : undefined); + const reason = isFounderMission + ? "recipient holds a founder mission; status never starts a turn" + : "status never starts a turn"; + return resolveDecision(requestedAs, "digest", reason, coalesceKey); + } + + if (event.kind === "pr_routine") { + return resolveDecision(requestedAs, "log_only", "routine PR events never wake a thread"); + } + + if (event.kind === "pr_actionable") { + if (sender === "system" && event.authenticatedSystem === true && event.prCovered === true) { + const coalesceKey = event.coalesceKey ?? (event.itemKey ? `pr:${event.itemKey}` : undefined); + const reason = isFounderMission + ? "authenticated actionable PR event on founder thread PR" + : "authenticated actionable PR event covered by seat watch"; + return resolveDecision(requestedAs, "next_turn", reason, coalesceKey); + } + if (sender === "system") { + const reason = + event.authenticatedSystem !== true + ? "unauthenticated system PR event cannot wake a thread" + : "system PR event is not covered by the thread's PR or active watch"; + return resolveDecision(requestedAs, "log_only", reason); + } + return resolveDecision( + requestedAs, + "digest", + "non-system PR events cannot wake a thread; capped at digest", + event.coalesceKey, + ); + } + + if (event.kind === "system_nudge") { + return resolveDecision( + requestedAs, + "digest", + "system_nudge is capped at digest and never wakes a thread", + event.coalesceKey, + ); + } + + if (event.kind === "question") { + return resolveDecision( + requestedAs, + "digest", + "questions use ask_agent rather than starting a turn; capped at digest", + event.coalesceKey, + ); + } + + if (isFounderMission) { + if (sender === "founder") { + return resolveDecision( + requestedAs, + requestedAs, + "founder message to founder-mission thread", + event.coalesceKey, + ); + } + if (sender === "child") { + return resolveDecision( + requestedAs, + "steer_at_tool_boundary", + "own child delivery to founder-mission thread", + event.coalesceKey, + ); + } + return resolveDecision( + requestedAs, + "digest", + "recipient holds a founder mission; only the founder, own children, or covered system PR events may wake it", + event.coalesceKey, + ); + } + + if (isSeat) { + if (sender === "founder") { + return resolveDecision( + requestedAs, + requestedAs, + "founder message to standing seat", + event.coalesceKey, + ); + } + if (sender === "chain") { + return resolveDecision( + requestedAs, + "steer_at_tool_boundary", + "reportsTo chain message to standing seat", + event.coalesceKey, + ); + } + if (sender === "child") { + return resolveDecision( + requestedAs, + "steer_at_tool_boundary", + "own child delivery to standing seat", + event.coalesceKey, + ); + } + if (event.kind === "schedule" && sender === "system" && event.authenticatedSystem === true) { + return resolveDecision( + requestedAs, + "when_idle", + "authenticated scheduled task for standing seat", + event.coalesceKey, + ); + } + const reason = + sender === "peer" + ? "peer messages to a seat are capped at digest; only founders, the reportsTo chain, own children, or covered system PR watches may wake it" + : "sender is outside the seat's waking allowlist; capped at digest"; + return resolveDecision(requestedAs, "digest", reason, event.coalesceKey); + } + + if (sender === "founder" || sender === "chain" || sender === "delegator" || sender === "child") { + return resolveDecision( + requestedAs, + sender === "founder" ? requestedAs : "steer_at_tool_boundary", + `${sender} delivery to thread`, + event.coalesceKey, + ); + } + + if (event.kind === "schedule" && sender === "system" && event.authenticatedSystem === true) { + return resolveDecision( + requestedAs, + "when_idle", + "authenticated scheduled task for thread", + event.coalesceKey, + ); + } + + return resolveDecision( + requestedAs, + "digest", + "sender is outside the thread's waking allowlist; capped at digest", + event.coalesceKey, + ); +} + +const KNOWN_COMPANY_AUDIENCES: ReadonlySet = new Set([ + "kameron", + "jeff", + "shared", + "agent-only", +]); + +const SENSITIVE_CONTENT_PATTERNS: ReadonlyArray = [ + /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/i, + /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/, + /\bgithub_pat_[A-Za-z0-9_]{20,}/, + /\b(?:sk|pk)_(?:live|test)_[A-Za-z0-9]{16,}/, + /\bsk-[A-Za-z0-9]{20,}/, + /\blin_api_[A-Za-z0-9]{20,}/, + /-----BEGIN [A-Z ]+ PRIVATE KEY-----/, +]; + +export type RuntimeDecisionRecord = + | { + readonly at: string; + readonly env: string; + readonly thread: string; + readonly kind: "inbound"; + readonly eventKind: InboundEventKind; + readonly recipientFounderMission: boolean; + readonly inputDigest: string; + readonly decision: InboundDeliveryDecision; + readonly reason: string; + readonly enforced: boolean; + } + | { + readonly at: string; + readonly env: string; + readonly thread: string; + readonly kind: "placement"; + readonly eventKind: null; + readonly recipientFounderMission: null; + readonly inputDigest: string; + readonly decision: string; + readonly reason: string; + readonly enforced: boolean; + }; + +export interface RuntimeDecisionAudienceContext { + readonly audience?: string | null | undefined; + readonly containsSecretOrCustomerData?: boolean | undefined; +} + +export type RuntimeDecisionFilterResult = + | { readonly allowed: true; readonly record: RuntimeDecisionRecord } + | { readonly allowed: false; readonly reason: string }; + +/** + * Audience & classification filter applied before appending to `runtime_decisions` (CLO-1368 I8). + * Fails closed on unknown audiences, secret/customer-data markers, or malformed inbound fields. + */ +export function filterRuntimeDecisionForAudience( + record: RuntimeDecisionRecord, + context: RuntimeDecisionAudienceContext = {}, +): RuntimeDecisionFilterResult { + if (context.containsSecretOrCustomerData === true) { + return { allowed: false, reason: "contains_secret_or_customer_data" }; + } + if ( + context.audience !== undefined && + context.audience !== null && + !KNOWN_COMPANY_AUDIENCES.has(context.audience) + ) { + return { allowed: false, reason: "unclassifiable_audience" }; + } + if (record.kind === "inbound") { + if (!(INBOUND_EVENT_KINDS as readonly string[]).includes(record.eventKind)) { + return { allowed: false, reason: "unclassifiable_event_kind" }; + } + } else if (record.eventKind !== null || record.recipientFounderMission !== null) { + return { allowed: false, reason: "placement_record_has_inbound_fields" }; + } + const boundedReason = record.reason.trim(); + if (boundedReason.length === 0 || boundedReason.length > 512) { + return { allowed: false, reason: "unbounded_reason" }; + } + if (SENSITIVE_CONTENT_PATTERNS.some((pattern) => pattern.test(boundedReason))) { + return { allowed: false, reason: "sensitive_pattern_in_reason" }; + } + return { + allowed: true, + record: + record.kind === "inbound" + ? { ...record, reason: boundedReason } + : { ...record, reason: boundedReason }, + }; +} + +/** Deterministic SHA-256 hex digest of structured admission inputs (never raw message text). */ +export function computeRuntimeDecisionInputDigest( + input: Readonly>, +): string { + const canonicalKeys = Object.keys(input).sort(); + const normalized: Record = {}; + for (const key of canonicalKeys) { + const value = input[key]; + if (value !== undefined) normalized[key] = value; + } + const bytes = sha256(new TextEncoder().encode(JSON.stringify(normalized))); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); +} From ca33e76bc9408250fbb6f62730212634a88d4370 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 4 Dec 2026 06:57:10 +0000 Subject: [PATCH 2/3] fix(server): address PR #264 inbound admission review findings (CLO-1368) Address clean-room review findings F1-F4 on the M0 inbound admission cap: - F1: match pullRequestWatch 'new comments' and 'checks await approval' summaries as pr_actionable. - F2: add 'gardening: cto' to DEFAULT_SEAT_REPORTS_TO. - F3: downgrade restart_active to steer_active when applyInboundAdmissionToCommand caps interrupt to steer_at_tool_boundary. - F4: omit capped deliveryReason in t3_thread_send when runtimeEnforcement is observe (enforced=false) so it does not contradict the uncapped deliveryClass. Model: gemini-4-neon Task: fix Agent: Builder Harness: t3/antigravity Model-family: Gemini Model-generation: 4 Neon Skills-SHA: nullStack65/closura-agent-config@da5f66450f9d69207369395f7a30686834767453; skills/github-repository-ops/SKILL.md (sha256:e3778c3a953bfa9e7bf5c9b9609b6d6c947cffa03366b3bc0f75bbb722b76784, installed matches source) Refs: CLO-1368 --- .../OrchestratorMcpService.activity.test.ts | 138 ++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 6 +- .../orchestration-v2/InboundAdmission.test.ts | 135 +++++++++++++++++ .../src/orchestration-v2/InboundAdmission.ts | 18 ++- packages/shared/src/inboundAdmission.test.ts | 4 + packages/shared/src/inboundAdmission.ts | 1 + 6 files changed, 294 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 9026133520828..36e998eca6b46 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -1777,3 +1777,141 @@ it("requestSecret delivers a fields card as one file per field", async () => { }); }).pipe(Effect.provide(layer), Effect.runPromise); }); + +it("sendToThread omits capped deliveryReason in observe mode and reports it when enforced", async () => { + const targetThreadId = ThreadId.make("thread-mcp-delivery-reason"); + const parentProjection = { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], + visibleTurnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + const targetProjection = { + thread: baseThread({ + threadId: targetThreadId, + title: "Founder Mission", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [], + visibleTurnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + + const responses: Array = [ + { + run: { id: "run-observe-capped", status: "running", delivery: { class: "next_turn" } }, + delivery: "started", + inboundAdmission: { + deliverAs: "digest", + requestedAs: "next_turn", + capped: true, + wakesThread: false, + enforced: false, + reason: "recipient holds a founder mission; status never starts a turn", + }, + } as unknown as ThreadManagementService.ThreadManagementSendResult, + { + run: { id: "run-observe-uncapped", status: "running", delivery: { class: "next_turn" } }, + delivery: "started", + inboundAdmission: { + deliverAs: "next_turn", + requestedAs: "next_turn", + capped: false, + wakesThread: true, + enforced: false, + reason: "chain handoff wakes idle seat", + }, + } as unknown as ThreadManagementService.ThreadManagementSendResult, + { + run: { id: "run-enforce-capped", status: "queued", delivery: { class: "digest" } }, + delivery: "queued", + inboundAdmission: { + deliverAs: "digest", + requestedAs: "next_turn", + capped: true, + wakesThread: false, + enforced: true, + reason: "recipient holds a founder mission; status never starts a turn", + }, + } as unknown as ThreadManagementService.ThreadManagementSendResult, + ]; + let callIndex = 0; + + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (threadId) => + Effect.succeed(threadId === targetThreadId ? targetProjection : parentProjection), + getProjectThreadRecords: (input) => + Effect.succeed(input.threadId === targetThreadId ? targetProjection : parentProjection), + getThreadShell: (threadId) => + Effect.succeed( + (threadId === targetThreadId + ? targetProjection.thread + : parentProjection.thread) as unknown as OrchestrationV2ThreadShell, + ), + sendToThread: () => Effect.succeed(responses[callIndex++]!), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + } satisfies Partial), + NodeCrypto.layer, + ), + ), + ); + + await Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + + const observedCapped = yield* service.sendToThread(makeScope(), { + threadId: targetThreadId, + message: "status update", + deliveryClass: "next_turn", + }); + expect(observedCapped.deliveryClass).toBe("next_turn"); + expect(observedCapped.deliveryReason).toBeUndefined(); + + const observedUncapped = yield* service.sendToThread(makeScope(), { + threadId: targetThreadId, + message: "handoff", + deliveryClass: "next_turn", + }); + expect(observedUncapped.deliveryClass).toBe("next_turn"); + expect(observedUncapped.deliveryReason).toBe("chain handoff wakes idle seat"); + + const enforcedCapped = yield* service.sendToThread(makeScope(), { + threadId: targetThreadId, + message: "status update", + deliveryClass: "next_turn", + }); + expect(enforcedCapped.deliveryClass).toBe("digest"); + expect(enforcedCapped.deliveryReason).toBe( + "recipient holds a founder mission; status never starts a turn", + ); + }).pipe(Effect.provide(layer), Effect.runPromise); +}); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 16dd0df33162c..f99d3896bcd99 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -4081,7 +4081,11 @@ const make = Effect.gen(function* () { result.inboundAdmission.deliverAs !== "log_only" ? result.inboundAdmission.deliverAs : deliveryClass); - const deliveryReason = result.inboundAdmission?.reason; + const deliveryReason = + result.inboundAdmission !== undefined && + (result.inboundAdmission.enforced || !result.inboundAdmission.capped) + ? result.inboundAdmission.reason + : undefined; return { threadId: liveThreadId, link: threadLinkFor(scope, liveThreadId, target.thread.title), diff --git a/apps/server/src/orchestration-v2/InboundAdmission.test.ts b/apps/server/src/orchestration-v2/InboundAdmission.test.ts index 9d6d2a15bc270..31831e81b8fba 100644 --- a/apps/server/src/orchestration-v2/InboundAdmission.test.ts +++ b/apps/server/src/orchestration-v2/InboundAdmission.test.ts @@ -5,6 +5,7 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + RunId, ThreadId, } from "@t3tools/contracts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -16,6 +17,7 @@ import * as RuntimeDecisions from "../persistence/RuntimeDecisions.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ServerSettings from "../serverSettings.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import { applyInboundAdmissionToCommand } from "./InboundAdmission.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; @@ -476,4 +478,137 @@ it.layer(layerTest)("M0 inbound admission and runtime_decisions", (it) => { assert.strictEqual(exactCheck2?.count, 0); }), ); + + it.effect( + "classifies pullRequestWatch new comments and checks await approval summaries as actionable", + () => + Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const decisions = yield* RuntimeDecisions.RuntimeDecisionStore; + + yield* settings.updateSettings({ runtimeEnforcement: "enforce" }); + + const reviewerId = ThreadId.make("thread:enforce-pr-summaries"); + yield* createThread({ + threadId: reviewerId, + title: "PR Reviewer", + createdBy: "agent", + standing: { + name: "PR Reviewer", + role: "Code Review", + avatarId: "visor", + accent: "sky", + }, + audience: "shared", + }); + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("reviewer:watch-482"), + threadId: reviewerId, + host: "github.com", + repository: "nullStack65/Closura", + number: 482, + watching: true, + link: { + url: "https://github.com/nullStack65/Closura/pull/482", + source: "manual", + }, + }); + + const dispatchMonitor = (tag: string, outcome: "completed" | "updated", summary: string) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`reviewer:${tag}`), + threadId: reviewerId, + messageId: MessageId.make(`msg:reviewer:${tag}`), + text: `Update on pull request: ${summary}`, + notification: { + source: { + kind: "monitor", + pullRequest: { + host: "github.com", + repository: "nullStack65/Closura", + number: 482, + watchStartedAt: "2026-12-01T20:00:00.000Z", + headSha: "2222222", + }, + }, + outcome, + summary, + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + + const routine = yield* dispatchMonitor("passed", "completed", "#482: checks passed"); + assert.strictEqual(routine.inboundAdmission?.deliverAs, "log_only"); + assert.strictEqual(routine.inboundAdmission?.wakesThread, false); + + const remarks = yield* dispatchMonitor("remarks", "updated", "#482: new comments"); + assert.strictEqual(remarks.inboundAdmission?.deliverAs, "next_turn"); + assert.strictEqual(remarks.inboundAdmission?.wakesThread, true); + + const approval = yield* dispatchMonitor( + "approval", + "updated", + "#482: checks await approval", + ); + assert.strictEqual(approval.inboundAdmission?.deliverAs, "next_turn"); + assert.strictEqual(approval.inboundAdmission?.wakesThread, true); + + const rows = yield* decisions.listForThread(reviewerId); + assert.deepStrictEqual( + rows.map((row) => [row.eventKind, row.decision]), + [ + ["pr_routine", "log_only"], + ["pr_actionable", "next_turn"], + ["pr_actionable", "next_turn"], + ], + ); + }), + ); + + it("downgrades restart_active to steer_active when capped to steer_at_tool_boundary", () => { + const targetRunId = RunId.make("run:active-1"); + const command = { + type: "message.dispatch" as const, + commandId: CommandId.make("cap:restart-to-steer"), + threadId: ThreadId.make("thread:cap-target"), + messageId: MessageId.make("msg:cap-restart"), + text: "Interrupt requested by child", + attachments: [], + delivery: { class: "interrupt" as const }, + deliveryIntent: "restart" as const, + dispatchMode: { type: "restart_active" as const, targetRunId }, + createdBy: "agent" as const, + creationSource: "mcp" as const, + }; + + const steered = applyInboundAdmissionToCommand(command, { + deliverAs: "steer_at_tool_boundary", + requestedAs: "interrupt", + capped: true, + wakesThread: true, + reason: "child result capped at steer_at_tool_boundary", + }); + assert.deepStrictEqual(steered.dispatchMode, { type: "steer_active", targetRunId }); + assert.strictEqual(steered.delivery?.class, "steer_at_tool_boundary"); + assert.strictEqual(steered.deliveryIntent, undefined); + + const digested = applyInboundAdmissionToCommand(command, { + deliverAs: "digest", + requestedAs: "interrupt", + capped: true, + wakesThread: false, + coalesceKey: "status:item", + reason: "peer status capped at digest", + }); + assert.deepStrictEqual(digested.dispatchMode, { type: "queue_after_active" }); + assert.strictEqual(digested.delivery?.class, "digest"); + assert.strictEqual(digested.delivery?.coalesceKey, "status:item"); + assert.strictEqual(digested.deliveryIntent, undefined); + }); }); diff --git a/apps/server/src/orchestration-v2/InboundAdmission.ts b/apps/server/src/orchestration-v2/InboundAdmission.ts index fa3873ba3c0d8..5b45a85621006 100644 --- a/apps/server/src/orchestration-v2/InboundAdmission.ts +++ b/apps/server/src/orchestration-v2/InboundAdmission.ts @@ -85,7 +85,7 @@ function classifyInboundRecipient( } const ACTIONABLE_PR_SUMMARY_RE = - /\b(merged|closed|changes requested|comment|conflict|rebase|failed|failing|removed from merge queue|stopped watching|no observed progress|awaiting approval)\b/i; + /\b(merged|closed|changes requested|comments?|conflict|rebase|failed|failing|removed from merge queue|stopped watching|no observed progress|await(?:ing)? approval)\b/i; function classifyMonitorPullRequestEvent( notification: OrchestrationV2Notification, @@ -366,15 +366,19 @@ export function applyInboundAdmissionToCommand( : {}), }; const { deliveryIntent: _droppedIntent, ...withoutIntent } = command; + const dispatchMode = + admission.deliverAs === "digest" || + admission.deliverAs === "next_turn" || + admission.deliverAs === "when_idle" + ? ({ type: "queue_after_active" } as const) + : admission.deliverAs === "steer_at_tool_boundary" && + command.dispatchMode.type === "restart_active" + ? ({ type: "steer_active", targetRunId: command.dispatchMode.targetRunId } as const) + : command.dispatchMode; return { ...withoutIntent, delivery, - dispatchMode: - admission.deliverAs === "digest" || - admission.deliverAs === "next_turn" || - admission.deliverAs === "when_idle" - ? { type: "queue_after_active" as const } - : command.dispatchMode, + dispatchMode, }; } diff --git a/packages/shared/src/inboundAdmission.test.ts b/packages/shared/src/inboundAdmission.test.ts index 419a78b7ce7d0..936b642ff46ee 100644 --- a/packages/shared/src/inboundAdmission.test.ts +++ b/packages/shared/src/inboundAdmission.test.ts @@ -272,8 +272,11 @@ describe("admitInbound (M0 Inbound Cap v0)", () => { describe("reportsTo chain resolution", () => { it("resolves direct and transitive standing seat managers", () => { expect(normalizeSeatRoleKey("Platform")).toBe("platform-cto"); + expect(normalizeSeatRoleKey("Gardening")).toBe("gardening"); expect(isInReportsToChain("CTO", "Platform")).toBe(true); expect(isInReportsToChain("CEO", "Platform")).toBe(true); + expect(isInReportsToChain("CTO", "Gardening")).toBe(true); + expect(isInReportsToChain("CEO", "Gardening")).toBe(true); expect(isInReportsToChain("CEO", "CTO")).toBe(true); expect(isInReportsToChain("Product / Site", "Product Designer")).toBe(true); expect(isInReportsToChain("CEO", "Product Designer")).toBe(true); @@ -281,6 +284,7 @@ describe("reportsTo chain resolution", () => { it("rejects peers, subordinates, self, and cyclic maps", () => { expect(isInReportsToChain("Platform", "CTO")).toBe(false); + expect(isInReportsToChain("Gardening", "CTO")).toBe(false); expect(isInReportsToChain("CoS", "CTO")).toBe(false); expect(isInReportsToChain("Ops Bus", "CTO")).toBe(false); expect(isInReportsToChain("CTO", "CTO")).toBe(false); diff --git a/packages/shared/src/inboundAdmission.ts b/packages/shared/src/inboundAdmission.ts index 7eedece7e7159..5cb96e39c4fb7 100644 --- a/packages/shared/src/inboundAdmission.ts +++ b/packages/shared/src/inboundAdmission.ts @@ -91,6 +91,7 @@ const DEFAULT_SEAT_REPORTS_TO: Readonly> = { "ops-bus": "cto", "release-engineer": "cto", "pr-reviewer": "cto", + gardening: "cto", }; const SEAT_ROLE_ALIASES: Readonly> = { From 18436729ac06d036b738faaa8afe5a2ac71a7f1f Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:17:43 +0000 Subject: [PATCH 3/3] fix(server): bypass provider wakes in inbound admission and isolate fork migration ledger (CLO-1368) Address clean-room review 2/2 (Opus) findings on PR #264: - Opus F1: bypass inbound admission for a thread's own provider continuations (creationSource === 'provider' or commandId starting with 'provider-continuation:'), and only classify monitor notifications with a PR stamp (pullRequest / otherPullRequests) or 'message:pr-watch:' prefix as pr_actionable/pr_routine so background_task and non-PR monitor wakes pass through as child/child_result under enforce. - Opus F2: move RuntimeDecisions out of effect_sql_migrations (avoiding collision with upstream 119_WorkflowRunSubject under the +6 offset) into Migrations/fork/001_RuntimeDecisions.ts tracked in a dedicated closura_sql_migrations table without advancing effect_sql_migrations MAX(migration_id) or writing under PRAGMA query_only = ON. Model: gemini-4-neon Task: fix Agent: Builder Harness: t3/antigravity Model-family: Gemini Model-generation: 4 Neon Skills-SHA: nullStack65/closura-agent-config@da5f66450f9d69207369395f7a30686834767453; skills/github-repository-ops/SKILL.md (sha256:e3778c3a953bfa9e7bf5c9b9609b6d6c947cffa03366b3bc0f75bbb722b76784, installed matches source) Refs: CLO-1368 --- .../orchestration-v2/InboundAdmission.test.ts | 129 ++++++++++++++++++ .../src/orchestration-v2/InboundAdmission.ts | 15 +- .../server/src/persistence/Migrations.test.ts | 61 ++++++++- apps/server/src/persistence/Migrations.ts | 67 ++++++++- .../001_RuntimeDecisions.ts} | 0 5 files changed, 259 insertions(+), 13 deletions(-) rename apps/server/src/persistence/Migrations/{125_RuntimeDecisions.ts => fork/001_RuntimeDecisions.ts} (100%) diff --git a/apps/server/src/orchestration-v2/InboundAdmission.test.ts b/apps/server/src/orchestration-v2/InboundAdmission.test.ts index 31831e81b8fba..33d6804f36aaf 100644 --- a/apps/server/src/orchestration-v2/InboundAdmission.test.ts +++ b/apps/server/src/orchestration-v2/InboundAdmission.test.ts @@ -611,4 +611,133 @@ it.layer(layerTest)("M0 inbound admission and runtime_decisions", (it) => { assert.strictEqual(digested.delivery?.coalesceKey, "status:item"); assert.strictEqual(digested.deliveryIntent, undefined); }); + + it.effect( + "allows provider continuations, background_task, and non-PR monitor wakes under enforce while keeping PR-watch redirects gated", + () => + Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const decisions = yield* RuntimeDecisions.RuntimeDecisionStore; + + yield* settings.updateSettings({ runtimeEnforcement: "enforce" }); + + const factoryId = ThreadId.make("thread:enforce-provider-wakes"); + yield* createThread({ + threadId: factoryId, + title: "Software Factory", + createdBy: "user", + audience: "kameron", + }); + + // 1. Provider-origin continuation bypasses inbound admission completely. + const providerWake = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("wake:provider-source"), + threadId: factoryId, + messageId: MessageId.make("msg:provider-wake"), + text: "Continue after provider background activity", + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: "Provider monitor wake without PR stamp", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "provider", + }); + assert.isUndefined(providerWake.inboundAdmission); + assert.strictEqual(yield* startedRunsCount(factoryId), 1); + + // 2. provider-continuation: commandId (delivery: message_text -> creationSource: server) bypasses admission. + const continuationWake = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("provider-continuation:msg-cont-1"), + threadId: factoryId, + messageId: MessageId.make("msg:cont-1"), + text: "Background task finished", + notification: { + source: { kind: "background_task" }, + outcome: "completed", + summary: "Background activity updated", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.isUndefined(continuationWake.inboundAdmission); + assert.strictEqual((yield* decisions.listForThread(factoryId)).length, 0); + + // 3. Direct background_task and non-PR monitor wakes classify as child / child_result and wake under enforce. + const backgroundTaskWake = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("server:bg-task-1"), + threadId: factoryId, + messageId: MessageId.make("msg:bg-task-1"), + text: "Background command completed", + notification: { + source: { kind: "background_task" }, + outcome: "completed", + summary: "Background build completed", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.strictEqual(backgroundTaskWake.inboundAdmission?.deliverAs, "next_turn"); + assert.strictEqual(backgroundTaskWake.inboundAdmission?.wakesThread, true); + + const nonPrMonitorWake = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("server:monitor-non-pr-1"), + threadId: factoryId, + messageId: MessageId.make("msg:monitor-non-pr-1"), + text: "Monitor wake without PR stamp", + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: "Background monitor update", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.strictEqual(nonPrMonitorWake.inboundAdmission?.deliverAs, "next_turn"); + assert.strictEqual(nonPrMonitorWake.inboundAdmission?.wakesThread, true); + + // 4. PR-watch monitor wake with message:pr-watch: prefix and no PR stamp still classifies as uncovered PR -> log_only. + const redirectedPrWatch = yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("server:pr-watch-redirect-1"), + threadId: factoryId, + messageId: MessageId.make("message:pr-watch:redirect-1"), + text: "Update on pull request #999: checks failed", + notification: { + source: { kind: "monitor" }, + outcome: "failed", + summary: "#999: checks failed", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + assert.strictEqual(redirectedPrWatch.inboundAdmission?.deliverAs, "log_only"); + assert.strictEqual(redirectedPrWatch.inboundAdmission?.wakesThread, false); + + const rows = yield* decisions.listForThread(factoryId); + assert.deepStrictEqual( + rows.map((row) => [row.eventKind, row.decision]), + [ + ["child_result", "next_turn"], + ["child_result", "next_turn"], + ["pr_actionable", "log_only"], + ], + ); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/InboundAdmission.ts b/apps/server/src/orchestration-v2/InboundAdmission.ts index 5b45a85621006..0e7fcd210022e 100644 --- a/apps/server/src/orchestration-v2/InboundAdmission.ts +++ b/apps/server/src/orchestration-v2/InboundAdmission.ts @@ -45,6 +45,8 @@ export interface OrchestratorV2InboundAdmissionOutcome { export function isInternalDispatchCommand(command: MessageDispatchCommand): boolean { return ( command.humanNote === true || + command.creationSource === "provider" || + command.commandId.startsWith("provider-continuation:") || command.idleCompaction !== undefined || command.restartContinuationOfRunId !== undefined || command.usageLimitContinuationOfRunId !== undefined || @@ -87,6 +89,15 @@ function classifyInboundRecipient( const ACTIONABLE_PR_SUMMARY_RE = /\b(merged|closed|changes requested|comments?|conflict|rebase|failed|failing|removed from merge queue|stopped watching|no observed progress|await(?:ing)? approval)\b/i; +function isPullRequestMonitorNotification(command: MessageDispatchCommand): boolean { + if (command.notification?.source.kind !== "monitor") return false; + return ( + command.notification.source.pullRequest !== undefined || + (command.notification.source.otherPullRequests?.length ?? 0) > 0 || + command.messageId.startsWith("message:pr-watch:") + ); +} + function classifyMonitorPullRequestEvent( notification: OrchestrationV2Notification, ): "pr_actionable" | "pr_routine" { @@ -219,8 +230,8 @@ function evaluateInboundDispatch(input: { command.notification?.source.kind === "delegated_task" || command.notification?.source.kind === "subagent" || command.notification?.source.kind === "command" || - (command.notification?.source.kind === "monitor" && - command.notification.source.staleWaits !== undefined) + command.notification?.source.kind === "background_task" || + (command.notification?.source.kind === "monitor" && !isPullRequestMonitorNotification(command)) ) { sender = "child"; kind = command.inboundEventKind ?? "child_result"; diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index b9956cf831094..0e688177dd94b 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -17,7 +17,13 @@ import { } from "@t3tools/shared/databaseMigrationLog"; import * as DatabaseMigrationProgress from "./DatabaseMigrationProgress.ts"; -import { migrationManifest, runMigrations, UPSTREAM_MIGRATION_ID_OFFSET } from "./Migrations.ts"; +import { + closuraForkMigrationManifest, + hasPendingMigrations, + migrationManifest, + runMigrations, + UPSTREAM_MIGRATION_ID_OFFSET, +} from "./Migrations.ts"; const v2Migrations = migrationManifest.filter(([id]) => id >= 55); const newerMigrationId = Math.max(...migrationManifest.map(([id]) => id)) + 1; @@ -282,6 +288,16 @@ it.effect("registers every migration file", () => migrationManifest.length, "every ledger id is used once", ); + + const forkDir = path.join(dir, "fork"); + const forkFiles = (yield* fs.readDirectory(forkDir)).flatMap((name) => { + const match = /^(\d+)_(\w+)\.ts$/.exec(name); + return match ? [[Number(match[1]), match[2]!] as const] : []; + }); + assert.deepStrictEqual( + forkFiles.toSorted(([a], [b]) => a - b), + closuraForkMigrationManifest, + ); }).pipe(Effect.provide(NodeServices.layer)), ); @@ -290,9 +306,14 @@ it.effect("registers every migration file", () => // history and must be refused, not skipped past. describe("the fork's migration ledger", () => { const forkIds = [97, 98, 99, 100, 101, 102] as const; - const upstreamLater = migrationManifest.filter( - ([id]) => id > 102 && id <= 118 + UPSTREAM_MIGRATION_ID_OFFSET, - ); + const upstreamLater = migrationManifest.filter(([id]) => id > 102); + const forkHistory = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ readonly migration_id: number; readonly name: string }>` + SELECT migration_id, name FROM closura_sql_migrations ORDER BY migration_id + `; + return rows.map((row) => [row.migration_id, row.name] as const); + }); const columns = (table: string) => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; @@ -341,10 +362,42 @@ describe("the fork's migration ledger", () => { assert.isTrue(present.has("scheduled_task_occurrences"), "the fork's last migration ran"); assert.isTrue(present.has("issue_tracker_bindings"), "upstream's first later one ran"); assert.isTrue(present.has("runtime_decisions"), "post-offset fork migration ran"); + assert.strictEqual( + (yield* history).at(-1)?.[0], + 118 + UPSTREAM_MIGRATION_ID_OFFSET, + "effect_sql_migrations stops at upstream's shifted head without taking id 125", + ); + assert.deepStrictEqual(yield* forkHistory, closuraForkMigrationManifest); assert.deepStrictEqual(yield* runMigrations(), []); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); + it.effect( + "tracks post-offset fork migrations in closura_sql_migrations without advancing effect_sql_migrations or writing under query_only", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const upstreamHead = 118 + UPSTREAM_MIGRATION_ID_OFFSET; + yield* runMigrations({ toMigrationInclusive: upstreamHead }); + + assert.strictEqual((yield* history).at(-1)?.[0], upstreamHead); + assert.isFalse((yield* tables).has("closura_sql_migrations")); + assert.isFalse((yield* tables).has("runtime_decisions")); + assert.isTrue(yield* hasPendingMigrations()); + + const executed = yield* runMigrations(); + assert.deepStrictEqual(executed, []); + assert.strictEqual((yield* history).at(-1)?.[0], upstreamHead); + assert.deepStrictEqual(yield* forkHistory, closuraForkMigrationManifest); + assert.isTrue((yield* tables).has("runtime_decisions")); + assert.isFalse(yield* hasPendingMigrations()); + + yield* sql`PRAGMA query_only = ON`; + assert.isFalse(yield* hasPendingMigrations()); + assert.deepStrictEqual(yield* runMigrations(), []); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), + ); + it.effect.each(forkIds)( "upgrades a fork database recorded at %s, applying only what it lacks", (recordedThrough) => diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 1d82e57327437..25cfb5a5b5bff 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -135,7 +135,7 @@ import Migration0115 from "./Migrations/115_WorkflowRunTags.ts"; import Migration0116 from "./Migrations/116_ForkHistoryMembership.ts"; import Migration0117 from "./Migrations/117_WorkflowMailSender.ts"; import Migration0118 from "./Migrations/118_WorkflowPools.ts"; -import ForkMigration0125 from "./Migrations/125_RuntimeDecisions.ts"; +import ClosuraForkMigration0001 from "./Migrations/fork/001_RuntimeDecisions.ts"; /** * Closura: deployed fork databases record the fork's own migrations at ledger ids 97 to 102. @@ -270,11 +270,17 @@ const migrationEntries = [ [116 + UPSTREAM_MIGRATION_ID_OFFSET, "ForkHistoryMembership", Migration0116], [117 + UPSTREAM_MIGRATION_ID_OFFSET, "WorkflowMailSender", Migration0117], [118 + UPSTREAM_MIGRATION_ID_OFFSET, "WorkflowPools", Migration0118], - [125, "RuntimeDecisions", ForkMigration0125], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); +// Post-102 fork migrations live in their own ledger so upstream's shifted ids stay collision-free. +const closuraForkMigrationEntries = [[1, "RuntimeDecisions", ClosuraForkMigration0001]] as const; + +export const closuraForkMigrationManifest = closuraForkMigrationEntries.map( + ([id, name]) => [id, name] as const, +); + const makeMigrationLoader = (throughId?: number) => Migrator.fromRecord( Object.fromEntries( @@ -331,8 +337,7 @@ const assertV2MigrationsCanRun = Effect.fn("assertV2MigrationsCanRun")(function* const latestMigrationId = Math.max(...migrationEntries.map(([id]) => id)); -// Mirrors the Migrator, which runs only ids above the highest recorded, plus the V2-preview reconciliation. -export const hasPendingMigrations = Effect.fn("hasPendingMigrations")(function* () { +const hasPendingEffectMigrations = Effect.fn("hasPendingEffectMigrations")(function* () { const sql = yield* SqlClient.SqlClient; const tables = yield* sql` SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations' @@ -348,6 +353,25 @@ export const hasPendingMigrations = Effect.fn("hasPendingMigrations")(function* return (row?.latestId ?? 0) < latestMigrationId || (row?.previewRows ?? 0) > 0; }); +const pendingClosuraForkMigrations = Effect.fn("pendingClosuraForkMigrations")(function* () { + const sql = yield* SqlClient.SqlClient; + const tables = yield* sql` + SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'closura_sql_migrations' + `; + if (tables.length === 0) return [...closuraForkMigrationEntries]; + const recorded = yield* sql<{ readonly migration_id: number }>` + SELECT migration_id FROM closura_sql_migrations + `; + const recordedIds = new Set(recorded.map((row) => row.migration_id)); + return closuraForkMigrationEntries.filter(([id]) => !recordedIds.has(id)); +}); + +// Mirrors the Migrator, which runs only ids above the highest recorded, plus V2 preview & fork ledgers. +export const hasPendingMigrations = Effect.fn("hasPendingMigrations")(function* () { + if (yield* hasPendingEffectMigrations()) return true; + return (yield* pendingClosuraForkMigrations()).length > 0; +}); + const run = Migrator.make({}); export interface RunMigrationsOptions { @@ -359,12 +383,16 @@ export const runMigrations = Effect.fn("runMigrations")(function* ({ }: RunMigrationsOptions = {}) { const progress = yield* Effect.serviceOption(DatabaseMigrationProgress.DatabaseMigrationProgress); // The desktop waits past its readiness budget until the finished line follows this one. - const hasPending = yield* hasPendingMigrations(); + const hasPendingEffect = yield* hasPendingEffectMigrations(); + const pendingFork = + toMigrationInclusive === undefined ? yield* pendingClosuraForkMigrations() : []; + const hasPending = hasPendingEffect || pendingFork.length > 0; if (hasPending) yield* Effect.log(DATABASE_MIGRATIONS_STARTED_MESSAGE); const includesV2 = toMigrationInclusive === undefined || toMigrationInclusive >= FIRST_V2_MIGRATION_ID; // The reconcile takes the write lock; CLI startup must not contend with the server for a no-op. - const previewMigrations = includesV2 && hasPending ? yield* reconcileV2PreviewMigration() : []; + const previewMigrations = + includesV2 && hasPendingEffect ? yield* reconcileV2PreviewMigration() : []; if (includesV2) { yield* assertV2MigrationsCanRun(toMigrationInclusive); } @@ -406,7 +434,32 @@ export const runMigrations = Effect.fn("runMigrations")(function* ({ }).pipe( Effect.ensuring(Option.isSome(progress) ? Ref.set(progress.value.current, null) : Effect.void), ); - const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`); + const executedForkMigrations: Array = []; + if (pendingFork.length > 0) { + yield* sql` + CREATE TABLE IF NOT EXISTS closura_sql_migrations ( + migration_id INTEGER PRIMARY KEY NOT NULL, + created_at DATETIME NOT NULL DEFAULT current_timestamp, + name VARCHAR(255) NOT NULL + ) + `; + for (const [id, name, migration] of pendingFork) { + yield* sql.withTransaction( + Effect.gen(function* () { + yield* migration; + yield* sql` + INSERT INTO closura_sql_migrations (migration_id, name) + VALUES (${id}, ${name}) + `; + }), + ); + executedForkMigrations.push([id, name]); + } + } + const migrations = [ + ...executedMigrations.map(([id, name]) => `${id}_${name}`), + ...executedForkMigrations.map(([id, name]) => `fork:${id}_${name}`), + ]; yield* migrations.length === 0 ? Effect.logDebug("Database schema is current") : Effect.log(DATABASE_MIGRATIONS_FINISHED_MESSAGE).pipe(Effect.annotateLogs({ migrations })); diff --git a/apps/server/src/persistence/Migrations/125_RuntimeDecisions.ts b/apps/server/src/persistence/Migrations/fork/001_RuntimeDecisions.ts similarity index 100% rename from apps/server/src/persistence/Migrations/125_RuntimeDecisions.ts rename to apps/server/src/persistence/Migrations/fork/001_RuntimeDecisions.ts