T3code/implement p0 step 4 #165
codething/648ca884 fromrefs/pull/165/head·merged by juliusmarminge View on GitHubNote
Medium Risk
Medium risk because it changes the session/permission model (approvalPolicy/sandboxMode → runtimeMode), updates the persisted projection schema, and refactors runtime event ingestion across providers, which can affect session restarts, approvals, and UI state.
Overview
Unifies session permissions under runtimeMode. Replaces approvalPolicy + sandboxMode with runtimeMode across orchestration commands/events, provider session start inputs, and adapters (including session restart logic when runtimeMode changes).
Updates persistence and projections. Migrates projection_thread_sessions to store runtime_mode (new migration + query/upsert updates) and updates snapshot queries/tests to read/write the new column.
Modernizes and expands provider runtime event handling. Refactors ProviderRuntimeIngestion to rely on canonical payload-based event shapes (content.delta, item.started/updated/completed, payload-based turn.completed/runtime.error), adds handling for session.state.changed, thread.metadata.updated, turn.plan.updated, turn.diff.updated (creating provider-diff checkpoints), runtime.warning, and removes legacy backward-compat parsing.
Provider-specific behavior tweaks. Codex now maps windowsSandbox/setupCompleted into session.state.changed (+ warning on failure) and drops emitting warnings for unknown methods; Cursor/Claude permission gating now keys off runtimeMode (full-access bypasses approvals), and web client turn dispatch sends runtimeMode directly. Note: adds .tmp/acp-plan-probe/* probe artifacts to the repo.
Note
Adopt P1 runtime event schema and replace approvalPolicy/sandboxMode with runtimeMode across orchestration, providers, projection, and web clients in ProviderRuntimeIngestion.ts and related modules#
Switch system-wide session configuration to runtimeMode and update ingestion to P1 events. Ingestion now processes content.delta and item.completed (assistant_message), maps session.state.changed to orchestration status, emits activities for runtime.warning/turn.plan.updated/item.updated, and persists runtimeMode through projection, persistence, and contracts. Providers (Codex, Claude, Cursor) consume/emit the new shapes; clients send runtimeMode on thread.turn.start.
📍Where to Start#
Start with the runtime event handling in ProviderRuntimeIngestion.make in ProviderRuntimeIngestion.ts, then review the contract changes in packages/contracts/src/orchestration.ts and provider mappings in apps/server/src/provider/Layers/CodexAdapter.ts.
📊 Macroscope summarized a34aa54. 17 files reviewed, 23 issues evaluated, 12 issues filtered, 1 comment posted
🗂️ Filtered Issues#
apps/server/src/codexAppServerManager.ts — 0 comments posted, 2 evaluated, 1 filtered
- line 107: The
mapCodexRuntimeModefunction uses a "fail-open" logic: any input string that does not strictly match"approval-required"results in a return value that grants full system access (sandbox: "danger-full-access",approvalPolicy: "never"). If an invalid string is passed at runtime (e.g. from loosely typed JSON input or a typo like"approval_required"), the system defaults to the most insecure state instead of rejecting the input or defaulting to a safe configuration. [ Cross-file consolidated ]
apps/server/src/orchestration/Layers/ProjectionPipeline.ts — 0 comments posted, 1 evaluated, 1 filtered
- line 654: The
applyThreadSessionsProjectionfunction accessesevent.payload.session.runtimeModedirectly, assuming strictly the new event shape. However, this introduces a breaking change for event replay: existingthread.session-setevents in theOrchestrationEventStorewere created with the now-deprecatedapprovalPolicyandsandboxModefields and lackruntimeMode. [ Cross-file consolidated ]
apps/server/src/orchestration/decider.ts — 0 comments posted, 1 evaluated, 1 filtered
- line 520: In the
defaultcase of the switch statement handling unknown command types, the code attempts toyield*a raw error instance (new OrchestrationCommandInvariantError(...)) instead of an Effect. In an Effect generator,yield*expects an Effect, Promise, or Iterable. Since the error class is a plain object/value, this will likely throw a runtimeTypeError(e.g., "value is not iterable") causing the application to crash, rather than returning a controlled failure Effect. [ Cross-file consolidated ]
apps/server/src/provider/Layers/CodexAdapter.ts — 0 comments posted, 3 evaluated, 2 filtered
- line 1020: Runtime crash in
sendTurnwhen an attachment path cannot be resolved. The functiontoRequestErrorreturns a standardErrorobject (specificallyProviderAdapterRequestError), not an Effect. Usingyield*on this object attempts to iterate over it, causing a TypeError at runtime. This should be wrapped asyield* Effect.fail(toRequestError(...)). [ Out of scope ] - line 1130: Unhandled Promise Rejection in event listener. The listener uses
Effect.runPromiseWith, which returns a Promise that rejects if the effect fails (e.g., ifnativeEventLogger.writethrows due to a file system error orQueue.offerAllfails). Becausemanager.oninvokes the listener without awaiting or handling the returned Promise, any failure here will cause the Node.js process to crash with an unhandled rejection. The effect body must be wrapped inEffect.catchAllto swallow and log errors. [ Out of scope ]
apps/server/src/provider/Layers/CursorAdapter.ts — 0 comments posted, 3 evaluated, 3 filtered
- line 551: Protocol hang in
handlePermissionRequestwhenoptionsis empty. Infull-accessmode, if a permission request arrives with an emptyoptionsarray, the code logs a warning and returns without sending a JSON-RPC response to the Cursor ACP process. This leaves the ACP process hanging indefinitely, waiting for a response tosession/request_permission. The adapter should reply with an error or a rejection to close the request cycle. [ Out of scope ] - line 642: Data loss in
readThreaddue to missing state aggregation. ThehandleSessionUpdateNotificationfunction emits runtime events for content deltas and tool calls but fails to updatecontext.turnState.items. As a result,completeTurn(line 487) captures an emptyitemsarray for every turn. Consequently,readThreadreturns valid turn IDs but with empty item lists, making the persistent session history inaccessible. [ Out of scope ] - line 1137: Resource leak in
startSessionon initialization failure. The session context is added to thesessionsmap and the child process is spawned before theinitializeandauthenticatehandshakes occur. If these subsequent requests fail (e.g., due to timeout or protocol error),startSessionfails and returns an error to the caller, but the session remains in thesessionsmap and the child process keeps running. The caller receives nosessionIdto manually clean up the leaked resources. [ Out of scope ]
apps/web/src/components/ChatView.tsx — 0 comments posted, 2 evaluated, 2 filtered
- line 1992: The drag-and-drop overlay logic in
ChatViewcombines depth counting with arelatedTargetcheck in a way that causes thedragDepthRefcounter to drift, resulting in the overlay getting stuck in the active state. [ Out of scope ] - line 2259: In
ChatView'sonSendfunction, if the message send fails (e.g. network error) and the user has typed in the prompt field while the request was in-flight, the optimistic message will be permanently stuck in the timeline. The error handling block (lines 2247-2280) only removes the optimistic message ifpromptRef.currentis empty (lines 2258-2261). If the user types any character during the send process,promptRefis not empty, the cleanup is skipped, and the optimistic message (which will never receive a server ID) remains in the list as a ghost message until the component remounts. [ Out of scope ]
packages/contracts/src/orchestration.ts — 0 comments posted, 3 evaluated, 1 filtered
- line 154: Insecure default value for
runtimeModeinOrchestrationSession. The schema replaces the legacyapprovalPolicyfield withruntimeModeand explicitly sets a decoding default ofDEFAULT_RUNTIME_MODE(defined as"full-access"at line 37). When decoding persistedOrchestrationSessionobjects (e.g., fromgetSnapshotorreplayEventson existing data) that lack theruntimeModefield, the system will silently upgrade the session to"full-access". This is a security regression for any legacy sessions that were configured with restrictive approval policies (e.g., requiring approval), as they effectively lose their security constraints. A fail-safe default like"approval-required"should be used instead. [ Cross-file consolidated ]
packages/contracts/src/provider.ts — 0 comments posted, 1 evaluated, 1 filtered
- line 82: Breaking backward compatibility and data loss in
ProviderSessionStartInput. The schema definition removes theapprovalPolicyandsandboxModefields. Because Schema decoders typically strip excess properties, legacy clients sending these fields will have them silently removed during decoding. SinceruntimeModeis optional and likely missing in legacy requests, the resulting decoded object will contain neither the old security settings nor the new one (runtimeModewill beundefined). This forces the downstream handler to guess the user's intent, likely falling back to a default that may be incorrect or insecure. The legacy fields should be preserved as optional to allow for proper mapping during migration. [ Cross-file consolidated ]
- 1
juliusmarminge merged this
juliusmarminge closed this
- @@ -1,19 +1,13 @@11 import * as SqlClient from "effect/unstable/sql/SqlClient";22 import * as Effect from "effect/Effect";334-const DEFAULT_APPROVAL_POLICY = "never";5-const DEFAULT_SANDBOX_MODE = "workspace-write";4+const DEFAULT_RUNTIME_MODE = "full-access";6576 export default Effect.gen(function* () {87 const sql = yield* SqlClient.SqlClient;98109 yield* sql`1110 ALTER TABLE projection_thread_sessions12- ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'11+ ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'1312 `;141315- yield* sql`16- ALTER TABLE projection_thread_sessions17- ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'18- `;19-
In-place migration edit breaks existing databases#
Medium Severity
Migration
006was edited in-place to replaceapproval_policy+sandbox_modecolumns with a singleruntime_modecolumn. Any environment (dev, CI, staging) that previously ran the old version of migration006will have theapproval_policyandsandbox_modecolumns inprojection_thread_sessionsbut notruntime_mode. Because migration runners track applied versions by number, migration006won't re-execute on those databases, and all SQL statements inProjectionThreadSessions.tsandProjectionSnapshotQuery.tsthat referenceruntime_modewill fail with a column-not-found error. A new migration (e.g.,009) is needed to drop the old columns and addruntime_modefor any database that already has006applied. - @@ -415 +415 @@415415 const input = {
🟡 Medium
Layers/ProviderService.ts:415When
runtimeModeis omitted from the input, the code defaults to"full-access"— the most permissive mode. If a legacy client sendssandboxModeorapprovalPolicyinstead (whichProviderSessionStartInputmay strip), those security constraints are silently discarded and the session runs with full access. This fails open: missing or unrecognized security fields result in elevated privileges rather than safe defaults or validation errors.Also found in 4 other location(s)
apps/server/src/codexAppServerManager.ts:107The
mapCodexRuntimeModefunction uses a "fail-open" logic: any input string that does not strictly match"approval-required"results in a return value that grants full system access (sandbox: "danger-full-access",approvalPolicy: "never"). If an invalid string is passed at runtime (e.g. from loosely typed JSON input or a typo like"approval_required"), the system defaults to the most insecure state instead of rejecting the input or defaulting to a safe configuration.packages/contracts/src/orchestration.ts:35Insecure default value for
runtimeModeinOrchestrationSession. The schema replaces the legacyapprovalPolicyfield withruntimeModeand explicitly sets a decoding default ofDEFAULT_RUNTIME_MODE(defined as"full-access"at line 37). When decoding persistedOrchestrationSessionobjects (e.g., fromgetSnapshotorreplayEventson existing data) that lack theruntimeModefield, the system will silently upgrade the session to"full-access". This is a security regression for any legacy sessions that were configured with restrictive approval policies (e.g., requiring approval), as they effectively lose their security constraints. A fail-safe default like"approval-required"should be used instead.packages/contracts/src/provider.ts:76Breaking backward compatibility and data loss in
ProviderSessionStartInput. The schema definition removes theapprovalPolicyandsandboxModefields. Because Schema decoders typically strip excess properties, legacy clients sending these fields will have them silently removed during decoding. SinceruntimeModeis optional and likely missing in legacy requests, the resulting decoded object will contain neither the old security settings nor the new one (runtimeModewill beundefined). This forces the downstream handler to guess the user's intent, likely falling back to a default that may be incorrect or insecure. The legacy fields should be preserved as optional to allow for proper mapping during migration.apps/server/src/orchestration/Layers/ProjectionPipeline.ts:654The
applyThreadSessionsProjectionfunction accessesevent.payload.session.runtimeModedirectly, assuming strictly the new event shape. However, this introduces a breaking change for event replay: existingthread.session-setevents in theOrchestrationEventStorewere created with the now-deprecatedapprovalPolicyandsandboxModefields and lackruntimeMode.During server startup/bootstrap, replaying these legacy events will result in
runtimeModeevaluating toundefined. PassingundefinedtoprojectionThreadSessionRepository.upsertwill fail schema validation (asruntimeModeis required inProjectionThreadSession), causing the projection pipeline to crash.To fix this, provide a default value or mapping logic for legacy events:
runtimeMode: event.payload.session.runtimeMode ?? "web", // or infer from legacy fields🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file apps/server/src/provider/Layers/ProviderService.ts around line 415: When `runtimeMode` is omitted from the input, the code defaults to `"full-access"` — the most permissive mode. If a legacy client sends `sandboxMode` or `approvalPolicy` instead (which `ProviderSessionStartInput` may strip), those security constraints are silently discarded and the session runs with full access. This fails open: missing or unrecognized security fields result in elevated privileges rather than safe defaults or validation errors. Evidence trail: 1. apps/server/src/provider/Layers/ProviderService.ts:415 — `runtimeMode: parsed.runtimeMode ?? "full-access"` 2. git_diff MERGE_BASE..REVIEWED_COMMIT packages/contracts/src/provider.ts — schema changed from `approvalPolicy`/`sandboxMode` to `runtimeMode` 3. git_diff MERGE_BASE..REVIEWED_COMMIT packages/contracts/src/provider.test.ts — confirms the old test used `approvalPolicy: "on-request", sandboxMode: "workspace-write"` which mapped to restrictive access 4. packages/contracts/src/orchestration.ts:35-37 — `RuntimeMode = Schema.Literals(["approval-required", "full-access"])` and `DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"` Also found in 4 other location(s): - apps/server/src/codexAppServerManager.ts:107 -- The `mapCodexRuntimeMode` function uses a "fail-open" logic: any input string that does not strictly match `"approval-required"` results in a return value that grants full system access (`sandbox: "danger-full-access"`, `approvalPolicy: "never"`). If an invalid string is passed at runtime (e.g. from loosely typed JSON input or a typo like `"approval_required"`), the system defaults to the most insecure state instead of rejecting the input or defaulting to a safe configuration. - packages/contracts/src/orchestration.ts:35 -- Insecure default value for `runtimeMode` in `OrchestrationSession`. The schema replaces the legacy `approvalPolicy` field with `runtimeMode` and explicitly sets a decoding default of `DEFAULT_RUNTIME_MODE` (defined as `"full-access"` at line 37). When decoding persisted `OrchestrationSession` objects (e.g., from `getSnapshot` or `replayEvents` on existing data) that lack the `runtimeMode` field, the system will silently upgrade the session to `"full-access"`. This is a security regression for any legacy sessions that were configured with restrictive approval policies (e.g., requiring approval), as they effectively lose their security constraints. A fail-safe default like `"approval-required"` should be used instead. - packages/contracts/src/provider.ts:76 -- Breaking backward compatibility and data loss in `ProviderSessionStartInput`. The schema definition removes the `approvalPolicy` and `sandboxMode` fields. Because Schema decoders typically strip excess properties, legacy clients sending these fields will have them silently removed during decoding. Since `runtimeMode` is optional and likely missing in legacy requests, the resulting decoded object will contain neither the old security settings nor the new one (`runtimeMode` will be `undefined`). This forces the downstream handler to guess the user's intent, likely falling back to a default that may be incorrect or insecure. The legacy fields should be preserved as optional to allow for proper mapping during migration. - apps/server/src/orchestration/Layers/ProjectionPipeline.ts:654 -- The `applyThreadSessionsProjection` function accesses `event.payload.session.runtimeMode` directly, assuming strictly the new event shape. However, this introduces a breaking change for event replay: existing `thread.session-set` events in the `OrchestrationEventStore` were created with the now-deprecated `approvalPolicy` and `sandboxMode` fields and lack `runtimeMode`. During server startup/bootstrap, replaying these legacy events will result in `runtimeMode` evaluating to `undefined`. Passing `undefined` to `projectionThreadSessionRepository.upsert` will fail schema validation (as `runtimeMode` is required in `ProjectionThreadSession`), causing the projection pipeline to crash. To fix this, provide a default value or mapping logic for legacy events: [code fence]typescript runtimeMode: event.payload.session.runtimeMode ?? "web", // or infer from legacy fields [code fence]
Sign in to join this conversation.


cursor[bot](GitHub profile, opens in a new tab) reviewed
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is ON, but it could not run because the branch was deleted or merged before autofix could start.