Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
chore(ci): add and apply `fmt:check` script (#779)
Jason Laster223c3dc8005b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8035a57ed..815a3bcdd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -8,7 +8,7 @@ on:jobs:quality:- name: Lint, Typecheck, Test, Browser Test, Build+ name: Format, Lint, Typecheck, Test, Browser Test, Buildruns-on: blacksmith-4vcpu-ubuntu-2404steps:- name: Checkout@@ -45,6 +45,9 @@ jobs:- name: Install dependenciesrun: bun install --frozen-lockfile+ - name: Format+ run: bun run fmt:check+- name: Lintrun: bun run lintdiff --git a/.oxfmtrc.json b/.oxfmtrc.jsonindex f0fbfde6d..ef2236d0f 100644--- a/.oxfmtrc.json+++ b/.oxfmtrc.json@@ -7,7 +7,8 @@"node_modules","bun.lock","*.tsbuildinfo",- "**/routeTree.gen.ts"+ "**/routeTree.gen.ts",+ "apps/web/public/mockServiceWorker.js"],- "experimentalSortPackageJson": {}+ "sortPackageJson": {}}diff --git a/.plans/01-shared-model-normalization.md b/.plans/01-shared-model-normalization.mdindex e1e5f77db..d38c41643 100644--- a/.plans/01-shared-model-normalization.md+++ b/.plans/01-shared-model-normalization.md@@ -1,20 +1,24 @@# Plan: Centralize Model Normalization in Contracts## Summary+Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.## Motivation+- Removes duplicated logic between:- `apps/desktop/src/codexAppServerManager.ts`- `apps/renderer/src/model-logic.ts`- Prevents behavior drift when model aliases/defaults are updated.## Scope+- Add shared model utilities to contracts.- Update desktop and renderer to consume shared utilities.- Keep renderer-specific display options in renderer.## Proposed Changes+1. Add `packages/contracts/src/model.ts` with:- Canonical model list- Alias map@@ -29,14 +33,17 @@ Move model alias/default normalization into `packages/contracts` so desktop and- Keep renderer tests focused on renderer-only behavior.## Risks+- Desktop/renderer may currently rely on slightly different fallback behavior.- Import graph must avoid bundling issues for Electron main/preload.## Validation+- `bun run test`- `bun run typecheck`- Manual check that model selection and session start still send expected model slug.## Done Criteria+- No duplicated alias/default map in desktop and renderer.- Shared model utilities are contract-tested.diff --git a/.plans/02-typed-ipc-boundaries.md b/.plans/02-typed-ipc-boundaries.mdindex 4e9100435..fac5b1fc2 100644--- a/.plans/02-typed-ipc-boundaries.md+++ b/.plans/02-typed-ipc-boundaries.md@@ -1,17 +1,21 @@# Plan: Strengthen Typed IPC Boundaries in Main Process## Summary+Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.## Motivation+- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.- Casts can hide contract breakages until runtime.## Scope+- Desktop main process IPC registration.- Optional shared helper for handler registration.## Proposed Changes+1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:- Parse payload(s) with Zod schemas- Standardize typed handler signatures@@ -24,14 +28,17 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ4. Add tests for handler parsing failure paths (invalid payloads).## Risks+- Refactor can subtly change IPC error shape/messages.- Helper abstraction should stay simple and not obscure control flow.## Validation+- `bun run test`- `bun run typecheck`- Manual invalid payload check from renderer/devtools to confirm fast failure.## Done Criteria+- No provider handler uses `payload as Parameters<...>`.- All IPC entrypoints parse unknown payloads at boundary.diff --git a/.plans/03-split-codex-app-server-manager.md b/.plans/03-split-codex-app-server-manager.mdindex e425a6ae7..4f7fadb43 100644--- a/.plans/03-split-codex-app-server-manager.md+++ b/.plans/03-split-codex-app-server-manager.md@@ -1,9 +1,11 @@# Plan: Decompose CodexAppServerManager## Summary+Split `CodexAppServerManager` into smaller modules with clear responsibilities.## Motivation+- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:- Process lifecycle- JSON-RPC parsing/routing@@ -12,10 +14,12 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.- This increases regression risk and slows changes.## Scope+- Desktop provider internals only.- Keep external behavior/API stable.## Proposed Changes+1. Extract modules:- `codex/processLifecycle.ts`- `codex/jsonrpcRouter.ts`@@ -29,13 +33,16 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.- Session state transitions## Risks+- Reordering event handling can change behavior.- Must preserve pending request timeout/cancellation semantics.## Validation+- Existing tests pass.- Add module-level tests for parsing and transition logic.## Done Criteria+- Main manager file materially smaller and orchestration-focused.- Core protocol/state logic covered by focused tests.diff --git a/.plans/04-split-chatview-component.md b/.plans/04-split-chatview-component.mdindex 3d6f949e9..abf30c04f 100644--- a/.plans/04-split-chatview-component.md+++ b/.plans/04-split-chatview-component.md@@ -1,9 +1,11 @@# Plan: Split ChatView into Smaller UI/Logic Units## Summary+Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.## Motivation+- `apps/renderer/src/components/ChatView.tsx` is large and handles:- Session orchestration- Send/interrupt actions@@ -13,10 +15,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.- Hard to test and maintain as one component.## Scope+- Renderer component boundaries and hooks.- Keep visual behavior unchanged.## Proposed Changes+1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`- `ensureSession`- `sendTurn`@@ -29,12 +33,15 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.4. Add focused tests for hook behavior (error handling, session reuse).## Risks+- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).## Validation+- `bun run test`- Manual smoke: send, stream, interrupt, model switch.## Done Criteria+- `ChatView.tsx` significantly reduced and easier to scan.- Session logic isolated from rendering.diff --git a/.plans/05-zod-persisted-state-validation.md b/.plans/05-zod-persisted-state-validation.mdindex 51fcf805d..869da8679 100644--- a/.plans/05-zod-persisted-state-validation.md+++ b/.plans/05-zod-persisted-state-validation.md@@ -1,17 +1,21 @@# Plan: Move Renderer Persisted-State Validation to Zod## Summary+Use explicit Zod schemas for localStorage state parsing and migration.## Motivation+- `apps/renderer/src/store.ts` has large manual sanitize functions.- Manual type guards are verbose and easier to get wrong during schema evolution.## Scope+- Renderer state hydration/persistence path.- No backend/protocol changes.## Proposed Changes+1. Add schema module: `apps/renderer/src/persistenceSchema.ts`- Persisted payload versions (`v1`, `v2`)- Thread/message/project schemas@@ -23,12 +27,15 @@ Use explicit Zod schemas for localStorage state parsing and migration.- Unknown thread/project references filtered## Risks+- Overly strict schemas could drop valid historical data unexpectedly.## Validation+- Unit tests for migration/hydration.- Manual reload test with existing localStorage data.## Done Criteria+- Store hydration logic is schema-driven.- Migration behavior is tested and documented.diff --git a/.plans/06-provider-logstream-lifecycle.md b/.plans/06-provider-logstream-lifecycle.mdindex 71d1cbd95..0a92de36f 100644--- a/.plans/06-provider-logstream-lifecycle.md+++ b/.plans/06-provider-logstream-lifecycle.md@@ -1,17 +1,21 @@# Plan: Add Provider Log Stream Lifecycle Management## Summary+Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.## Motivation+- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.- Stream lifecycle is not explicit on shutdown.## Scope+- Desktop provider logging behavior.- App shutdown integration.## Proposed Changes+1. Add explicit `dispose()` on `ProviderManager`:- Remove event listeners- End/close log stream@@ -20,12 +24,15 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and4. Optional: per-session log files under `.logs/providers/`.## Risks+- Improper close sequencing may lose final log lines.## Validation+- Manual run/quit cycle to ensure no open handle warnings.- Confirm logs flush on quit and file descriptors are not leaked.## Done Criteria+- ProviderManager owns complete log stream lifecycle.- Shutdown path explicitly disposes provider resources.diff --git a/.plans/07-ci-quality-gates.md b/.plans/07-ci-quality-gates.mdindex 5ebcb0448..ff27a9dbd 100644--- a/.plans/07-ci-quality-gates.md+++ b/.plans/07-ci-quality-gates.md@@ -1,17 +1,21 @@# Plan: Add CI Workflow for Core Quality Gates## Summary+Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.## Motivation+- Repository currently has no CI workflow files.- Quality checks are only local/manual.## Scope+- `.github/workflows/ci.yml`- Bun + Turbo setup in CI.## Proposed Changes+1. Add `ci.yml` with jobs:- Setup Bun and Node environment- Install deps@@ -22,13 +26,16 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes3. Configure caching for Bun/Turbo as appropriate.## Risks+- Smoke test may be flaky in headless CI environments.- CI runtime can grow if caching is misconfigured.## Validation+- Verify workflow runs on a branch PR.- Ensure failures surface clearly by job name.## Done Criteria+- CI blocks regressions in lint/typecheck/test.- Workflow docs added to README.diff --git a/.plans/08-precommit-format-and-lint.md b/.plans/08-precommit-format-and-lint.mdindex e89289278..a919ac07e 100644--- a/.plans/08-precommit-format-and-lint.md+++ b/.plans/08-precommit-format-and-lint.md@@ -1,17 +1,21 @@# Plan: Add Pre-Commit Formatting/Lint Hooks## Summary+Introduce pre-commit automation so formatting and basic lint checks happen before commits.## Motivation+- Current lint failures include formatting-only issues.- Shift-left feedback reduces noisy CI failures and cleanup churn.## Scope+- Root tooling config and package scripts.- No runtime code changes.## Proposed Changes+1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).2. Configure staged-file tasks:- `biome format --write`@@ -20,13 +24,16 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor4. Keep checks fast to avoid developer friction.## Risks+- Slow hooks can frustrate contributors and be bypassed.- Need to ensure compatibility with Bun workspace setup.## Validation+- Create sample staged changes and verify hook behavior.- Confirm formatting fixes are applied automatically.## Done Criteria+- Pre-commit hook installed and documented.- Formatting-only lint failures drop significantly.diff --git a/.plans/09-event-state-test-expansion.md b/.plans/09-event-state-test-expansion.mdindex 226ebf4cd..35db64bc0 100644--- a/.plans/09-event-state-test-expansion.md+++ b/.plans/09-event-state-test-expansion.md@@ -1,17 +1,21 @@# Plan: Expand Event/State Transition Test Coverage## Summary+Add focused tests for renderer event handling and session evolution logic.## Motivation+- Core behavior is event-driven and stateful.- Existing renderer tests cover only a subset of timeline/model behavior.## Scope+- `apps/renderer/src/session-logic.test.ts`- Optional reducer tests for `apps/renderer/src/store.ts`.## Proposed Changes+1. Add tests for `evolveSession`:- `thread/started`- `turn/started`@@ -24,12 +28,15 @@ Add focused tests for renderer event handling and session evolution logic.3. Add reducer integration tests for `APPLY_EVENT`.## Risks+- Tests may be brittle if event payload fixtures are too coupled to implementation details.## Validation+- `bun run test`- Ensure new tests remain deterministic and fast.## Done Criteria+- High-risk event transitions are covered by unit tests.- Regressions in stream assembly/session status are caught quickly.diff --git a/.plans/10-unify-process-session-abstraction.md b/.plans/10-unify-process-session-abstraction.mdindex c3feec020..72f5d618b 100644--- a/.plans/10-unify-process-session-abstraction.md+++ b/.plans/10-unify-process-session-abstraction.md@@ -1,17 +1,21 @@# Plan: Unify Process and PTY Session Abstractions in ProcessManager## Summary+Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.## Motivation+- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.- New execution backends/providers will multiply complexity.## Scope+- Desktop process execution internals.- Preserve public `ProcessManager` API.## Proposed Changes+1. Introduce internal interface (e.g. `RuntimeSession`):- `write(data)`- `kill()`@@ -24,12 +28,15 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr5. Add tests for both implementations.## Risks+- PTY behavior differs by platform; abstraction must not hide required differences.## Validation+- Existing `processManager.test.ts` passes.- Add PTY-path tests where feasible.## Done Criteria+- Manager no longer branches per backend in `write/kill/killAll`.- Session backends are independently testable.diff --git a/.plans/11-effect.md b/.plans/11-effect.mdindex 05f118dd7..66521c20a 100644--- a/.plans/11-effect.md+++ b/.plans/11-effect.md@@ -1,5 +1,3 @@--PR 1: Service contracts + error taxonomyAdd ProviderService, CodexService, CheckpointStore as Context.Tag service defs.Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).@@ -39,4 +37,4 @@ Remove throw-based flow entirely from provider path.PR 10: Cleanup + deprecation removalRemove legacy class implementations/adapters once parity is proven.Finalize layer composition and startup graph docs.-Add architecture notes for service boundaries and error model.\ No newline at end of file+Add architecture notes for service boundaries and error model.diff --git a/.plans/12-effect-new.md b/.plans/12-effect-new.mdindex 556b6c92b..3d87049f8 100644--- a/.plans/12-effect-new.md+++ b/.plans/12-effect-new.md@@ -1,12 +1,14 @@# Effect Migration Plan (From Current State)Current status summary:+- Service contracts, typed errors, and most checkpoint/persistence services exist.- `ProviderServiceLive` is already native orchestration (not a thin adapter).- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.- Checkpoint flow now avoids snapshot re-sync and is write-time driven.## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`+- Build one runtime layer graph for provider + checkpoint + persistence + orchestration.- Resolve `ProviderService` from runtime in `wsServer`.- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.@@ -14,12 +16,14 @@ Current status summary:- Keep WS method/push payloads identical.## PR 2: Runtime Composition + Startup Ownership+- Create/centralize `AppLive` composition for server startup.- Ensure outer runtime provides Node/platform services once.- Ensure migrations run at startup via scoped/layer startup path.- Remove ad-hoc service initialization in request-time paths.## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants+- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.- Remove per-session lock/cwd map leaks.- Keep strict invariant model:@@ -29,12 +33,14 @@ Current status summary:- Add tests for lifecycle cleanup and invariant-failure surfaces.## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)+- Keep `ProviderService` as the public event surface.- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control.- Keep API as `subscribeToEvents` unless we explicitly choose stream API later.- Add tests for ordering and subscriber isolation under load.## PR 5: Codex Runtime Split (Scoped Effect Core)+- Extract `CodexAppServerManager` responsibilities into Effect-native layers:- scoped process lifecycle- RPC request/response + pending map via `Deferred`@@ -43,16 +49,19 @@ Current status summary:- Preserve protocol behavior and timeout semantics.## PR 6: Codex Protocol Decode Hardening+- Replace ad-hoc unknown parsing with runtime schema decode.- Map decode failures to typed tagged errors with `cause` retained.- Add regression tests for malformed/partial protocol frames.## PR 7: Remove Legacy Provider Stack+- Remove `ProviderManager` + legacy checkpoint integration from runtime path.- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).- Update tests to assert only Effect service path is used.## PR 8: Final Cleanup + Docs+- Update architecture docs with final layer graph and service boundaries.- Document error model and recovery semantics.- Trim dead compatibility code and stale plan references.diff --git a/.plans/13-provider-service-integration-tests.md b/.plans/13-provider-service-integration-tests.mdindex 0cc916429..f3fe4edf0 100644--- a/.plans/13-provider-service-integration-tests.md+++ b/.plans/13-provider-service-integration-tests.md@@ -1,6 +1,7 @@# ProviderService Integration Test PlanGoal:+- Validate end-to-end `ProviderService` behavior with real layers:- `ProviderServiceLive`- `CheckpointServiceLive`@@ -13,6 +14,7 @@ Goal:## Test HarnessBuild a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:+- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.- Internal state:- session registry (session + cwd + threadId)@@ -29,13 +31,15 @@ Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Lay- `readThread`, `rollbackThread`, `stopSession`, `stopAll`.Use real git-backed temporary workspaces in integration tests:+- initialize repo with baseline commit- run provider turn in workspace- assert checkpoint diffs against real git refs## Core Integration Specs-1) `startSession` initializes checkpoint root exactly once+1. `startSession` initializes checkpoint root exactly once+- Arrange:- start provider session in git repo.- Assert:@@ -43,7 +47,8 @@ Use real git-backed temporary workspaces in integration tests:- checkpoint ref exists in git.- second `startSession` for new session creates a new independent root.-2) Turn without filesystem change+2. Turn without filesystem change+- Arrange:- emit normal turn events, no file mutation.- Assert:@@ -54,7 +59,8 @@ Use real git-backed temporary workspaces in integration tests:- `listCheckpoints` returns root + turn 1.- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.-3) Turn with filesystem change+3. Turn with filesystem change+- Arrange:- mutate `README.md` during turn.- Assert:@@ -62,7 +68,8 @@ Use real git-backed temporary workspaces in integration tests:- `getCheckpointDiff(0 -> 1)` contains file path and hunk.- persisted checkpoint metadata includes non-empty `checkpointRef`.-4) Multi-turn sequencing and checkpoint monotonicity+4. Multi-turn sequencing and checkpoint monotonicity+- Arrange:- turn 1: no file change- turn 2: file change@@ -72,7 +79,8 @@ Use real git-backed temporary workspaces in integration tests:- latest checkpoint is marked current.- diffs for adjacent turns map to expected filesystem deltas.-5) Revert to checkpoint+5. Revert to checkpoint+- Arrange:- execute 3 turns with at least one file-changing turn.- call `revertToCheckpoint(turnCount=1)`.@@ -82,7 +90,8 @@ Use real git-backed temporary workspaces in integration tests:- DB rows for turns >1 are removed.- later refs are deleted from git.-6) Capture failure surface+6. Capture failure surface+- Arrange:- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.- Assert:@@ -92,6 +101,7 @@ Use real git-backed temporary workspaces in integration tests:## WebSocket Coverage (Thin Integration)Add one ws server integration spec:+- Subscribe to `providers.event`.- Run a deterministic provider turn through ws methods.- Assert push stream includes:@@ -101,10 +111,13 @@ Add one ws server integration spec:## Proposed PR SplitPR A:+- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).PR B:+- Core ProviderService integration specs (cases 1-4).PR C:+- Revert + failure-path specs (cases 5-6) + ws thin integration spec.diff --git a/.plans/14-server-authoritative-event-sourcing-cleanup.md b/.plans/14-server-authoritative-event-sourcing-cleanup.mdindex c73cbc883..e5c502320 100644--- a/.plans/14-server-authoritative-event-sourcing-cleanup.md+++ b/.plans/14-server-authoritative-event-sourcing-cleanup.md@@ -1,6 +1,7 @@# Server-Authoritative Event-Sourcing Cleanup PlanGoal:+- Move to a cleaner service architecture with:- durable, server-authoritative event sourcing- strict command routing/validation@@ -85,6 +86,7 @@ CheckpointCatalog ------> SQLite## Commit Series### Commit 1: Split public vs system orchestration command contracts+- Create separate schemas/types:- `ClientOrchestrationCommandSchema`- `SystemOrchestrationCommandSchema`@@ -100,6 +102,7 @@ CheckpointCatalog ------> SQLite- preserve internal dispatch functionality for system commands### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary+- Add dedicated router service to validate, authorize, and route commands.- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).@@ -113,6 +116,7 @@ CheckpointCatalog ------> SQLite- handler happy-path tests per command type### Commit 3: Harden event store for idempotency + optimistic append metadata+- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.- Add optional aggregate version metadata for future optimistic concurrency.@@ -125,6 +129,7 @@ CheckpointCatalog ------> SQLite- concurrent append behavior stays ordered and deterministic### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`+- Create `ProviderRuntimeIngestionService` that:- subscribes to `ProviderService.streamEvents`- translates runtime events into orchestration commands@@ -139,6 +144,7 @@ CheckpointCatalog ------> SQLite- ws integration confirms same external push behavior### Commit 5: Make session directory durable (`ProviderSessionRegistry`)+- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.- Keep in-memory cache optional, but source of truth must be persistent.- Add startup reconciliation to prune dead sessions / keep known thread mapping.@@ -152,6 +158,7 @@ CheckpointCatalog ------> SQLite- stale session cleanup semantics### Commit 6: Re-key checkpoint metadata from session to thread identity+- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.- Keep `session_id` as nullable metadata only.- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.@@ -165,6 +172,7 @@ CheckpointCatalog ------> SQLite- revert/diff still work after session churn### Commit 7: Add durable projection persistence for orchestration read models+- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.- Keep event stream as source of truth; projection rebuild stays deterministic.- `getSnapshot` reads from projection store (memory cache optional).@@ -177,6 +185,7 @@ CheckpointCatalog ------> SQLite- projection rebuild from events yields same result as previous reducer semantics### Commit 8: Narrow `ProviderService` responsibilities+- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.- Preserve adapter pluggability and provider-neutral contracts.@@ -188,6 +197,7 @@ CheckpointCatalog ------> SQLite- checkpoint capture still triggered by turn completion through new coordinator### Commit 9: Look over schemas (contracts and events)+- Scan for unused schemas.- Use effect/Schema everywhere- Analyze which we need@@ -196,6 +206,7 @@ CheckpointCatalog ------> SQLite- Persistence entities### Commit 10: Remove dead legacy path and finalize docs+- Remove unused legacy manager/store path from active architecture:- `providerManager.ts`- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)@@ -210,6 +221,7 @@ CheckpointCatalog ------> SQLite- no regressions in WS protocol behavior## Risk Controls+- Keep WS method names and payload contracts stable throughout.- Gate each commit with targeted integration tests before moving forward.- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.diff --git a/.plans/15-effect-server.md b/.plans/15-effect-server.mdindex 50e869d49..5e245bb8e 100644--- a/.plans/15-effect-server.md+++ b/.plans/15-effect-server.md@@ -1,10 +1,11 @@Rewrite `createServer` and `index.ts` to be Effect native.Maybe use `effect/unstable/Socket` for the web socket server+- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts- Migrate remaining runtime code to Effect- `gitManager` -> `src/git`- `terminalManager` -> `src/terminal` (Manager + PTY)- - ...\ No newline at end of file+ - ...diff --git a/.plans/16-pr89-review-remediation-phases.md b/.plans/16-pr89-review-remediation-phases.mdindex 52bedc2ef..81ed6bd9f 100644--- a/.plans/16-pr89-review-remediation-phases.md+++ b/.plans/16-pr89-review-remediation-phases.md@@ -24,21 +24,25 @@- Mark invalid/false-positive items with explicit rationale.Exit criteria:+- Every open thread is mapped to one canonical fix item or marked invalid.## Phase 1: Runtime Survival and Critical Event WiringRelated bug groups solved together:+- Worker loop/fiber fatal error handling in orchestration reactors.- WebSocket message error boundaries and unhandled rejection guards.- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).Primary files:+- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`- `apps/server/src/wsServer.ts`Exit criteria:+- A single event-processing failure cannot permanently stop ingestion/reactor loops.- WS message handling cannot produce unhandled promise rejections.- Invalid provider-event-channel review findings are closed with architecture rationale.@@ -46,17 +50,20 @@ Exit criteria:## Phase 2: State Consistency and OrderingRelated bug groups solved together:+- Fire-and-forget revert completion causing consistency windows.- Non-atomic append/projection paths and retry behavior.- Race-sensitive thread/event association issues.Primary files:+- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`Exit criteria:+- Revert flow is deterministically reflected in read model updates.- Append/project failure mode is explicit and safe under retry.- No cross-thread misassociation under concurrent runtime events.@@ -64,12 +71,14 @@ Exit criteria:## Phase 3: Checkpointing Correctness BundleRelated bug groups solved together:+- Checkpoint input normalization consistency.- Snapshot/projector coverage mismatches.- Checkpoint ref/workspace CWD utility duplication.- Checkpoint diff/error handling behavior gaps.Primary files:+- `apps/server/src/checkpointing/Layers/CheckpointStore.ts`- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`@@ -77,6 +86,7 @@ Primary files:- `apps/server/src/wsServer.ts`Exit criteria:+- Checkpoint capture/restore/revert paths use one normalization policy.- Required projectors are actually represented in snapshot reads.- Shared checkpoint/ref/CWD helpers are centralized.@@ -84,27 +94,32 @@ Exit criteria:## Phase 4: Memory and Lifecycle HygieneRelated bug groups solved together:+- Unbounded in-memory dedup sets/maps.- Missing cleanup/lifecycle protections in long-lived effects/resources.Primary files:+- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`- `apps/server/src/config.ts`Exit criteria:+- Long-running server memory does not grow unbounded from dedup bookkeeping.- Resource cleanup paths are registered for interruption/shutdown.## Phase 5: Transport, Parsing, and Platform Edge CasesRelated bug groups solved together:+- UTF-8 chunk boundary decode correctness.- Markdown/file-link parsing edge cases.- Shell/OS-specific PATH parsing behavior.- Git rename parsing and small keybinding edge cases.Primary files:+- `apps/server/src/wsServer.ts`- `apps/server/src/git/Layers/CodexTextGeneration.ts`- `apps/web/src/markdown-links.ts`@@ -113,23 +128,27 @@ Primary files:- `apps/server/src/keybindings.ts`Exit criteria:+- Edge-case parsers are robust across valid but non-trivial inputs.- Platform-dependent command behavior has safe fallbacks.## Phase 6: Build and Maintainability CleanupRelated bug groups solved together:+- Build script/runtime assumption cleanup.- Redundant error-union declarations and utility/type duplication.- Non-functional cleanup comments/docs markers.Primary files:+- `apps/server/package.json`- `apps/server/src/checkpointing/Errors.ts`- Shared utility locations introduced during earlier phases- `AGENTS.md` (if cleanup is still pending)Exit criteria:+- Build path is explicit and environment-safe.- Redundant types/utilities are removed in favor of single sources of truth.@@ -140,6 +159,7 @@ Exit criteria:- Resolve threads with fix references per canonical checklist item.Exit criteria:+- Lint passes.- Backend tests pass.- All actionable review threads are resolved or explicitly justified.diff --git a/.plans/16c-pr89-remediation-checklist.md b/.plans/16c-pr89-remediation-checklist.mdindex c77b59dda..6512e9246 100644--- a/.plans/16c-pr89-remediation-checklist.md+++ b/.plans/16c-pr89-remediation-checklist.md@@ -5,6 +5,7 @@ _Last updated: 2026-02-26_This is the working checklist for remediation execution.Status values:+- `TODO`: Not started- `IN_PROGRESS`: Currently being worked- `BLOCKED`: Waiting on decision/dependency@@ -150,7 +151,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`- Area: `WebSocket robustness`- File: `apps/web/src/wsTransport.ts:59`- Threads: PRRT_kwDORLtfbc5whtrN- - Audit note: Transport _tag override risk exists but current callsites are constrained.+ - Audit note: Transport \_tag override risk exists but current callsites are constrained.### Phase 2@@ -181,7 +182,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`- Threads: PRRT_kwDORLtfbc5whxJO- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.-- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes *after* the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>+- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>- Status: `DONE`- Verdict: `valid`- Severity: `Medium`@@ -198,7 +199,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`- Severity: `Medium`- Area: `Checkpointing correctness`- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94`- - Threads: PRRT_kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv_, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))+ - Threads: PRRT*kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv*, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>@@ -250,7 +251,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`### Phase 5-- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after ` => ` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>+- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>- Status: `TODO`- Verdict: `valid`- Severity: `Medium`diff --git a/.plans/spec-1-1-cutover-plan.md b/.plans/spec-1-1-cutover-plan.mdindex d48937b40..7345995f1 100644--- a/.plans/spec-1-1-cutover-plan.md+++ b/.plans/spec-1-1-cutover-plan.md@@ -3,13 +3,16 @@Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.Execution mode for this plan:+- Hard cutover only. Existing DB and migration history are disposable.- Intermediate steps are allowed to break runtime, tests, typecheck, and lint.- We optimize for small, reviewable work units, not continuous app operability.- Only the final gate requires everything to run cleanly.## 1. Freeze SPEC contract as source of truth+Work units:+- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`.- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants.- Add app-level requirements per row: writer path, reader path, and owning module.@@ -17,17 +20,22 @@ Work units:- Identify any ambiguous spec lines and record a concrete interpretation in the matrix.Deliverables:+- Complete matrix file with no unclassified rows.- Single source checklist used by all later steps.Breakage allowed:+- No code changes required yet.Exit criteria:+- Every requirement in `7.1`-`7.4` has exactly one matrix row.## 2. Hard cutover migrations (replace current migration set)+Work units:+- Delete the current legacy migration files and rewrite migration loader ordering.- Create `001_orchestration_events.ts` with full envelope columns and required event indexes.- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes.@@ -47,17 +55,22 @@ Work units:- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.Deliverables:+- New 5-file migration chain.- Updated migration loader references only new migrations.Breakage allowed:+- Repositories/services can be temporarily broken due to removed old tables.Exit criteria:+- Fresh DB initializes with only canonical tables plus migration bookkeeping.## 3. Align persistence row/request schemas to DB 1:1+Work units:+- Define row schemas for each canonical table (contracts or persistence layer module).- Define request schemas for every insert/update/query operation touching canonical tables.- Remove or deprecate row/request schemas tied to deleted legacy tables.@@ -65,17 +78,22 @@ Work units:- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).Deliverables:+- Canonical row/request schemas committed.- Zero references to legacy row schemas in active code paths.Breakage allowed:+- Runtime can still fail while query layers are being rewired.Exit criteria:+- Every canonical table used in code has a typed row schema and typed request schema.## 4. Rewrite event store for full persisted envelope+Work units:+- Refactor append path to write full envelope fields:- `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json`- Implement stream version assignment/checking per aggregate stream.@@ -84,16 +102,21 @@ Work units:- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).Deliverables:+- Event store append/replay fully aligned with canonical envelope.Breakage allowed:+- Command dispatch flow can be partially broken until receipts/projectors are updated.Exit criteria:+- Event store no longer depends on legacy event table shape.## 5. Add command receipt idempotency+Work units:+- Introduce persistence access layer for `orchestration_command_receipts`.- In command dispatch flow, check existing receipt by `commandId` before append.- On first execution, persist accepted receipt with `resultSequence`.@@ -102,16 +125,21 @@ Work units:- Ensure receipt write and event append ordering is deterministic.Deliverables:+- Dispatch path with idempotency behavior wired through receipts.Breakage allowed:+- Snapshot/read model may still be inconsistent until projectors are fully wired.Exit criteria:+- Duplicate command IDs no longer create duplicate events.## 6. Build DB-backed projection pipeline+Work units:+- Create projector runner that consumes events and applies table-specific projections.- Implement projector handlers for each projection table.- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction.@@ -120,16 +148,21 @@ Work units:- Add safe resume logic from projector `last_applied_sequence`.Deliverables:+- Persistent projector pipeline writing all `projection_*` tables.Breakage allowed:+- Web/API layer may still read old in-memory model until step 7.Exit criteria:+- Events drive projection rows in DB; projection state advances transactionally.## 7. Move RPC reads to projections and diff blobs+Work units:+- Implement snapshot query service reading only projection tables.- Build thread hydration from projection rows: messages, activities, checkpoints, session.- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`.@@ -138,16 +171,21 @@ Work units:- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.Deliverables:+- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.Breakage allowed:+- Provider runtime persistence may still be partially legacy until step 8.Exit criteria:+- No orchestration read RPC depends on legacy tables or in-memory-only state.## 8. Migrate provider runtime persistence to canonical table+Work units:+- Create repository/service for `provider_session_runtime`.- Update adapter/session manager to persist runtime/resume cursor in new table.- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`.@@ -155,16 +193,21 @@ Work units:- Verify restart/resume path reads runtime state from canonical table only.Deliverables:+- Provider runtime state entirely backed by `provider_session_runtime`.Breakage allowed:+- Some legacy interfaces may still exist but should be disconnected.Exit criteria:+- Runtime restore no longer reads/writes legacy provider session persistence.## 9. Remove old cruft aggressively+Work units:+- Delete legacy repositories/services that map to removed tables.- Remove dead migration imports and obsolete persistence service interfaces.- Remove compatibility code paths that translate legacy row shapes.@@ -172,16 +215,21 @@ Work units:- Update internal docs/comments to reference canonical projection/event model only.Deliverables:+- Legacy persistence and translation layers removed from active codebase.Breakage allowed:+- Temporary compile failures acceptable while deletion/refactor is in progress.Exit criteria:+- No production code path references deleted legacy tables/services.## 10. Final verification gate (first point where green is required)+Work units:+- Add migration tests that assert canonical tables, columns, constraints, and indexes.- Add event store tests for envelope persistence, metadata, actor kind, and replay.- Add receipt idempotency tests for accept/reject/duplicate paths.@@ -192,10 +240,13 @@ Work units:- Run project lint/typecheck/tests and fix failures.Deliverables:+- Green checks with canonical schema + persistence model in place.Breakage allowed:+- None at end of step.Exit criteria:+- SPEC `7.1`-`7.4` requirements satisfied and validated by tests.diff --git a/.plans/spec-contract-matrix.md b/.plans/spec-contract-matrix.mdindex 842f0d25d..7cbb9509a 100644--- a/.plans/spec-contract-matrix.md+++ b/.plans/spec-contract-matrix.md@@ -1,6 +1,7 @@# SPEC Contract Matrix (Sections 7.1-7.4)Status legend:+- `required`: requirement acknowledged, no current implementation claim yet.- `implemented`: requirement currently satisfied in code + schema.- `to-replace`: partial/misaligned implementation exists and must be replaced.@@ -9,6 +10,7 @@ Status legend:## 7.1 Write-Side Persisted Tables### W1+- Spec ref: `7.1.1 orchestration_events`- Requirement: append-only event store with canonical envelope columns.- SQL contract:@@ -32,6 +34,7 @@ Status legend:- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.### W2+- Spec ref: `7.1.2 orchestration_command_receipts`- Requirement: command idempotency + ack replay receipts table.- SQL contract:@@ -49,6 +52,7 @@ Status legend:- Notes: missing table and missing idempotency flow.### W3+- Spec ref: `7.1.3 checkpoint_diff_blobs`- Requirement: store large plaintext diffs separate from checkpoint summaries.- SQL contract:@@ -65,6 +69,7 @@ Status legend:- Notes: no canonical diff blob table yet.### W4+- Spec ref: `7.1.4 provider_session_runtime`- Requirement: server-internal provider runtime/resume state.- SQL contract:@@ -86,6 +91,7 @@ Status legend:## 7.2 Canonical Persisted Event Schema### E1+- Spec ref: `7.2 OrchestrationPersistedEventSchema`- Requirement: full typed persisted event envelope in shared contracts.- SQL contract: envelope fields in W1 must map 1:1 to contracts schema.@@ -96,6 +102,7 @@ Status legend:- Notes: contract schema exists; DB + store mapping still incomplete.### E2+- Spec ref: `7.2 Rules/payload discriminated by eventType`- Requirement: `payload` validation keyed by `eventType`.- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected.@@ -106,6 +113,7 @@ Status legend:- Notes: decode is present but DB does not persist full envelope columns.### E3+- Spec ref: `7.2 Rules/provider ids scope`- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement.- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id.@@ -116,6 +124,7 @@ Status legend:- Notes: metadata plumbing is incomplete in persistence path.### E4+- Spec ref: `7.2 Rules/streamVersion concurrency guard`- Requirement: stream version monotonic per aggregate stream; enforced on write.- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream.@@ -128,6 +137,7 @@ Status legend:## 7.3 Required Projected Tables (Read Models)### P1+- Spec ref: `7.3.1 projection_projects`- Requirement: persisted project projection table.- SQL contract:@@ -145,6 +155,7 @@ Status legend:- Notes: legacy `projects` table is separate concept and should be removed from orchestration model.### P2+- Spec ref: `7.3.2 projection_threads`- Requirement: persisted thread projection table.- SQL contract:@@ -165,6 +176,7 @@ Status legend:- Notes: missing table and projector writes.### P3+- Spec ref: `7.3.3 projection_thread_messages`- Requirement: persisted thread message projection table.- SQL contract:@@ -183,6 +195,7 @@ Status legend:- Notes: missing table and message projection writes.### P4+- Spec ref: `7.3.4 projection_thread_activities`- Requirement: persisted thread activity projection table.- SQL contract:@@ -201,6 +214,7 @@ Status legend:- Notes: no canonical activity projection persistence.### P5+- Spec ref: `7.3.5 projection_thread_sessions`- Requirement: persisted thread session projection table.- SQL contract:@@ -219,6 +233,7 @@ Status legend:- Notes: current provider session table is not this domain projection.### P6+- Spec ref: `7.3.6 projection_thread_turns`- Requirement: persisted thread turn projection table.- SQL contract:@@ -237,6 +252,7 @@ Status legend:- Notes: missing table and projection logic.### P7+- Spec ref: `7.3.7 projection_checkpoints`- Requirement: persisted checkpoint summary projection table.- SQL contract:@@ -256,6 +272,7 @@ Status legend:- Notes: current table semantics do not match canonical checkpoint projection schema.### P8+- Spec ref: `7.3.8 projection_pending_approvals`- Requirement: persisted pending-approval projection table.- SQL contract:@@ -273,6 +290,7 @@ Status legend:- Notes: missing table and projection logic.### P9+- Spec ref: `7.3.9 projection_state`- Requirement: projector progress tracking table.- SQL contract:@@ -286,6 +304,7 @@ Status legend:- Notes: missing table and projector bookkeeping.### P10+- Spec ref: `7.3 Projection consistency rules`- Requirement: projector row updates and `projection_state` update must be atomic per event.- SQL contract: per-projector transaction boundary covering both projection write and state update.@@ -296,6 +315,7 @@ Status legend:- Notes: requires transactional projection executor.### P11+- Spec ref: `7.3 Optional debug field`- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.- SQL contract: optional; not required in baseline schema.@@ -308,6 +328,7 @@ Status legend:## 7.4 Snapshot and RPC Requirements### R1+- Spec ref: `7.4.1`- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`.@@ -318,6 +339,7 @@ Status legend:- Notes: current in-memory read model path must be removed for SPEC compliance.### R2+- Spec ref: `7.4.2`- Requirement: snapshot `projects[]` source is `projection_projects`.- SQL contract: `projects` collection assembled from `projection_projects` rows.@@ -328,6 +350,7 @@ Status legend:- Notes: no DB project projection reader exists yet.### R3+- Spec ref: `7.4.3`- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`.@@ -338,6 +361,7 @@ Status legend:- Notes: canonical projection table and reader not implemented.### R4+- Spec ref: `7.4.4`- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.@@ -348,6 +372,7 @@ Status legend:- Notes: current checkpoint repository is not canonical source.### R5+- Spec ref: `7.4.5`- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.- SQL contract: session lookup by `thread_id` from projection table.@@ -358,6 +383,7 @@ Status legend:- Notes: remove provider-session-as-routing-key behavior.### R6+- Spec ref: `7.4.6`- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.- SQL contract: `MIN(last_applied_sequence)` across required projector keys.@@ -368,6 +394,7 @@ Status legend:- Notes: must move from in-memory sequence to DB projection-state semantics.### R7+- Spec ref: `7.4.7`- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence).- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start.@@ -380,22 +407,27 @@ Status legend:## Ambiguous/Interpretation Decisions (tracked upfront)### A1+- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.### A2+- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.### A3+- Topic: `snapshotSequence` dependency set for min-sequence computation.- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).### A4+- Topic: no-gap handoff mechanism in `7.4.7`.- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.## Checklist Completeness Statement+- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.- Unclassified rows: `0`.diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjsindex 5d8bbe111..cf5dc2669 100644--- a/apps/desktop/scripts/dev-electron.mjs+++ b/apps/desktop/scripts/dev-electron.mjs@@ -7,7 +7,11 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);const devServerUrl = `http://localhost:${port}`;-const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];+const requiredFiles = [+ "dist-electron/main.js",+ "dist-electron/preload.js",+ "../server/dist/index.mjs",+];const watchedDirectories = [{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },{ directory: "../server/dist", files: new Set(["index.mjs"]) },@@ -148,13 +152,17 @@ function scheduleRestart() {function startWatchers() {for (const { directory, files } of watchedDirectories) {- const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {- if (typeof filename !== "string" || !files.has(filename)) {- return;- }+ const watcher = watch(+ join(desktopDir, directory),+ { persistent: true },+ (_eventType, filename) => {+ if (typeof filename !== "string" || !files.has(filename)) {+ return;+ }- scheduleRestart();- });+ scheduleRestart();+ },+ );watchers.push(watcher);}diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 03cf67cd6..4fec75804 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -15,10 +15,7 @@ import { NetService } from "@t3tools/shared/Net";import { RotatingFileSink } from "@t3tools/shared/logging";import { showDesktopConfirmDialog } from "./confirmDialog";import { fixPath } from "./fixPath";-import {- getAutoUpdateDisabledReason,- shouldBroadcastDownloadProgress,-} from "./updateState";+import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";import {createInitialDesktopUpdateState,reduceDesktopUpdateStateOnCheckFailure,@@ -702,7 +699,9 @@ async function checkForUpdates(reason: string): Promise<void> {await autoUpdater.checkForUpdates();} catch (error: unknown) {const message = error instanceof Error ? error.message : String(error);- setUpdateState(reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()));+ setUpdateState(+ reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),+ );console.error(`[desktop-updater] Failed to check for updates: ${message}`);} finally {updateCheckInFlight = false;@@ -764,9 +763,7 @@ function configureAutoUpdater(): void {updaterConfigured = true;const githubToken =- process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() ||- process.env.GH_TOKEN?.trim() ||- "";+ process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";if (githubToken) {// When a token is provided, re-configure the feed with `private: true` so// electron-updater uses the GitHub API (api.github.com) instead of the@@ -801,7 +798,13 @@ function configureAutoUpdater(): void {console.info("[desktop-updater] Looking for updates...");});autoUpdater.on("update-available", (info) => {- setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));+ setUpdateState(+ reduceDesktopUpdateStateOnUpdateAvailable(+ updateState,+ info.version,+ new Date().toISOString(),+ ),+ );lastLoggedDownloadMilestone = -1;console.info(`[desktop-updater] Update available: ${info.version}`);});diff --git a/apps/desktop/src/runtimeArch.ts b/apps/desktop/src/runtimeArch.tsindex 7e4265afb..127abf51a 100644--- a/apps/desktop/src/runtimeArch.ts+++ b/apps/desktop/src/runtimeArch.ts@@ -25,8 +25,7 @@ export function resolveDesktopRuntimeInfo(};}- const hostArch =- appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;+ const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;return {hostArch,diff --git a/apps/desktop/src/updateMachine.test.ts b/apps/desktop/src/updateMachine.test.tsindex 620c683b8..7fbc982ef 100644--- a/apps/desktop/src/updateMachine.test.ts+++ b/apps/desktop/src/updateMachine.test.ts@@ -83,7 +83,10 @@ describe("updateMachine", () => {},"1.1.0",);- const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");+ const failedInstall = reduceDesktopUpdateStateOnInstallFailure(+ downloaded,+ "backend shutdown timed out",+ );expect(downloaded.status).toBe("downloaded");expect(downloaded.downloadedVersion).toBe("1.1.0");diff --git a/apps/server/integration/TestProviderAdapter.integration.ts b/apps/server/integration/TestProviderAdapter.integration.tsindex 82c08da3e..017c59e2c 100644--- a/apps/server/integration/TestProviderAdapter.integration.ts+++ b/apps/server/integration/TestProviderAdapter.integration.ts@@ -72,10 +72,9 @@ function normalizeTurnState(value: unknown): "completed" | "failed" | "interruptreturn "completed";}-function mapRequestType(requestKind: unknown):- | "command_execution_approval"- | "file_change_approval"- | "unknown" {+function mapRequestType(+ requestKind: unknown,+): "command_execution_approval" | "file_change_approval" | "unknown" {if (requestKind === "command") {return "command_execution_approval";}@@ -239,323 +238,323 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter}>>();- const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);+ const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);- const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>- Effect.gen(function* () {- if (input.provider !== undefined && input.provider !== provider) {- return yield* new ProviderAdapterValidationError({- provider,- operation: "startSession",- issue: `Expected provider '${provider}' but received '${input.provider}'.`,- });- }+ const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>+ Effect.gen(function* () {+ if (input.provider !== undefined && input.provider !== provider) {+ return yield* new ProviderAdapterValidationError({+ provider,+ operation: "startSession",+ issue: `Expected provider '${provider}' but received '${input.provider}'.`,+ });+ }- sessionCount += 1;- const threadId = input.threadId;- const createdAt = nowIso();-- const session: ProviderSession = {- provider,- status: "ready",- runtimeMode: input.runtimeMode,- threadId,- cwd: input.cwd,- resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },- createdAt,- updatedAt: createdAt,- };-- sessions.set(threadId, {- session,- snapshot: {+ sessionCount += 1;+ const threadId = input.threadId;+ const createdAt = nowIso();++ const session: ProviderSession = {+ provider,+ status: "ready",+ runtimeMode: input.runtimeMode,threadId,- turns: [],- },- turnCount: 0,- queuedResponses: queuedResponsesForNextSession.splice(0),- rollbackCalls: [],- });+ cwd: input.cwd,+ resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },+ createdAt,+ updatedAt: createdAt,+ };- return session;- });+ sessions.set(threadId, {+ session,+ snapshot: {+ threadId,+ turns: [],+ },+ turnCount: 0,+ queuedResponses: queuedResponsesForNextSession.splice(0),+ rollbackCalls: [],+ });- const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>- Effect.gen(function* () {- const state = sessions.get(input.threadId);- if (!state) {- return yield* missingSessionEffect(provider, input.threadId);- }+ return session;+ });- state.turnCount += 1;- const turnCount = state.turnCount;- const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);+ const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>+ Effect.gen(function* () {+ const state = sessions.get(input.threadId);+ if (!state) {+ return yield* missingSessionEffect(provider, input.threadId);+ }- const response = state.queuedResponses.shift();- if (!response) {- return yield* new ProviderAdapterValidationError({- provider,- operation: "sendTurn",- issue: `No queued turn response for thread ${input.threadId}.`,- });- }+ state.turnCount += 1;+ const turnCount = state.turnCount;+ const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);- const assistantDeltas: string[] = [];- const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];- for (const fixtureEvent of response.events) {- const rawEvent: Record<string, unknown> = {- ...(fixtureEvent as Record<string, unknown>),- eventId: randomUUID(),- provider,- sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),- createdAt: nowIso(),- };- rawEvent.threadId = state.snapshot.threadId;- if (Object.hasOwn(rawEvent, "turnId")) {- rawEvent.turnId = turnId;+ const response = state.queuedResponses.shift();+ if (!response) {+ return yield* new ProviderAdapterValidationError({+ provider,+ operation: "sendTurn",+ issue: `No queued turn response for thread ${input.threadId}.`,+ });}- const runtimeEvent = normalizeFixtureEvent(rawEvent);- const runtimeType = (runtimeEvent as { type: string }).type;- if (runtimeType === "content.delta") {- const payload = runtimeEvent.payload as { delta?: unknown } | undefined;- if (typeof payload?.delta === "string") {- assistantDeltas.push(payload.delta);+ const assistantDeltas: string[] = [];+ const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];+ for (const fixtureEvent of response.events) {+ const rawEvent: Record<string, unknown> = {+ ...(fixtureEvent as Record<string, unknown>),+ eventId: randomUUID(),+ provider,+ sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),+ createdAt: nowIso(),+ };+ rawEvent.threadId = state.snapshot.threadId;+ if (Object.hasOwn(rawEvent, "turnId")) {+ rawEvent.turnId = turnId;+ }++ const runtimeEvent = normalizeFixtureEvent(rawEvent);+ const runtimeType = (runtimeEvent as { type: string }).type;+ if (runtimeType === "content.delta") {+ const payload = runtimeEvent.payload as { delta?: unknown } | undefined;+ if (typeof payload?.delta === "string") {+ assistantDeltas.push(payload.delta);+ }+ } else if (runtimeType === "message.delta") {+ const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;+ if (typeof legacyDelta === "string") {+ assistantDeltas.push(legacyDelta);+ }}- } else if (runtimeType === "message.delta") {- const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;- if (typeof legacyDelta === "string") {- assistantDeltas.push(legacyDelta);+ if (runtimeEvent.type === "turn.completed") {+ deferredTurnCompletedEvents.push(runtimeEvent);+ continue;}++ yield* emit(runtimeEvent);}- if (runtimeEvent.type === "turn.completed") {- deferredTurnCompletedEvents.push(runtimeEvent);- continue;++ if (response.mutateWorkspace && state.session.cwd) {+ yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });}- yield* emit(runtimeEvent);- }+ const userItem = {+ type: "userMessage",+ content: [{ type: "text", text: input.input }],+ } as const;+ const assistantText = assistantDeltas.join("");+ const nextItems: Array<unknown> =+ assistantText.length > 0+ ? [userItem, { type: "agentMessage", text: assistantText }]+ : [userItem];++ const nextTurn: ProviderThreadTurnSnapshot = {+ id: turnId,+ items: nextItems,+ };- if (response.mutateWorkspace && state.session.cwd) {- yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });- }+ state.snapshot = {+ threadId: state.snapshot.threadId,+ turns: [...state.snapshot.turns, nextTurn],+ };- const userItem = {- type: "userMessage",- content: [{ type: "text", text: input.input }],- } as const;- const assistantText = assistantDeltas.join("");- const nextItems: Array<unknown> =- assistantText.length > 0- ? [userItem, { type: "agentMessage", text: assistantText }]- : [userItem];-- const nextTurn: ProviderThreadTurnSnapshot = {- id: turnId,- items: nextItems,- };-- state.snapshot = {- threadId: state.snapshot.threadId,- turns: [...state.snapshot.turns, nextTurn],- };-- if (deferredTurnCompletedEvents.length === 0) {- yield* emit({- type: "turn.completed",- eventId: EventId.makeUnsafe(randomUUID()),- provider,- createdAt: nowIso(),+ if (deferredTurnCompletedEvents.length === 0) {+ yield* emit({+ type: "turn.completed",+ eventId: EventId.makeUnsafe(randomUUID()),+ provider,+ createdAt: nowIso(),+ threadId: state.snapshot.threadId,+ turnId,+ payload: {+ state: "completed",+ },+ });+ } else {+ for (const completedEvent of deferredTurnCompletedEvents) {+ yield* emit(completedEvent);+ }+ }++ return {threadId: state.snapshot.threadId,turnId,- payload: {- state: "completed",- },- });- } else {- for (const completedEvent of deferredTurnCompletedEvents) {- yield* emit(completedEvent);- }+ } satisfies ProviderTurnStartResult;+ });++ const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (+ threadId,+ turnId,+ ) =>+ sessions.has(threadId)+ ? Effect.sync(() => {+ const existing = interruptCallsBySession.get(threadId) ?? [];+ existing.push(turnId);+ interruptCallsBySession.set(threadId, existing);+ })+ : missingSessionEffect(provider, threadId);++ const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (+ threadId,+ requestId,+ decision,+ ) =>+ sessions.has(threadId)+ ? Effect.sync(() => {+ const existing = approvalResponsesBySession.get(threadId) ?? [];+ existing.push({+ threadId,+ requestId,+ decision,+ });+ approvalResponsesBySession.set(threadId, existing);+ })+ : missingSessionEffect(provider, threadId);++ const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (+ threadId,+ _requestId,+ _answers,+ ) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));++ const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>+ Effect.sync(() => {+ sessions.delete(threadId);+ });++ const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>+ Effect.sync(() => Array.from(sessions.values(), (state) => state.session));++ const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>+ Effect.succeed(sessions.has(threadId));++ const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {+ const state = sessions.get(threadId);+ if (!state) {+ return missingSessionEffect(provider, threadId);+ }+ return Effect.succeed(state.snapshot);+ };++ const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (+ threadId,+ numTurns,+ ) => {+ const state = sessions.get(threadId);+ if (!state) {+ return missingSessionEffect(provider, threadId);+ }+ if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {+ return Effect.fail(+ new ProviderAdapterValidationError({+ provider,+ operation: "rollbackThread",+ issue: "numTurns must be an integer between 0 and current turn count.",+ }),+ );}- return {- threadId: state.snapshot.threadId,- turnId,- } satisfies ProviderTurnStartResult;- });-- const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (- threadId,- turnId,- ) =>- sessions.has(threadId)- ? Effect.sync(() => {- const existing = interruptCallsBySession.get(threadId) ?? [];- existing.push(turnId);- interruptCallsBySession.set(threadId, existing);- })- : missingSessionEffect(provider, threadId);-- const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (- threadId,- requestId,- decision,- ) =>- sessions.has(threadId)- ? Effect.sync(() => {- const existing = approvalResponsesBySession.get(threadId) ?? [];- existing.push({- threadId,- requestId,- decision,- });- approvalResponsesBySession.set(threadId, existing);- })- : missingSessionEffect(provider, threadId);-- const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (- threadId,- _requestId,- _answers,- ) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));-- const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>- Effect.sync(() => {- sessions.delete(threadId);- });-- const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>- Effect.sync(() => Array.from(sessions.values(), (state) => state.session));-- const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>- Effect.succeed(sessions.has(threadId));-- const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {- const state = sessions.get(threadId);- if (!state) {- return missingSessionEffect(provider, threadId);- }- return Effect.succeed(state.snapshot);- };-- const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (- threadId,- numTurns,- ) => {- const state = sessions.get(threadId);- if (!state) {- return missingSessionEffect(provider, threadId);- }- if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {- return Effect.fail(- new ProviderAdapterValidationError({- provider,- operation: "rollbackThread",- issue: "numTurns must be an integer between 0 and current turn count.",- }),+ return Effect.sync(() => {+ state.rollbackCalls.push(numTurns);+ state.snapshot = {+ threadId: state.snapshot.threadId,+ turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),+ };+ state.turnCount = state.snapshot.turns.length;+ return state.snapshot;+ });+ };++ const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>+ Effect.sync(() => {+ sessions.clear();+ });++ const adapter: ProviderAdapterShape<ProviderAdapterError> = {+ provider,+ capabilities: {+ sessionModelSwitch: "in-session",+ },+ startSession,+ sendTurn,+ interruptTurn,+ respondToRequest,+ respondToUserInput,+ stopSession,+ listSessions,+ hasSession,+ readThread,+ rollbackThread,+ stopAll,+ streamEvents: Stream.fromQueue(runtimeEvents),+ };++ const queueTurnResponse = (+ threadId: ThreadId,+ response: TestTurnResponse,+ ): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>+ Effect.sync(() => sessions.get(threadId)).pipe(+ Effect.flatMap((state) =>+ state+ ? Effect.sync(() => {+ state.queuedResponses.push(response);+ })+ : Effect.fail(sessionNotFound(provider, threadId)),+ ),);- }-- return Effect.sync(() => {- state.rollbackCalls.push(numTurns);- state.snapshot = {- threadId: state.snapshot.threadId,- turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),- };- state.turnCount = state.snapshot.turns.length;- return state.snapshot;- });- };-- const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>- Effect.sync(() => {- sessions.clear();- });-- const adapter: ProviderAdapterShape<ProviderAdapterError> = {- provider,- capabilities: {- sessionModelSwitch: "in-session",- },- startSession,- sendTurn,- interruptTurn,- respondToRequest,- respondToUserInput,- stopSession,- listSessions,- hasSession,- readThread,- rollbackThread,- stopAll,- streamEvents: Stream.fromQueue(runtimeEvents),- };-- const queueTurnResponse = (- threadId: ThreadId,- response: TestTurnResponse,- ): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>- Effect.sync(() => sessions.get(threadId)).pipe(- Effect.flatMap((state) =>- state- ? Effect.sync(() => {- state.queuedResponses.push(response);- })- : Effect.fail(sessionNotFound(provider, threadId)),- ),- );-- const queueTurnResponseForNextSession = (- response: TestTurnResponse,- ): Effect.Effect<void, never> =>- Effect.sync(() => {- queuedResponsesForNextSession.push(response);- });-- const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {- const state = sessions.get(threadId);- if (!state) {- return [];- }- return [...state.rollbackCalls];- };-- const getStartCount = (): number => sessionCount;-- const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {- const calls = interruptCallsBySession.get(threadId);- if (!calls) {- return [];- }- return [...calls];- };-- const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>- Array.from(sessions.values(), (state) => state.session.threadId);-- const getApprovalResponses = (- threadId: ThreadId,- ): ReadonlyArray<{- readonly threadId: ThreadId;- readonly requestId: ApprovalRequestId;- readonly decision: ProviderApprovalDecision;- }> => {- const responses = approvalResponsesBySession.get(threadId);- if (!responses) {- return [];- }- return [...responses];- };-- return {- adapter,- provider,- queueTurnResponse,- queueTurnResponseForNextSession,- getStartCount,- getRollbackCalls,- getInterruptCalls,- listActiveSessionIds,- getApprovalResponses,- } satisfies TestProviderAdapterHarness;-});++ const queueTurnResponseForNextSession = (+ response: TestTurnResponse,+ ): Effect.Effect<void, never> =>+ Effect.sync(() => {+ queuedResponsesForNextSession.push(response);+ });++ const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {+ const state = sessions.get(threadId);+ if (!state) {+ return [];+ }+ return [...state.rollbackCalls];+ };++ const getStartCount = (): number => sessionCount;++ const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {+ const calls = interruptCallsBySession.get(threadId);+ if (!calls) {+ return [];+ }+ return [...calls];+ };++ const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>+ Array.from(sessions.values(), (state) => state.session.threadId);++ const getApprovalResponses = (+ threadId: ThreadId,+ ): ReadonlyArray<{+ readonly threadId: ThreadId;+ readonly requestId: ApprovalRequestId;+ readonly decision: ProviderApprovalDecision;+ }> => {+ const responses = approvalResponsesBySession.get(threadId);+ if (!responses) {+ return [];+ }+ return [...responses];+ };++ return {+ adapter,+ provider,+ queueTurnResponse,+ queueTurnResponseForNextSession,+ getStartCount,+ getRollbackCalls,+ getInterruptCalls,+ listActiveSessionIds,+ getApprovalResponses,+ } satisfies TestProviderAdapterHarness;+ });diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.tsindex 3eaa72ea8..21bc515aa 100644--- a/apps/server/scripts/cli.ts+++ b/apps/server/scripts/cli.ts@@ -6,7 +6,10 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";import { Command, Flag } from "effect/unstable/cli";import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";-import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";+import {+ DEVELOPMENT_ICON_OVERRIDES,+ PUBLISH_ICON_OVERRIDES,+} from "../../../scripts/lib/brand-assets.ts";import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";import rootPackageJson from "../../../package.json" with { type: "json" };import serverPackageJson from "../package.json" with { type: "json" };@@ -237,9 +240,7 @@ const publishCmd = Command.make(Effect.gen(function* () {yield* restorePublishIconOverrides(resource.iconBackups).pipe(Effect.catch((error) =>- Effect.logError(- `[cli] Failed to restore publish icon overrides: ${String(error)}`,- ),+ Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),),);yield* fs.rename(backupPath, packageJsonPath);diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.tsindex 48be2df8a..3440e29fc 100644--- a/apps/server/src/attachmentStore.ts+++ b/apps/server/src/attachmentStore.ts@@ -12,8 +12,7 @@ import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts"const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";-const ATTACHMENT_ID_UUID_PATTERN =- "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";+const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";const ATTACHMENT_ID_PATTERN = new RegExp(`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,"i",diff --git a/apps/server/src/codexAppServerManager.test.ts b/apps/server/src/codexAppServerManager.test.tsindex 4e0073d75..cea8df0a0 100644--- a/apps/server/src/codexAppServerManager.test.ts+++ b/apps/server/src/codexAppServerManager.test.ts@@ -749,88 +749,82 @@ describe("respondToUserInput", () => {});describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {- it(- "keeps prior thread history when resuming with a changed runtime mode",- async () => {- const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));- writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");+ it("keeps prior thread history when resuming with a changed runtime mode", async () => {+ const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));+ writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");- const manager = new CodexAppServerManager();+ const manager = new CodexAppServerManager();- try {- const firstSession = await manager.startSession({- threadId: asThreadId("thread-live"),- provider: "codex",- cwd: workspaceDir,- runtimeMode: "full-access",- providerOptions: {- codex: {- ...(process.env.CODEX_BINARY_PATH- ? { binaryPath: process.env.CODEX_BINARY_PATH }- : {}),- ...(process.env.CODEX_HOME_PATH- ? { homePath: process.env.CODEX_HOME_PATH }- : {}),- },+ try {+ const firstSession = await manager.startSession({+ threadId: asThreadId("thread-live"),+ provider: "codex",+ cwd: workspaceDir,+ runtimeMode: "full-access",+ providerOptions: {+ codex: {+ ...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),+ ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),},- });+ },+ });- const firstTurn = await manager.sendTurn({- threadId: firstSession.threadId,- input: `Reply with exactly the word ALPHA ${randomUUID()}`,- });+ const firstTurn = await manager.sendTurn({+ threadId: firstSession.threadId,+ input: `Reply with exactly the word ALPHA ${randomUUID()}`,+ });- expect(firstTurn.threadId).toBe(firstSession.threadId);+ expect(firstTurn.threadId).toBe(firstSession.threadId);- await vi.waitFor(async () => {+ await vi.waitFor(+ async () => {const snapshot = await manager.readThread(firstSession.threadId);expect(snapshot.turns.length).toBeGreaterThan(0);- }, { timeout: 120_000, interval: 1_000 });+ },+ { timeout: 120_000, interval: 1_000 },+ );- const firstSnapshot = await manager.readThread(firstSession.threadId);- const originalThreadId = firstSnapshot.threadId;- const originalTurnCount = firstSnapshot.turns.length;+ const firstSnapshot = await manager.readThread(firstSession.threadId);+ const originalThreadId = firstSnapshot.threadId;+ const originalTurnCount = firstSnapshot.turns.length;- manager.stopSession(firstSession.threadId);+ manager.stopSession(firstSession.threadId);- const resumedSession = await manager.startSession({- threadId: firstSession.threadId,- provider: "codex",- cwd: workspaceDir,- runtimeMode: "approval-required",- resumeCursor: firstSession.resumeCursor,- providerOptions: {- codex: {- ...(process.env.CODEX_BINARY_PATH- ? { binaryPath: process.env.CODEX_BINARY_PATH }- : {}),- ...(process.env.CODEX_HOME_PATH- ? { homePath: process.env.CODEX_HOME_PATH }- : {}),- },+ const resumedSession = await manager.startSession({+ threadId: firstSession.threadId,+ provider: "codex",+ cwd: workspaceDir,+ runtimeMode: "approval-required",+ resumeCursor: firstSession.resumeCursor,+ providerOptions: {+ codex: {+ ...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),+ ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),},- });+ },+ });- expect(resumedSession.threadId).toBe(originalThreadId);+ expect(resumedSession.threadId).toBe(originalThreadId);- const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);- expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);- expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);+ const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);+ expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);+ expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);- await manager.sendTurn({- threadId: resumedSession.threadId,- input: `Reply with exactly the word BETA ${randomUUID()}`,- });+ await manager.sendTurn({+ threadId: resumedSession.threadId,+ input: `Reply with exactly the word BETA ${randomUUID()}`,+ });- await vi.waitFor(async () => {+ await vi.waitFor(+ async () => {const snapshot = await manager.readThread(resumedSession.threadId);expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);- }, { timeout: 120_000, interval: 1_000 });- } finally {- manager.stopAll();- rmSync(workspaceDir, { recursive: true, force: true });- }- },- 180_000,- );+ },+ { timeout: 120_000, interval: 1_000 },+ );+ } finally {+ manager.stopAll();+ rmSync(workspaceDir, { recursive: true, force: true });+ }+ }, 180_000);});diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.tsindex 9642f0b06..1cf2d0e09 100644--- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts+++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts@@ -363,8 +363,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const path = yield* Path.Path;- const attachmentId =- `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;+ const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });yield* fs.writeFile(imagePath, Buffer.from("hello"));@@ -392,9 +391,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {}),),),- Effect.ensuring(- fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),- ),+ Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),);expect(generated.branch).toBe("fix/ui-regression");diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.tsindex e2af44b6d..05b2ade03 100644--- a/apps/server/src/git/Layers/GitCore.test.ts+++ b/apps/server/src/git/Layers/GitCore.test.ts@@ -153,9 +153,7 @@ function createGitWorktree(input: Parameters<GitCoreShape["createWorktree"]>[0])});}-function fetchGitPullRequestBranch(- input: Parameters<GitCoreShape["fetchPullRequestBranch"]>[0],-) {+function fetchGitPullRequestBranch(input: Parameters<GitCoreShape["fetchPullRequestBranch"]>[0]) {return Effect.gen(function* () {const core = yield* GitCore;return yield* core.fetchPullRequestBranch(input);@@ -441,7 +439,9 @@ it.layer(TestLayer)("git integration", (it) => {true,);expect(- result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),+ result.branches.some(+ (branch) => branch.name === "feature/local-only" && !branch.isRemote,+ ),).toBe(true);expect(result.branches.some(@@ -704,29 +704,27 @@ it.layer(TestLayer)("git integration", (it) => {}),);- it.effect(- "does not silently checkout a local branch when a remote ref no longer exists",- () =>- Effect.gen(function* () {- const remote = yield* makeTmpDir();- const source = yield* makeTmpDir();- yield* git(remote, ["init", "--bare"]);+ it.effect("does not silently checkout a local branch when a remote ref no longer exists", () =>+ Effect.gen(function* () {+ const remote = yield* makeTmpDir();+ const source = yield* makeTmpDir();+ yield* git(remote, ["init", "--bare"]);- yield* initRepoWithCommit(source);- const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(- (branch) => branch.current,- )!.name;- yield* git(source, ["remote", "add", "origin", remote]);- yield* git(source, ["push", "-u", "origin", defaultBranch]);+ yield* initRepoWithCommit(source);+ const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(+ (branch) => branch.current,+ )!.name;+ yield* git(source, ["remote", "add", "origin", remote]);+ yield* git(source, ["push", "-u", "origin", defaultBranch]);- yield* createGitBranch({ cwd: source, branch: "feature" });+ yield* createGitBranch({ cwd: source, branch: "feature" });- const checkoutResult = yield* Effect.result(- checkoutGitBranch({ cwd: source, branch: "origin/feature" }),- );- expect(checkoutResult._tag).toBe("Failure");- expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);- }),+ const checkoutResult = yield* Effect.result(+ checkoutGitBranch({ cwd: source, branch: "origin/feature" }),+ );+ expect(checkoutResult._tag).toBe("Failure");+ expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);+ }),);it.effect("checks out a remote tracking branch when remote name contains slashes", () =>@@ -955,13 +953,7 @@ it.layer(TestLayer)("git integration", (it) => {});expect(renamed.branch).toBe("feature/new-name");- expect(renameArgs).toEqual([- "branch",- "-m",- "--",- "feature/old-name",- "feature/new-name",- ]);+ expect(renameArgs).toEqual(["branch", "-m", "--", "feature/old-name", "feature/new-name"]);}),);});@@ -1325,23 +1317,25 @@ it.layer(TestLayer)("git integration", (it) => {}),);- it.effect("reuses an existing remote when the target URL only differs by a trailing slash after .git", () =>- Effect.gen(function* () {- const tmp = yield* makeTmpDir();- yield* initRepoWithCommit(tmp);- const core = yield* GitCore;+ it.effect(+ "reuses an existing remote when the target URL only differs by a trailing slash after .git",+ () =>+ Effect.gen(function* () {+ const tmp = yield* makeTmpDir();+ yield* initRepoWithCommit(tmp);+ const core = yield* GitCore;- yield* git(tmp, ["remote", "add", "origin", "[email protected]:pingdotgg/t3code.git"]);+ yield* git(tmp, ["remote", "add", "origin", "[email protected]:pingdotgg/t3code.git"]);- const remoteName = yield* core.ensureRemote({- cwd: tmp,- preferredName: "origin",- url: "[email protected]:pingdotgg/t3code.git/",- });+ const remoteName = yield* core.ensureRemote({+ cwd: tmp,+ preferredName: "origin",+ url: "[email protected]:pingdotgg/t3code.git/",+ });- expect(remoteName).toBe("origin");- expect((yield* git(tmp, ["remote"])).split("\n").filter(Boolean)).toEqual(["origin"]);- }),+ expect(remoteName).toBe("origin");+ expect((yield* git(tmp, ["remote"])).split("\n").filter(Boolean)).toEqual(["origin"]);+ }),);it.effect("reports status details and dirty state", () =>diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.tsindex 86eeb3fb4..05f458af6 100644--- a/apps/server/src/git/Layers/GitCore.ts+++ b/apps/server/src/git/Layers/GitCore.ts@@ -101,12 +101,19 @@ function parseRemoteNames(stdout: string): ReadonlyArray<string> {}function sanitizeRemoteName(value: string): string {- const sanitized = value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");+ const sanitized = value+ .trim()+ .replace(/[^A-Za-z0-9._-]+/g, "-")+ .replace(/^-+|-+$/g, "");return sanitized.length > 0 ? sanitized : "fork";}function normalizeRemoteUrl(value: string): string {- return value.trim().replace(/\/+$/g, "").replace(/\.git$/i, "").toLowerCase();+ return value+ .trim()+ .replace(/\/+$/g, "")+ .replace(/\.git$/i, "")+ .toLowerCase();}function parseRemoteFetchUrls(stdout: string): Map<string, string> {@@ -470,10 +477,11 @@ const makeGitCore = Effect.gen(function* () {Effect.gen(function* () {const preferredName = sanitizeRemoteName(input.preferredName);const normalizedTargetUrl = normalizeRemoteUrl(input.url);- const remoteFetchUrls = yield* runGitStdout("GitCore.ensureRemote.listRemoteUrls", input.cwd, [- "remote",- "-v",- ]).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));+ const remoteFetchUrls = yield* runGitStdout(+ "GitCore.ensureRemote.listRemoteUrls",+ input.cwd,+ ["remote", "-v"],+ ).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) {@@ -488,7 +496,12 @@ const makeGitCore = Effect.gen(function* () {suffix += 1;}- yield* runGit("GitCore.ensureRemote.add", input.cwd, ["remote", "add", remoteName, input.url]);+ yield* runGit("GitCore.ensureRemote.add", input.cwd, [+ "remote",+ "add",+ remoteName,+ input.url,+ ]);return remoteName;});@@ -1099,14 +1112,9 @@ const makeGitCore = Effect.gen(function* () {? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch]: ["worktree", "add", worktreePath, input.branch];- yield* executeGit(- "GitCore.createWorktree",- input.cwd,- args,- {- fallbackErrorMessage: "git worktree add failed",- },- );+ yield* executeGit("GitCore.createWorktree", input.cwd, args, {+ fallbackErrorMessage: "git worktree add failed",+ });return {worktree: {diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.tsindex 120ed83be..856eb076b 100644--- a/apps/server/src/git/Layers/GitManager.test.ts+++ b/apps/server/src/git/Layers/GitManager.test.ts@@ -120,7 +120,11 @@ function runGit(function initRepo(cwd: string,-): Effect.Effect<void, PlatformError.PlatformError | GitCommandError, FileSystem.FileSystem | Scope.Scope | GitService> {+): Effect.Effect<+ void,+ PlatformError.PlatformError | GitCommandError,+ FileSystem.FileSystem | Scope.Scope | GitService+> {return Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;yield* runGit(cwd, ["init", "--initial-branch=main"]);@@ -150,9 +154,7 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TEffect.succeed({subject: "Implement stacked git actions",body: "",- ...(input.includeBranch- ? { branch: "feature/implement-stacked-git-actions" }- : {}),+ ...(input.includeBranch ? { branch: "feature/implement-stacked-git-actions" } : {}),}),generatePrContent: () =>Effect.succeed({@@ -416,9 +418,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {"--json","number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",],- }).pipe(- Effect.map((result) => JSON.parse(result.stdout) as GitHubPullRequestSummary),- ),+ }).pipe(Effect.map((result) => JSON.parse(result.stdout) as GitHubPullRequestSummary)),getRepositoryCloneUrls: (input) =>execute({cwd: input.cwd,@@ -427,12 +427,7 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {checkoutPullRequest: (input) =>execute({cwd: input.cwd,- args: [- "pr",- "checkout",- input.reference,- ...(input.force ? ["--force"] : []),- ],+ args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],}).pipe(Effect.asVoid),},ghCalls,@@ -722,9 +717,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {return {subject: "Implement stacked git actions",body: "",- ...(input.includeBranch- ? { branch: "feature/implement-stacked-git-actions" }- : {}),+ ...(input.includeBranch ? { branch: "feature/implement-stacked-git-actions" } : {}),};}),},@@ -1199,9 +1192,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {expect(result.branch).toBe("feature/pr-worktree");expect(result.worktreePath).not.toBeNull();expect(fs.existsSync(result.worktreePath as string)).toBe(true);- const worktreeBranch = (- yield* runGit(result.worktreePath as string, ["branch", "--show-current"])- ).stdout.trim();+ const worktreeBranch = (yield* runGit(result.worktreePath as string, [+ "branch",+ "--show-current",+ ])).stdout.trim();expect(worktreeBranch).toBe("feature/pr-worktree");}),);@@ -1251,15 +1245,19 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {});expect(result.worktreePath).not.toBeNull();- const upstreamRef = (- yield* runGit(result.worktreePath as string, ["rev-parse", "--abbrev-ref", "@{upstream}"])- ).stdout.trim();+ const upstreamRef = (yield* runGit(result.worktreePath as string, [+ "rev-parse",+ "--abbrev-ref",+ "@{upstream}",+ ])).stdout.trim();expect(upstreamRef).toBe("fork-seed/feature/pr-fork");expect(upstreamRef.startsWith("origin/")).toBe(false);expect(- (yield* runGit(result.worktreePath as string, ["config", "--get", "remote.fork-seed.url"]))- .stdout- .trim(),+ (yield* runGit(result.worktreePath as string, [+ "config",+ "--get",+ "remote.fork-seed.url",+ ])).stdout.trim(),).toBe(forkDir);}),);@@ -1330,7 +1328,12 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {fs.writeFileSync(path.join(repoDir, "derived-fork.txt"), "derived fork\n");yield* runGit(repoDir, ["add", "derived-fork.txt"]);yield* runGit(repoDir, ["commit", "-m", "Derived fork PR branch"]);- yield* runGit(repoDir, ["push", "-u", "binbandit-seed", "fix/git-action-default-without-origin"]);+ yield* runGit(repoDir, [+ "push",+ "-u",+ "binbandit-seed",+ "fix/git-action-default-without-origin",+ ]);yield* runGit(repoDir, ["checkout", "main"]);yield* runGit(repoDir, ["branch", "-D", "fix/git-action-default-without-origin"]);@@ -1407,115 +1410,124 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {}),);- it.effect("does not block fork PR worktree prep when the fork head branch collides with root main", () =>- Effect.gen(function* () {- const repoDir = yield* makeTempDir("t3code-git-manager-");- yield* initRepo(repoDir);- const originDir = yield* createBareRemote();- const forkDir = yield* createBareRemote();- yield* runGit(repoDir, ["remote", "add", "origin", originDir]);- yield* runGit(repoDir, ["push", "-u", "origin", "main"]);- yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);- yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);- fs.writeFileSync(path.join(repoDir, "fork-main.txt"), "fork main\n");- yield* runGit(repoDir, ["add", "fork-main.txt"]);- yield* runGit(repoDir, ["commit", "-m", "Fork main branch"]);- yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);- yield* runGit(repoDir, ["checkout", "main"]);- const mainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();-- const { manager } = yield* makeManager({- ghScenario: {- pullRequest: {- number: 91,- title: "Fork main PR",- url: "https://github.com/pingdotgg/codething-mvp/pull/91",- baseRefName: "main",- headRefName: "main",- state: "open",- isCrossRepository: true,- headRepositoryNameWithOwner: "octocat/codething-mvp",- headRepositoryOwnerLogin: "octocat",- },- repositoryCloneUrls: {- "octocat/codething-mvp": {- url: forkDir,- sshUrl: forkDir,+ it.effect(+ "does not block fork PR worktree prep when the fork head branch collides with root main",+ () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ const originDir = yield* createBareRemote();+ const forkDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", originDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "main"]);+ yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);+ yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);+ fs.writeFileSync(path.join(repoDir, "fork-main.txt"), "fork main\n");+ yield* runGit(repoDir, ["add", "fork-main.txt"]);+ yield* runGit(repoDir, ["commit", "-m", "Fork main branch"]);+ yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);+ yield* runGit(repoDir, ["checkout", "main"]);+ const mainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();++ const { manager } = yield* makeManager({+ ghScenario: {+ pullRequest: {+ number: 91,+ title: "Fork main PR",+ url: "https://github.com/pingdotgg/codething-mvp/pull/91",+ baseRefName: "main",+ headRefName: "main",+ state: "open",+ isCrossRepository: true,+ headRepositoryNameWithOwner: "octocat/codething-mvp",+ headRepositoryOwnerLogin: "octocat",+ },+ repositoryCloneUrls: {+ "octocat/codething-mvp": {+ url: forkDir,+ sshUrl: forkDir,+ },},},- },- });+ });- const result = yield* preparePullRequestThread(manager, {- cwd: repoDir,- reference: "91",- mode: "worktree",- });+ const result = yield* preparePullRequestThread(manager, {+ cwd: repoDir,+ reference: "91",+ mode: "worktree",+ });- expect(result.branch).toBe("t3code/pr-91/main");- expect(result.worktreePath).not.toBeNull();- expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe("main");- expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(mainBefore);- expect(- (yield* runGit(result.worktreePath as string, ["branch", "--show-current"])).stdout.trim(),- ).toBe("t3code/pr-91/main");- }),+ expect(result.branch).toBe("t3code/pr-91/main");+ expect(result.worktreePath).not.toBeNull();+ expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe("main");+ expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(mainBefore);+ expect(+ (yield* runGit(result.worktreePath as string, [+ "branch",+ "--show-current",+ ])).stdout.trim(),+ ).toBe("t3code/pr-91/main");+ }),);- it.effect("does not overwrite an existing local main branch when preparing a fork PR worktree", () =>- Effect.gen(function* () {- const repoDir = yield* makeTempDir("t3code-git-manager-");- yield* initRepo(repoDir);- const originDir = yield* createBareRemote();- const forkDir = yield* createBareRemote();- yield* runGit(repoDir, ["remote", "add", "origin", originDir]);- yield* runGit(repoDir, ["push", "-u", "origin", "main"]);- yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);- yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);- fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");- yield* runGit(repoDir, ["add", "fork-main-second.txt"]);- yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);- yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);- yield* runGit(repoDir, ["checkout", "main"]);- const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();- yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]);-- const { manager } = yield* makeManager({- ghScenario: {- pullRequest: {- number: 92,- title: "Fork main overwrite PR",- url: "https://github.com/pingdotgg/codething-mvp/pull/92",- baseRefName: "main",- headRefName: "main",- state: "open",- isCrossRepository: true,- headRepositoryNameWithOwner: "octocat/codething-mvp",- headRepositoryOwnerLogin: "octocat",- },- repositoryCloneUrls: {- "octocat/codething-mvp": {- url: forkDir,- sshUrl: forkDir,+ it.effect(+ "does not overwrite an existing local main branch when preparing a fork PR worktree",+ () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-git-manager-");+ yield* initRepo(repoDir);+ const originDir = yield* createBareRemote();+ const forkDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", originDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "main"]);+ yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);+ yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);+ fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");+ yield* runGit(repoDir, ["add", "fork-main-second.txt"]);+ yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);+ yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);+ yield* runGit(repoDir, ["checkout", "main"]);+ const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();+ yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]);++ const { manager } = yield* makeManager({+ ghScenario: {+ pullRequest: {+ number: 92,+ title: "Fork main overwrite PR",+ url: "https://github.com/pingdotgg/codething-mvp/pull/92",+ baseRefName: "main",+ headRefName: "main",+ state: "open",+ isCrossRepository: true,+ headRepositoryNameWithOwner: "octocat/codething-mvp",+ headRepositoryOwnerLogin: "octocat",+ },+ repositoryCloneUrls: {+ "octocat/codething-mvp": {+ url: forkDir,+ sshUrl: forkDir,+ },},},- },- });+ });- const result = yield* preparePullRequestThread(manager, {- cwd: repoDir,- reference: "92",- mode: "worktree",- });+ const result = yield* preparePullRequestThread(manager, {+ cwd: repoDir,+ reference: "92",+ mode: "worktree",+ });- expect(result.branch).toBe("t3code/pr-92/main");- expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);- expect(- (yield* runGit(result.worktreePath as string, ["rev-parse", "--abbrev-ref", "@{upstream}"]))- .stdout- .trim(),- ).toBe("fork-seed/main");- }),+ expect(result.branch).toBe("t3code/pr-92/main");+ expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);+ expect(+ (yield* runGit(result.worktreePath as string, [+ "rev-parse",+ "--abbrev-ref",+ "@{upstream}",+ ])).stdout.trim(),+ ).toBe("fork-seed/main");+ }),);it.effect("reuses an existing PR worktree and restores fork upstream tracking", () =>diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.tsindex 7ac63ab54..1c711e3b4 100644--- a/apps/server/src/git/Layers/GitManager.ts+++ b/apps/server/src/git/Layers/GitManager.ts@@ -655,28 +655,27 @@ export const makeGitManager = Effect.gen(function* () {};});- const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fnUntraced(function* (- input,- ) {- const pullRequest = yield* gitHubCli- .getPullRequest({- cwd: input.cwd,- reference: normalizePullRequestReference(input.reference),- })- .pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));+ const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fnUntraced(+ function* (input) {+ const pullRequest = yield* gitHubCli+ .getPullRequest({+ cwd: input.cwd,+ reference: normalizePullRequestReference(input.reference),+ })+ .pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));- return { pullRequest };- });+ return { pullRequest };+ },+ );const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fnUntraced(function* (input) {const normalizedReference = normalizePullRequestReference(input.reference);const rootWorktreePath = canonicalizeExistingPath(input.cwd);- const pullRequestSummary = yield* gitHubCli- .getPullRequest({- cwd: input.cwd,- reference: normalizedReference,- });+ const pullRequestSummary = yield* gitHubCli.getPullRequest({+ cwd: input.cwd,+ reference: normalizedReference,+ });const pullRequest = toResolvedPullRequest(pullRequestSummary);if (input.mode === "local") {@@ -715,12 +714,11 @@ export const makeGitManager = Effect.gen(function* () {});const pullRequestWithRemoteInfo = {- ...pullRequest,- ...toPullRequestHeadRemoteInfo(pullRequestSummary),- } as const;- const localPullRequestBranch = resolvePullRequestWorktreeLocalBranchName(- pullRequestWithRemoteInfo,- );+ ...pullRequest,+ ...toPullRequestHeadRemoteInfo(pullRequestSummary),+ } as const;+ const localPullRequestBranch =+ resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);const findLocalHeadBranch = (cwd: string) =>gitCore.listBranches({ cwd }).pipe(diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.tsindex dce859ccb..502ac349d 100644--- a/apps/server/src/git/Services/GitCore.ts+++ b/apps/server/src/git/Services/GitCore.ts@@ -165,9 +165,7 @@ export interface GitCoreShape {/*** Ensure a named remote exists for the provided URL, returning the reused or created remote name.*/- readonly ensureRemote: (- input: GitEnsureRemoteInput,- ) => Effect.Effect<string, GitCommandError>;+ readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;/*** Fetch a remote branch into a local branch without checkout.diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.tsindex 4a10d5816..6954cafc5 100644--- a/apps/server/src/keybindings.test.ts+++ b/apps/server/src/keybindings.test.ts@@ -211,7 +211,9 @@ it.layer(NodeServices.layer)("keybindings", (it) => {});assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));- assert.isFalse(configState.keybindings.some((entry) => String(entry.command) === "invalid.command"));+ assert.isFalse(+ configState.keybindings.some((entry) => String(entry.command) === "invalid.command"),+ );assert.deepEqual(configState.issues, [{kind: "keybindings.invalid-entry",diff --git a/apps/server/src/open.ts b/apps/server/src/open.tsindex 5c742fba9..e7238c04b 100644--- a/apps/server/src/open.ts+++ b/apps/server/src/open.ts@@ -40,7 +40,9 @@ interface CommandAvailabilityOptions {const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {- return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);+ return (+ (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)+ );}function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {@@ -239,9 +241,7 @@ export const launchDetached = (launch: EditorLaunch) =>});} catch (error) {return resume(- Effect.fail(- new OpenError({ message: "failed to spawn detached process", cause: error }),- ),+ Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),);}diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.tsindex d675c85ff..eecfc069d 100644--- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts@@ -69,7 +69,7 @@ function createProviderServiceHarness(Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;const listSessions = () =>hasSession- ? Effect.succeed([+ ? Effect.succeed([{provider: providerName,status: "ready",@@ -350,7 +350,7 @@ describe("CheckpointReactor", () => {type: "turn.started",eventId: EventId.makeUnsafe("evt-turn-started-1"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-1"),@@ -365,7 +365,7 @@ describe("CheckpointReactor", () => {type: "turn.completed",eventId: EventId.makeUnsafe("evt-turn-completed-1"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-1"),@@ -426,7 +426,7 @@ describe("CheckpointReactor", () => {type: "turn.started",eventId: EventId.makeUnsafe("evt-turn-started-main"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-main"),@@ -442,7 +442,7 @@ describe("CheckpointReactor", () => {type: "turn.completed",eventId: EventId.makeUnsafe("evt-turn-completed-aux"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-aux"),@@ -460,7 +460,7 @@ describe("CheckpointReactor", () => {type: "turn.completed",eventId: EventId.makeUnsafe("evt-turn-completed-main"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-main"),@@ -500,7 +500,7 @@ describe("CheckpointReactor", () => {type: "turn.completed",eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-missing-baseline"),@@ -589,7 +589,7 @@ describe("CheckpointReactor", () => {type: "turn.completed",eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-missing-cwd"),@@ -635,7 +635,7 @@ describe("CheckpointReactor", () => {type: "checkpoint.captured",eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-3"),@@ -685,7 +685,7 @@ describe("CheckpointReactor", () => {type: "turn.completed",eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-runtime-failure"),@@ -696,7 +696,7 @@ describe("CheckpointReactor", () => {type: "turn.started",eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),provider: "codex",-+createdAt: new Date().toISOString(),threadId: ThreadId.makeUnsafe("thread-1"),turnId: asTurnId("turn-after-runtime-failure"),diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.tsindex 52243248f..da0e08b93 100644--- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts@@ -115,9 +115,7 @@ const make = Effect.gen(function* () {const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (threadId: ThreadId,- ): Effect.fn.Return<- Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>- > {+ ): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {const readModel = yield* orchestrationEngine.getReadModel();const thread = readModel.threads.find((entry) => entry.id === threadId);@@ -133,9 +131,7 @@ const make = Effect.gen(function* () {};if (thread) {- const projectedSession = sessions.find(- (session) => session.threadId === thread.id,- );+ const projectedSession = sessions.find((session) => session.threadId === thread.id);const fromProjected = findSessionWithCwd(projectedSession);if (Option.isSome(fromProjected)) {return fromProjected;@@ -306,9 +302,7 @@ const make = Effect.gen(function* () {}const readModel = yield* orchestrationEngine.getReadModel();- const thread = readModel.threads.find(- (entry) => entry.id === event.threadId,- );+ const thread = readModel.threads.find((entry) => entry.id === event.threadId);if (!thread) {return;}diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex 6e4e824f3..d15b2efa2 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -54,9 +54,7 @@ const runWithProjectionPipelineLayer = <A, E>((runtime) => Effect.promise(() => runtime.dispose()),);-const projectionLayer = it.layer(- makeProjectionPipelineTestLayer(process.cwd()),-);+const projectionLayer = it.layer(makeProjectionPipelineTestLayer(process.cwd()));projectionLayer("OrchestrationProjectionPipeline", (it) => {it.effect("bootstraps all projection states and writes projection rows", () =>@@ -450,153 +448,149 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {}),);- it.effect(- "overwrites stored attachment references when a message updates attachments",- () =>- Effect.sync(() =>- fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-overwrite-")),- ).pipe(- Effect.flatMap((stateDir) =>- Effect.gen(function* () {- const projectionPipeline = yield* OrchestrationProjectionPipeline;- const eventStore = yield* OrchestrationEventStore;- const sql = yield* SqlClient.SqlClient;- const now = new Date().toISOString();- const later = new Date(Date.now() + 1_000).toISOString();-- yield* eventStore.append({- type: "project.created",- eventId: EventId.makeUnsafe("evt-overwrite-1"),- aggregateKind: "project",- aggregateId: ProjectId.makeUnsafe("project-overwrite"),- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-overwrite-1"),- causationEventId: null,- correlationId: CommandId.makeUnsafe("cmd-overwrite-1"),- metadata: {},- payload: {- projectId: ProjectId.makeUnsafe("project-overwrite"),- title: "Project Overwrite",- workspaceRoot: "/tmp/project-overwrite",- defaultModel: null,- scripts: [],- createdAt: now,- updatedAt: now,- },- });+ it.effect("overwrites stored attachment references when a message updates attachments", () =>+ Effect.sync(() =>+ fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-overwrite-")),+ ).pipe(+ Effect.flatMap((stateDir) =>+ Effect.gen(function* () {+ const projectionPipeline = yield* OrchestrationProjectionPipeline;+ const eventStore = yield* OrchestrationEventStore;+ const sql = yield* SqlClient.SqlClient;+ const now = new Date().toISOString();+ const later = new Date(Date.now() + 1_000).toISOString();- yield* eventStore.append({- type: "thread.created",- eventId: EventId.makeUnsafe("evt-overwrite-2"),- aggregateKind: "thread",- aggregateId: ThreadId.makeUnsafe("thread-overwrite"),- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-overwrite-2"),- causationEventId: null,- correlationId: CommandId.makeUnsafe("cmd-overwrite-2"),- metadata: {},- payload: {- threadId: ThreadId.makeUnsafe("thread-overwrite"),- projectId: ProjectId.makeUnsafe("project-overwrite"),- title: "Thread Overwrite",- model: "gpt-5-codex",- runtimeMode: "full-access",- branch: null,- worktreePath: null,- createdAt: now,- updatedAt: now,- },- });+ yield* eventStore.append({+ type: "project.created",+ eventId: EventId.makeUnsafe("evt-overwrite-1"),+ aggregateKind: "project",+ aggregateId: ProjectId.makeUnsafe("project-overwrite"),+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-overwrite-1"),+ causationEventId: null,+ correlationId: CommandId.makeUnsafe("cmd-overwrite-1"),+ metadata: {},+ payload: {+ projectId: ProjectId.makeUnsafe("project-overwrite"),+ title: "Project Overwrite",+ workspaceRoot: "/tmp/project-overwrite",+ defaultModel: null,+ scripts: [],+ createdAt: now,+ updatedAt: now,+ },+ });- yield* eventStore.append({- type: "thread.message-sent",- eventId: EventId.makeUnsafe("evt-overwrite-3"),- aggregateKind: "thread",- aggregateId: ThreadId.makeUnsafe("thread-overwrite"),- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-overwrite-3"),- causationEventId: null,- correlationId: CommandId.makeUnsafe("cmd-overwrite-3"),- metadata: {},- payload: {- threadId: ThreadId.makeUnsafe("thread-overwrite"),- messageId: MessageId.makeUnsafe("message-overwrite"),- role: "user",- text: "first image",- attachments: [- {- type: "image",- id: "thread-overwrite-att-1",- name: "file.png",- mimeType: "image/png",- sizeBytes: 5,- },- ],- turnId: null,- streaming: false,- createdAt: now,- updatedAt: now,- },- });+ yield* eventStore.append({+ type: "thread.created",+ eventId: EventId.makeUnsafe("evt-overwrite-2"),+ aggregateKind: "thread",+ aggregateId: ThreadId.makeUnsafe("thread-overwrite"),+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-overwrite-2"),+ causationEventId: null,+ correlationId: CommandId.makeUnsafe("cmd-overwrite-2"),+ metadata: {},+ payload: {+ threadId: ThreadId.makeUnsafe("thread-overwrite"),+ projectId: ProjectId.makeUnsafe("project-overwrite"),+ title: "Thread Overwrite",+ model: "gpt-5-codex",+ runtimeMode: "full-access",+ branch: null,+ worktreePath: null,+ createdAt: now,+ updatedAt: now,+ },+ });- yield* eventStore.append({- type: "thread.message-sent",- eventId: EventId.makeUnsafe("evt-overwrite-4"),- aggregateKind: "thread",- aggregateId: ThreadId.makeUnsafe("thread-overwrite"),- occurredAt: later,- commandId: CommandId.makeUnsafe("cmd-overwrite-4"),- causationEventId: null,- correlationId: CommandId.makeUnsafe("cmd-overwrite-4"),- metadata: {},- payload: {- threadId: ThreadId.makeUnsafe("thread-overwrite"),- messageId: MessageId.makeUnsafe("message-overwrite"),- role: "user",- text: "",- attachments: [- {- type: "image",- id: "thread-overwrite-att-2",- name: "file.png",- mimeType: "image/png",- sizeBytes: 5,- },- ],- turnId: null,- streaming: false,- createdAt: now,- updatedAt: later,- },- });+ yield* eventStore.append({+ type: "thread.message-sent",+ eventId: EventId.makeUnsafe("evt-overwrite-3"),+ aggregateKind: "thread",+ aggregateId: ThreadId.makeUnsafe("thread-overwrite"),+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-overwrite-3"),+ causationEventId: null,+ correlationId: CommandId.makeUnsafe("cmd-overwrite-3"),+ metadata: {},+ payload: {+ threadId: ThreadId.makeUnsafe("thread-overwrite"),+ messageId: MessageId.makeUnsafe("message-overwrite"),+ role: "user",+ text: "first image",+ attachments: [+ {+ type: "image",+ id: "thread-overwrite-att-1",+ name: "file.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ],+ turnId: null,+ streaming: false,+ createdAt: now,+ updatedAt: now,+ },+ });- yield* projectionPipeline.bootstrap;+ yield* eventStore.append({+ type: "thread.message-sent",+ eventId: EventId.makeUnsafe("evt-overwrite-4"),+ aggregateKind: "thread",+ aggregateId: ThreadId.makeUnsafe("thread-overwrite"),+ occurredAt: later,+ commandId: CommandId.makeUnsafe("cmd-overwrite-4"),+ causationEventId: null,+ correlationId: CommandId.makeUnsafe("cmd-overwrite-4"),+ metadata: {},+ payload: {+ threadId: ThreadId.makeUnsafe("thread-overwrite"),+ messageId: MessageId.makeUnsafe("message-overwrite"),+ role: "user",+ text: "",+ attachments: [+ {+ type: "image",+ id: "thread-overwrite-att-2",+ name: "file.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ],+ turnId: null,+ streaming: false,+ createdAt: now,+ updatedAt: later,+ },+ });++ yield* projectionPipeline.bootstrap;- const rows = yield* sql<{- readonly attachmentsJson: string | null;- }>`+ const rows = yield* sql<{+ readonly attachmentsJson: string | null;+ }>`SELECT attachments_json AS "attachmentsJson"FROM projection_thread_messagesWHERE message_id = 'message-overwrite'`;- assert.equal(rows.length, 1);- assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [- {- type: "image",- id: "thread-overwrite-att-2",- name: "file.png",- mimeType: "image/png",- sizeBytes: 5,- },- ]);- }).pipe(- (effect) => runWithProjectionPipelineLayer(stateDir, effect),- Effect.ensuring(- Effect.sync(() => fs.rmSync(stateDir, { recursive: true, force: true })),- ),- ),+ assert.equal(rows.length, 1);+ assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [+ {+ type: "image",+ id: "thread-overwrite-att-2",+ name: "file.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ]);+ }).pipe(+ (effect) => runWithProjectionPipelineLayer(stateDir, effect),+ Effect.ensuring(Effect.sync(() => fs.rmSync(stateDir, { recursive: true, force: true }))),),),+ ),);it.effect("does not persist attachment files when projector transaction rolls back", () =>@@ -711,11 +705,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {`;assert.equal(rows[0]?.count ?? 0, 0);- const attachmentPath = path.join(- stateDir,- "attachments",- "thread-rollback-att-1.png",- );+ const attachmentPath = path.join(stateDir, "attachments", "thread-rollback-att-1.png");assert.equal(fs.existsSync(attachmentPath), false);yield* sql`DROP TRIGGER IF EXISTS fail_thread_messages_projection_state_update`;}).pipe(@@ -747,189 +737,189 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));yield* appendAndProject({- type: "project.created",- eventId: EventId.makeUnsafe("evt-revert-files-1"),- aggregateKind: "project",- aggregateId: ProjectId.makeUnsafe("project-revert-files"),- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-revert-files-1"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"),- metadata: {},- payload: {- projectId: ProjectId.makeUnsafe("project-revert-files"),- title: "Project Revert Files",- workspaceRoot: "/tmp/project-revert-files",- defaultModel: null,- scripts: [],- createdAt: now,- updatedAt: now,- },- });+ type: "project.created",+ eventId: EventId.makeUnsafe("evt-revert-files-1"),+ aggregateKind: "project",+ aggregateId: ProjectId.makeUnsafe("project-revert-files"),+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-revert-files-1"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-revert-files-1"),+ metadata: {},+ payload: {+ projectId: ProjectId.makeUnsafe("project-revert-files"),+ title: "Project Revert Files",+ workspaceRoot: "/tmp/project-revert-files",+ defaultModel: null,+ scripts: [],+ createdAt: now,+ updatedAt: now,+ },+ });- yield* appendAndProject({- type: "thread.created",- eventId: EventId.makeUnsafe("evt-revert-files-2"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-revert-files-2"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"),- metadata: {},- payload: {- threadId,- projectId: ProjectId.makeUnsafe("project-revert-files"),- title: "Thread Revert Files",- model: "gpt-5-codex",- runtimeMode: "full-access",- branch: null,- worktreePath: null,- createdAt: now,- updatedAt: now,- },- });+ yield* appendAndProject({+ type: "thread.created",+ eventId: EventId.makeUnsafe("evt-revert-files-2"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-revert-files-2"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-revert-files-2"),+ metadata: {},+ payload: {+ threadId,+ projectId: ProjectId.makeUnsafe("project-revert-files"),+ title: "Thread Revert Files",+ model: "gpt-5-codex",+ runtimeMode: "full-access",+ branch: null,+ worktreePath: null,+ createdAt: now,+ updatedAt: now,+ },+ });- yield* appendAndProject({- type: "thread.turn-diff-completed",- eventId: EventId.makeUnsafe("evt-revert-files-3"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-revert-files-3"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"),- metadata: {},- payload: {- threadId,- turnId: TurnId.makeUnsafe("turn-keep"),- checkpointTurnCount: 1,- checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/1"),- status: "ready",- files: [],- assistantMessageId: MessageId.makeUnsafe("message-keep"),- completedAt: now,- },- });+ yield* appendAndProject({+ type: "thread.turn-diff-completed",+ eventId: EventId.makeUnsafe("evt-revert-files-3"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-revert-files-3"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-revert-files-3"),+ metadata: {},+ payload: {+ threadId,+ turnId: TurnId.makeUnsafe("turn-keep"),+ checkpointTurnCount: 1,+ checkpointRef: CheckpointRef.makeUnsafe(+ "refs/t3/checkpoints/thread-revert-files/turn/1",+ ),+ status: "ready",+ files: [],+ assistantMessageId: MessageId.makeUnsafe("message-keep"),+ completedAt: now,+ },+ });- yield* appendAndProject({- type: "thread.message-sent",- eventId: EventId.makeUnsafe("evt-revert-files-4"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-revert-files-4"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"),- metadata: {},- payload: {- threadId,- messageId: MessageId.makeUnsafe("message-keep"),- role: "assistant",- text: "Keep",- attachments: [- {- type: "image",- id: keepAttachmentId,- name: "keep.png",- mimeType: "image/png",- sizeBytes: 5,+ yield* appendAndProject({+ type: "thread.message-sent",+ eventId: EventId.makeUnsafe("evt-revert-files-4"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-revert-files-4"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-revert-files-4"),+ metadata: {},+ payload: {+ threadId,+ messageId: MessageId.makeUnsafe("message-keep"),+ role: "assistant",+ text: "Keep",+ attachments: [+ {+ type: "image",+ id: keepAttachmentId,+ name: "keep.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ],+ turnId: TurnId.makeUnsafe("turn-keep"),+ streaming: false,+ createdAt: now,+ updatedAt: now,},- ],- turnId: TurnId.makeUnsafe("turn-keep"),- streaming: false,- createdAt: now,- updatedAt: now,- },- });+ });- yield* appendAndProject({- type: "thread.turn-diff-completed",- eventId: EventId.makeUnsafe("evt-revert-files-5"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-revert-files-5"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"),- metadata: {},- payload: {- threadId,- turnId: TurnId.makeUnsafe("turn-remove"),- checkpointTurnCount: 2,- checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert-files/turn/2"),- status: "ready",- files: [],- assistantMessageId: MessageId.makeUnsafe("message-remove"),- completedAt: now,- },- });+ yield* appendAndProject({+ type: "thread.turn-diff-completed",+ eventId: EventId.makeUnsafe("evt-revert-files-5"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-revert-files-5"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-revert-files-5"),+ metadata: {},+ payload: {+ threadId,+ turnId: TurnId.makeUnsafe("turn-remove"),+ checkpointTurnCount: 2,+ checkpointRef: CheckpointRef.makeUnsafe(+ "refs/t3/checkpoints/thread-revert-files/turn/2",+ ),+ status: "ready",+ files: [],+ assistantMessageId: MessageId.makeUnsafe("message-remove"),+ completedAt: now,+ },+ });- yield* appendAndProject({- type: "thread.message-sent",- eventId: EventId.makeUnsafe("evt-revert-files-6"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-revert-files-6"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"),- metadata: {},- payload: {- threadId,- messageId: MessageId.makeUnsafe("message-remove"),- role: "assistant",- text: "Remove",- attachments: [- {- type: "image",- id: removeAttachmentId,- name: "remove.png",- mimeType: "image/png",- sizeBytes: 5,+ yield* appendAndProject({+ type: "thread.message-sent",+ eventId: EventId.makeUnsafe("evt-revert-files-6"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-revert-files-6"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-revert-files-6"),+ metadata: {},+ payload: {+ threadId,+ messageId: MessageId.makeUnsafe("message-remove"),+ role: "assistant",+ text: "Remove",+ attachments: [+ {+ type: "image",+ id: removeAttachmentId,+ name: "remove.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ],+ turnId: TurnId.makeUnsafe("turn-remove"),+ streaming: false,+ createdAt: now,+ updatedAt: now,},- ],- turnId: TurnId.makeUnsafe("turn-remove"),- streaming: false,- createdAt: now,- updatedAt: now,- },- });+ });- const keepPath = path.join(- stateDir,- "attachments",- `${keepAttachmentId}.png`,- );- const removePath = path.join(- stateDir,- "attachments",- `${removeAttachmentId}.png`,- );- fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });- fs.writeFileSync(keepPath, Buffer.from("keep"));- fs.writeFileSync(removePath, Buffer.from("remove"));- const otherThreadPath = path.join(stateDir, "attachments", `${otherThreadAttachmentId}.png`);- fs.writeFileSync(otherThreadPath, Buffer.from("other"));- assert.equal(fs.existsSync(keepPath), true);- assert.equal(fs.existsSync(removePath), true);- assert.equal(fs.existsSync(otherThreadPath), true);+ const keepPath = path.join(stateDir, "attachments", `${keepAttachmentId}.png`);+ const removePath = path.join(stateDir, "attachments", `${removeAttachmentId}.png`);+ fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });+ fs.writeFileSync(keepPath, Buffer.from("keep"));+ fs.writeFileSync(removePath, Buffer.from("remove"));+ const otherThreadPath = path.join(+ stateDir,+ "attachments",+ `${otherThreadAttachmentId}.png`,+ );+ fs.writeFileSync(otherThreadPath, Buffer.from("other"));+ assert.equal(fs.existsSync(keepPath), true);+ assert.equal(fs.existsSync(removePath), true);+ assert.equal(fs.existsSync(otherThreadPath), true);- yield* appendAndProject({- type: "thread.reverted",- eventId: EventId.makeUnsafe("evt-revert-files-7"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-revert-files-7"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"),- metadata: {},- payload: {- threadId,- turnCount: 1,- },- });+ yield* appendAndProject({+ type: "thread.reverted",+ eventId: EventId.makeUnsafe("evt-revert-files-7"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-revert-files-7"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-revert-files-7"),+ metadata: {},+ payload: {+ threadId,+ turnCount: 1,+ },+ });assert.equal(fs.existsSync(keepPath), true);assert.equal(fs.existsSync(removePath), false);@@ -962,107 +952,107 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));yield* appendAndProject({- type: "project.created",- eventId: EventId.makeUnsafe("evt-delete-files-1"),- aggregateKind: "project",- aggregateId: ProjectId.makeUnsafe("project-delete-files"),- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-delete-files-1"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"),- metadata: {},- payload: {- projectId: ProjectId.makeUnsafe("project-delete-files"),- title: "Project Delete Files",- workspaceRoot: "/tmp/project-delete-files",- defaultModel: null,- scripts: [],- createdAt: now,- updatedAt: now,- },- });+ type: "project.created",+ eventId: EventId.makeUnsafe("evt-delete-files-1"),+ aggregateKind: "project",+ aggregateId: ProjectId.makeUnsafe("project-delete-files"),+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-delete-files-1"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-delete-files-1"),+ metadata: {},+ payload: {+ projectId: ProjectId.makeUnsafe("project-delete-files"),+ title: "Project Delete Files",+ workspaceRoot: "/tmp/project-delete-files",+ defaultModel: null,+ scripts: [],+ createdAt: now,+ updatedAt: now,+ },+ });- yield* appendAndProject({- type: "thread.created",- eventId: EventId.makeUnsafe("evt-delete-files-2"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-delete-files-2"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"),- metadata: {},- payload: {- threadId,- projectId: ProjectId.makeUnsafe("project-delete-files"),- title: "Thread Delete Files",- model: "gpt-5-codex",- runtimeMode: "full-access",- branch: null,- worktreePath: null,- createdAt: now,- updatedAt: now,- },- });+ yield* appendAndProject({+ type: "thread.created",+ eventId: EventId.makeUnsafe("evt-delete-files-2"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-delete-files-2"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-delete-files-2"),+ metadata: {},+ payload: {+ threadId,+ projectId: ProjectId.makeUnsafe("project-delete-files"),+ title: "Thread Delete Files",+ model: "gpt-5-codex",+ runtimeMode: "full-access",+ branch: null,+ worktreePath: null,+ createdAt: now,+ updatedAt: now,+ },+ });- yield* appendAndProject({- type: "thread.message-sent",- eventId: EventId.makeUnsafe("evt-delete-files-3"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-delete-files-3"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"),- metadata: {},- payload: {- threadId,- messageId: MessageId.makeUnsafe("message-delete-files"),- role: "user",- text: "Delete",- attachments: [- {- type: "image",- id: attachmentId,- name: "delete.png",- mimeType: "image/png",- sizeBytes: 5,+ yield* appendAndProject({+ type: "thread.message-sent",+ eventId: EventId.makeUnsafe("evt-delete-files-3"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-delete-files-3"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-delete-files-3"),+ metadata: {},+ payload: {+ threadId,+ messageId: MessageId.makeUnsafe("message-delete-files"),+ role: "user",+ text: "Delete",+ attachments: [+ {+ type: "image",+ id: attachmentId,+ name: "delete.png",+ mimeType: "image/png",+ sizeBytes: 5,+ },+ ],+ turnId: null,+ streaming: false,+ createdAt: now,+ updatedAt: now,},- ],- turnId: null,- streaming: false,- createdAt: now,- updatedAt: now,- },- });+ });- const threadAttachmentPath = path.join(stateDir, "attachments", `${attachmentId}.png`);- const otherThreadAttachmentPath = path.join(- stateDir,- "attachments",- `${otherThreadAttachmentId}.png`,- );- fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });- fs.writeFileSync(threadAttachmentPath, Buffer.from("delete"));- fs.writeFileSync(otherThreadAttachmentPath, Buffer.from("other-thread"));- assert.equal(fs.existsSync(threadAttachmentPath), true);- assert.equal(fs.existsSync(otherThreadAttachmentPath), true);+ const threadAttachmentPath = path.join(stateDir, "attachments", `${attachmentId}.png`);+ const otherThreadAttachmentPath = path.join(+ stateDir,+ "attachments",+ `${otherThreadAttachmentId}.png`,+ );+ fs.mkdirSync(path.join(stateDir, "attachments"), { recursive: true });+ fs.writeFileSync(threadAttachmentPath, Buffer.from("delete"));+ fs.writeFileSync(otherThreadAttachmentPath, Buffer.from("other-thread"));+ assert.equal(fs.existsSync(threadAttachmentPath), true);+ assert.equal(fs.existsSync(otherThreadAttachmentPath), true);- yield* appendAndProject({- type: "thread.deleted",- eventId: EventId.makeUnsafe("evt-delete-files-4"),- aggregateKind: "thread",- aggregateId: threadId,- occurredAt: now,- commandId: CommandId.makeUnsafe("cmd-delete-files-4"),- causationEventId: null,- correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"),- metadata: {},- payload: {- threadId,- deletedAt: now,- },- });+ yield* appendAndProject({+ type: "thread.deleted",+ eventId: EventId.makeUnsafe("evt-delete-files-4"),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: now,+ commandId: CommandId.makeUnsafe("cmd-delete-files-4"),+ causationEventId: null,+ correlationId: CorrelationId.makeUnsafe("cmd-delete-files-4"),+ metadata: {},+ payload: {+ threadId,+ deletedAt: now,+ },+ });assert.equal(fs.existsSync(threadAttachmentPath), false);assert.equal(fs.existsSync(otherThreadAttachmentPath), true);@@ -1075,7 +1065,9 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {);it.effect("ignores unsafe thread ids for attachment cleanup paths", () =>- Effect.sync(() => fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-unsafe-"))).pipe(+ Effect.sync(() =>+ fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-unsafe-")),+ ).pipe(Effect.flatMap((stateDir) =>Effect.gen(function* () {const projectionPipeline = yield* OrchestrationProjectionPipeline;diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 24b81d514..6ae94105a 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -78,9 +78,8 @@ interface AttachmentSideEffects {}const materializeAttachmentsForProjection = Effect.fn(- (input: {- readonly attachments: ReadonlyArray<ChatAttachment>;- }) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),+ (input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>+ Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),);function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {@@ -336,7 +335,6 @@ const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSid},{ concurrency: 1 },);-});const makeOrchestrationProjectionPipeline = Effect.gen(function* () {diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex e7e9cd4e1..fc7db5480 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -1,11 +1,4 @@-import {- CheckpointRef,- EventId,- MessageId,- ProjectId,- ThreadId,- TurnId,-} from "@t3tools/contracts";+import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";import { assert, it } from "@effect/vitest";import { Effect, Layer } from "effect";import * as SqlClient from "effect/unstable/sql/SqlClient";diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.tsindex 4f352435f..cd74642b8 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts@@ -41,7 +41,10 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);-async function waitFor(predicate: () => boolean | Promise<boolean>, timeoutMs = 2000): Promise<void> {+async function waitFor(+ predicate: () => boolean | Promise<boolean>,+ timeoutMs = 2000,+): Promise<void> {const deadline = Date.now() + timeoutMs;const poll = async (): Promise<void> => {if (await predicate()) {@@ -101,7 +104,10 @@ describe("ProviderCommandReactor", () => {? input.resumeCursor: undefined;const model =- typeof input === "object" && input !== null && "model" in input && typeof input.model === "string"+ typeof input === "object" &&+ input !== null &&+ "model" in input &&+ typeof input.model === "string"? input.model: undefined;const threadId =@@ -474,7 +480,9 @@ describe("ProviderCommandReactor", () => {await waitFor(async () => {const readModel = await Effect.runPromise(harness.engine.getReadModel());- const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));+ const thread = readModel.threads.find(+ (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),+ );return thread?.runtimeMode === "approval-required";});await waitFor(() => harness.startSession.mock.calls.length === 2);@@ -563,7 +571,9 @@ describe("ProviderCommandReactor", () => {await waitFor(async () => {const readModel = await Effect.runPromise(harness.engine.getReadModel());- const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));+ const thread = readModel.threads.find(+ (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),+ );return thread?.runtimeMode === "approval-required";});await waitFor(() => harness.startSession.mock.calls.length === 2);@@ -767,9 +777,13 @@ describe("ProviderCommandReactor", () => {await waitFor(async () => {const readModel = await Effect.runPromise(harness.engine.getReadModel());- const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));+ const thread = readModel.threads.find(+ (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),+ );if (!thread) return false;- return thread.activities.some((activity) => activity.kind === "provider.approval.respond.failed");+ return thread.activities.some(+ (activity) => activity.kind === "provider.approval.respond.failed",+ );});const readModel = await Effect.runPromise(harness.engine.getReadModel());diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.tsindex 39f137643..bd1c53b77 100644--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts@@ -224,9 +224,9 @@ const make = Effect.gen(function* () {});const resolveActiveSession = (threadId: ThreadId) =>- providerService.listSessions().pipe(- Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)),- );+ providerService+ .listSessions()+ .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));const startProviderSession = (input?: {readonly resumeCursor?: unknown;@@ -234,13 +234,15 @@ const make = Effect.gen(function* () {}) =>providerService.startSession(threadId, {threadId,- ...(input?.provider ?? preferredProvider+ ...((input?.provider ?? preferredProvider)? { provider: input?.provider ?? preferredProvider }: {}),...(effectiveCwd ? { cwd: effectiveCwd } : {}),...(desiredModel ? { model: desiredModel } : {}),...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),- ...(options?.providerOptions !== undefined ? { providerOptions: options.providerOptions } : {}),+ ...(options?.providerOptions !== undefined+ ? { providerOptions: options.providerOptions }+ : {}),...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),runtimeMode: desiredRuntimeMode,});@@ -265,16 +267,15 @@ const make = Effect.gen(function* () {thread.session && thread.session.status !== "stopped" ? thread.id : null;if (existingSessionThreadId) {const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;- const providerChanged = options?.provider !== undefined && options.provider !== currentProvider;+ const providerChanged =+ options?.provider !== undefined && options.provider !== currentProvider;const activeSession = yield* resolveActiveSession(existingSessionThreadId);const sessionModelSwitch =currentProvider === undefined? "in-session": (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;- const modelChanged =- options?.model !== undefined && options.model !== activeSession?.model;- const shouldRestartForModelChange =- modelChanged && sessionModelSwitch === "restart-session";+ const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;+ const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {return existingSessionThreadId;@@ -345,15 +346,16 @@ const make = Effect.gen(function* () {});const normalizedInput = toNonEmptyProviderInput(input.messageText);const normalizedAttachments = input.attachments ?? [];- const activeSession = yield* providerService.listSessions().pipe(- Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),- );+ const activeSession = yield* providerService+ .listSessions()+ .pipe(+ Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),+ );const sessionModelSwitch =activeSession === undefined? "in-session": (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;- const modelForTurn =- sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;+ const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;yield* providerService.sendTurn({threadId: input.threadId,@@ -474,8 +476,12 @@ const make = Effect.gen(function* () {...(message.attachments !== undefined ? { attachments: message.attachments } : {}),...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),...(event.payload.model !== undefined ? { model: event.payload.model } : {}),- ...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),- ...(event.payload.providerOptions !== undefined ? { providerOptions: event.payload.providerOptions } : {}),+ ...(event.payload.modelOptions !== undefined+ ? { modelOptions: event.payload.modelOptions }+ : {}),+ ...(event.payload.providerOptions !== undefined+ ? { providerOptions: event.payload.providerOptions }+ : {}),interactionMode: event.payload.interactionMode,createdAt: event.payload.createdAt,});diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.tsindex 7a1d0399f..76d6ecfee 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts@@ -379,7 +379,9 @@ describe("ProviderRuntimeIngestion", () => {await Effect.runPromise(Effect.sleep("40 millis"));const midReadModel = await Effect.runPromise(harness.engine.getReadModel());- const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));+ const midThread = midReadModel.threads.find(+ (entry) => entry.id === ThreadId.makeUnsafe("thread-1"),+ );expect(midThread?.session?.status).toBe("running");expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");@@ -620,7 +622,9 @@ describe("ProviderRuntimeIngestion", () => {const proposedPlan = thread.proposedPlans.find((entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-final",);- expect(proposedPlan?.planMarkdown).toBe("## Ship plan\n\n- wire projection\n- render follow-up");+ expect(proposedPlan?.planMarkdown).toBe(+ "## Ship plan\n\n- wire projection\n- render follow-up",+ );});it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {@@ -683,7 +687,8 @@ describe("ProviderRuntimeIngestion", () => {),);const proposedPlan = thread.proposedPlans.find(- (entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-buffer",+ (entry: ProviderRuntimeTestProposedPlan) =>+ entry.id === "plan:thread-1:turn:turn-plan-buffer",);expect(proposedPlan?.planMarkdown).toBe("## Buffered plan\n\n- first\n- second");});diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.tsindex 5a6f71d5e..bea3cdc81 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts@@ -210,9 +210,9 @@ function runtimeEventToActivities(? "Command approval requested": requestKind === "file-read"? "File-read approval requested"- : requestKind === "file-change"- ? "File-change approval requested"- : "Approval requested",+ : requestKind === "file-change"+ ? "File-change approval requested"+ : "Approval requested",payload: {requestId: toApprovalRequestId(event.requestId),...(requestKind ? { requestKind } : {}),@@ -298,7 +298,9 @@ function runtimeEventToActivities(summary: "Plan updated",payload: {plan: event.payload.plan,- ...(event.payload.explanation !== undefined ? { explanation: event.payload.explanation } : {}),+ ...(event.payload.explanation !== undefined+ ? { explanation: event.payload.explanation }+ : {}),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -358,7 +360,9 @@ function runtimeEventToActivities(payload: {taskId: event.payload.taskId,...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),- ...(event.payload.description ? { detail: truncateDetail(event.payload.description) } : {}),+ ...(event.payload.description+ ? { detail: truncateDetail(event.payload.description) }+ : {}),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,@@ -525,11 +529,7 @@ const make = Effect.gen(function* () {return isGitRepository(workspaceCwd);});- const rememberAssistantMessageId = (- threadId: ThreadId,- turnId: TurnId,- messageId: MessageId,- ) =>+ const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(Effect.flatMap((existingIds) =>Cache.set(@@ -547,11 +547,7 @@ const make = Effect.gen(function* () {),);- const forgetAssistantMessageId = (- threadId: ThreadId,- turnId: TurnId,- messageId: MessageId,- ) =>+ const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(Effect.flatMap((existingIds) =>Option.match(existingIds, {@@ -616,7 +612,8 @@ const make = Effect.gen(function* () {const existing = Option.getOrUndefined(existingEntry);return Cache.set(bufferedProposedPlanById, planId, {text: `${existing?.text ?? ""}${delta}`,- createdAt: existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,+ createdAt:+ existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,});}),);@@ -633,7 +630,8 @@ const make = Effect.gen(function* () {const clearBufferedProposedPlan = (planId: string) =>Cache.invalidate(bufferedProposedPlanById, planId);- const clearAssistantMessageState = (messageId: MessageId) => clearBufferedAssistantText(messageId);+ const clearAssistantMessageState = (messageId: MessageId) =>+ clearBufferedAssistantText(messageId);const finalizeAssistantMessage = (input: {event: ProviderRuntimeEvent;@@ -862,8 +860,8 @@ const make = Effect.gen(function* () {: event.type === "turn.completed" && runtimeTurnState(event) === "failed"? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed"): status === "ready"- ? null- : (thread.session?.lastError ?? null);+ ? null+ : (thread.session?.lastError ?? null);if (shouldApplyThreadLifecycle) {yield* orchestrationEngine.dispatch({@@ -935,7 +933,9 @@ const make = Effect.gen(function* () {const assistantCompletion =event.type === "item.completed" && event.payload.itemType === "assistant_message"? {- messageId: MessageId.makeUnsafe(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),+ messageId: MessageId.makeUnsafe(+ `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,+ ),fallbackText: event.payload.detail,}: undefined;@@ -951,10 +951,11 @@ const make = Effect.gen(function* () {if (assistantCompletion) {const assistantMessageId = assistantCompletion.messageId;const turnId = toTurnId(event.turnId);- const existingAssistantMessage = thread.messages.find((entry) => entry.id === assistantMessageId);+ const existingAssistantMessage = thread.messages.find(+ (entry) => entry.id === assistantMessageId,+ );const shouldApplyFallbackCompletionText =- !existingAssistantMessage ||- existingAssistantMessage.text.length === 0;+ !existingAssistantMessage || existingAssistantMessage.text.length === 0;if (turnId) {yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);}@@ -1029,9 +1030,7 @@ const make = Effect.gen(function* () {const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD? true- : activeTurnId === null ||- eventTurnId === undefined ||- sameId(activeTurnId, eventTurnId);+ : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);if (shouldApplyRuntimeError) {yield* orchestrationEngine.dispatch({diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex 2218f88cf..eea41a2b3 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -302,7 +302,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"...(command.provider !== undefined ? { provider: command.provider } : {}),...(command.model !== undefined ? { model: command.model } : {}),...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),- ...(command.providerOptions !== undefined ? { providerOptions: command.providerOptions } : {}),+ ...(command.providerOptions !== undefined+ ? { providerOptions: command.providerOptions }+ : {}),assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,runtimeMode:readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex c0badfe95..60575d30a 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -304,12 +304,7 @@ export function projectEvent();case "thread.runtime-mode-set":- return decodeForEvent(- ThreadRuntimeModeSetPayload,- event.payload,- event.type,- "payload",- ).pipe(+ return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, "payload").pipe(Effect.map((payload) => ({...nextBase,threads: updateThread(nextBase.threads, payload.threadId, {diff --git a/apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.ts b/apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.tsindex 24446e04d..3d103592f 100644--- a/apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreadProposedPlans.ts@@ -70,9 +70,7 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {const upsert: ProjectionThreadProposedPlanRepositoryShape["upsert"] = (row) =>upsertProjectionThreadProposedPlanRow(row).pipe(- Effect.mapError(- toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query"),- ),+ Effect.mapError(toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query")),);const listByThreadId: ProjectionThreadProposedPlanRepositoryShape["listByThreadId"] = (input) =>diff --git a/apps/server/src/projectFaviconRoute.test.ts b/apps/server/src/projectFaviconRoute.test.tsindex 34a430d97..a346e513e 100644--- a/apps/server/src/projectFaviconRoute.test.ts+++ b/apps/server/src/projectFaviconRoute.test.ts@@ -20,9 +20,7 @@ function makeTempDir(prefix: string): string {return dir;}-async function withRouteServer(- run: (baseUrl: string) => Promise<void>,-): Promise<void> {+async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> {const server = http.createServer((req, res) => {const url = new URL(req.url ?? "/", "http://127.0.0.1");if (tryHandleProjectFaviconRequest(url, res)) {@@ -104,7 +102,10 @@ describe("tryHandleProjectFaviconRequest", () => {const projectDir = makeTempDir("t3code-favicon-route-source-");const iconPath = path.join(projectDir, "public", "brand", "logo.svg");fs.mkdirSync(path.dirname(iconPath), { recursive: true });- fs.writeFileSync(path.join(projectDir, "index.html"), '<link rel="icon" href="/brand/logo.svg">');+ fs.writeFileSync(+ path.join(projectDir, "index.html"),+ '<link rel="icon" href="/brand/logo.svg">',+ );fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");await withRouteServer(async (baseUrl) => {@@ -120,7 +121,10 @@ describe("tryHandleProjectFaviconRequest", () => {const projectDir = makeTempDir("t3code-favicon-route-html-order-");const iconPath = path.join(projectDir, "public", "brand", "logo.svg");fs.mkdirSync(path.dirname(iconPath), { recursive: true });- fs.writeFileSync(path.join(projectDir, "index.html"), '<link href="/brand/logo.svg" rel="icon">');+ fs.writeFileSync(+ path.join(projectDir, "index.html"),+ '<link href="/brand/logo.svg" rel="icon">',+ );fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");await withRouteServer(async (baseUrl) => {diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.tsindex cb11219fc..2381cec32 100644--- a/apps/server/src/provider/Layers/CodexAdapter.ts+++ b/apps/server/src/provider/Layers/CodexAdapter.ts@@ -403,7 +403,9 @@ function asRuntimeTaskId(taskId: string): RuntimeTaskId {return RuntimeTaskId.makeUnsafe(taskId);}-function codexEventMessage(payload: Record<string, unknown> | undefined): Record<string, unknown> | undefined {+function codexEventMessage(+ payload: Record<string, unknown> | undefined,+): Record<string, unknown> | undefined {return asObject(payload?.msg);}@@ -1037,7 +1039,9 @@ function mapToRuntimeEvents(type: "content.delta",payload: {streamKind:- asNumber(msg?.summary_index) !== undefined ? "reasoning_summary_text" : "reasoning_text",+ asNumber(msg?.summary_index) !== undefined+ ? "reasoning_summary_text"+ : "reasoning_text",delta,...(asNumber(msg?.summary_index) !== undefined? { summaryIndex: asNumber(msg?.summary_index) }@@ -1314,9 +1318,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>detail: toMessage(cause, "Failed to start Codex adapter session."),cause,}),- }).pipe(- Effect.map((session) => session),- );+ }).pipe(Effect.map((session) => session));};const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.tsindex a50112a62..c6f4a3c08 100644--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts@@ -29,10 +29,7 @@ const fakeCodexAdapter: CodexAdapterShape = {const layer = it.layer(Layer.mergeAll(- Layer.provide(- ProviderAdapterRegistryLive,- Layer.succeed(CodexAdapter, fakeCodexAdapter),- ),+ Layer.provide(ProviderAdapterRegistryLive, Layer.succeed(CodexAdapter, fakeCodexAdapter)),NodeServices.layer,),);diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.tsindex 4f2c7f2c7..3062ed790 100644--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts@@ -23,10 +23,7 @@ export interface ProviderAdapterRegistryLiveOptions {const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>Effect.gen(function* () {- const adapters =- options?.adapters !== undefined- ? options.adapters- : [yield* CodexAdapter];+ const adapters = options?.adapters !== undefined ? options.adapters : [yield* CodexAdapter];const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {diff --git a/apps/server/src/provider/Layers/ProviderHealth.test.ts b/apps/server/src/provider/Layers/ProviderHealth.test.tsindex 90df9b691..964b45ba4 100644--- a/apps/server/src/provider/Layers/ProviderHealth.test.ts+++ b/apps/server/src/provider/Layers/ProviderHealth.test.ts@@ -132,30 +132,27 @@ it.effect("returns unauthenticated when auth probe reports login required", () =),);-it.effect(- "returns unauthenticated when login status output includes 'not logged in'",- () =>- Effect.gen(function* () {- const status = yield* checkCodexProviderStatus;- assert.strictEqual(status.provider, "codex");- assert.strictEqual(status.status, "error");- assert.strictEqual(status.available, true);- assert.strictEqual(status.authStatus, "unauthenticated");- assert.strictEqual(- status.message,- "Codex CLI is not authenticated. Run `codex login` and try again.",- );- }).pipe(- Effect.provide(- mockSpawnerLayer((args) => {- const joined = args.join(" ");- if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };- if (joined === "login status")- return { stdout: "Not logged in\n", stderr: "", code: 1 };- throw new Error(`Unexpected args: ${joined}`);- }),- ),+it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>+ Effect.gen(function* () {+ const status = yield* checkCodexProviderStatus;+ assert.strictEqual(status.provider, "codex");+ assert.strictEqual(status.status, "error");+ assert.strictEqual(status.available, true);+ assert.strictEqual(status.authStatus, "unauthenticated");+ assert.strictEqual(+ status.message,+ "Codex CLI is not authenticated. Run `codex login` and try again.",+ );+ }).pipe(+ Effect.provide(+ mockSpawnerLayer((args) => {+ const joined = args.join(" ");+ if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };+ if (joined === "login status") return { stdout: "Not logged in\n", stderr: "", code: 1 };+ throw new Error(`Unexpected args: ${joined}`);+ }),),+ ),);it.effect("returns warning when login status command is unsupported", () =>diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.tsindex 63b41d6b0..178f86916 100644--- a/apps/server/src/provider/Layers/ProviderService.test.ts+++ b/apps/server/src/provider/Layers/ProviderService.test.ts@@ -635,7 +635,6 @@ routing.layer("ProviderServiceLive routing", (it) => {assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");}}-}),);});diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.tsindex 05a1de149..088f5ba5f 100644--- a/apps/server/src/provider/Layers/ProviderService.ts+++ b/apps/server/src/provider/Layers/ProviderService.ts@@ -141,9 +141,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>Effect.succeed(event).pipe(Effect.tap((canonicalEvent) =>- canonicalEventLogger- ? canonicalEventLogger.write(canonicalEvent, null)- : Effect.void,+ canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,),Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),Effect.asVoid,@@ -193,7 +191,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);if (hasActiveSession) {const activeSessions = yield* adapter.listSessions();- const existing = activeSessions.find((session) => session.threadId === input.binding.threadId);+ const existing = activeSessions.find(+ (session) => session.threadId === input.binding.threadId,+ );if (existing) {yield* upsertSessionBinding(existing, input.binding.threadId);yield* analytics.record("provider.session.recovered", {@@ -292,7 +292,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>}yield* upsertSessionBinding(session, threadId, {- ...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),+ ...(input.providerOptions !== undefined+ ? { providerOptions: input.providerOptions }+ : {}),});yield* analytics.record("provider.session.started", {provider: session.provider,@@ -425,23 +427,23 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>const listSessions: ProviderServiceShape["listSessions"] = () =>Effect.gen(function* () {- const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) => adapter.listSessions());+ const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>+ adapter.listSessions(),+ );const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);- const persistedBindings = yield* directory- .listThreadIds()- .pipe(- Effect.flatMap((threadIds) =>- Effect.forEach(- threadIds,- (threadId) =>- directory.getBinding(threadId).pipe(- Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>()),- ),- { concurrency: "unbounded" },- ),+ const persistedBindings = yield* directory.listThreadIds().pipe(+ Effect.flatMap((threadIds) =>+ Effect.forEach(+ threadIds,+ (threadId) =>+ directory+ .getBinding(threadId)+ .pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),+ { concurrency: "unbounded" },),- Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),- );+ ),+ Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),+ );const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();for (const bindingOption of persistedBindings) {const binding = Option.getOrUndefined(bindingOption);diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.tsindex 69e1e439b..38e097e1c 100644--- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts+++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts@@ -2,10 +2,7 @@ import { type ProviderKind, type ThreadId } from "@t3tools/contracts";import { Effect, Layer, Option } from "effect";import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";-import {- ProviderSessionDirectoryPersistenceError,- ProviderValidationError,-} from "../Errors.ts";+import { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from "../Errors.ts";import {ProviderSessionDirectory,type ProviderRuntimeBinding,@@ -138,7 +135,9 @@ const makeProviderSessionDirectory = Effect.gen(function* () {const remove: ProviderSessionDirectoryShape["remove"] = (threadId) =>repository.deleteByThreadId({ threadId })- .pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")));+ .pipe(+ Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")),+ );const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>repository.list().pipe(diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.tsindex 67755b538..38a05f757 100644--- a/apps/server/src/provider/Services/ProviderAdapter.ts+++ b/apps/server/src/provider/Services/ProviderAdapter.ts@@ -66,10 +66,7 @@ export interface ProviderAdapterShape<TError> {/*** Interrupt an active turn.*/- readonly interruptTurn: (- threadId: ThreadId,- turnId?: TurnId,- ) => Effect.Effect<void, TError>;+ readonly interruptTurn: (threadId: ThreadId, turnId?: TurnId) => Effect.Effect<void, TError>;/*** Respond to an interactive approval request.@@ -107,9 +104,7 @@ export interface ProviderAdapterShape<TError> {/*** Read a provider thread snapshot.*/- readonly readThread: (- threadId: ThreadId,- ) => Effect.Effect<ProviderThreadSnapshot, TError>;+ readonly readThread: (threadId: ThreadId) => Effect.Effect<ProviderThreadSnapshot, TError>;/*** Roll back a provider thread by N turns.diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.tsindex cb9092cc7..ecb4c09ef 100644--- a/apps/server/src/wsServer.test.ts+++ b/apps/server/src/wsServer.test.ts@@ -1236,21 +1236,19 @@ describe("WebSocket Server", () => {return event.type === "thread.session-set";});- emitRuntimeEvent(- {- type: "content.delta",- eventId: asEventId("evt-ws-runtime-message-delta"),- provider: "codex",- threadId: asThreadId("thread-1"),- createdAt: new Date().toISOString(),- turnId: asTurnId("turn-1"),- itemId: asProviderItemId("item-1"),- payload: {- streamKind: "assistant_text",- delta: "hello from runtime",- },- } as unknown as ProviderRuntimeEvent,- );+ emitRuntimeEvent({+ type: "content.delta",+ eventId: asEventId("evt-ws-runtime-message-delta"),+ provider: "codex",+ threadId: asThreadId("thread-1"),+ createdAt: new Date().toISOString(),+ turnId: asTurnId("turn-1"),+ itemId: asProviderItemId("item-1"),+ payload: {+ streamKind: "assistant_text",+ delta: "hello from runtime",+ },+ } as unknown as ProviderRuntimeEvent);const domainPush = await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => {const event = push.data as { type?: string; payload?: { messageId?: string; text?: string } };@@ -1568,7 +1566,9 @@ describe("WebSocket Server", () => {});expect(response.result).toBeUndefined();- expect(response.error?.message).toContain("Workspace file path must stay within the project root.");+ expect(response.error?.message).toContain(+ "Workspace file path must stay within the project root.",+ );expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false);});diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.tsindex cc118eb75..1bd1c02c4 100644--- a/apps/server/src/wsServer.ts+++ b/apps/server/src/wsServer.ts@@ -198,8 +198,7 @@ function stripRequestTag<T extends { _tag: string }>(body: T) {function messageFromCause(cause: Cause.Cause<unknown>): string {const squashed = Cause.squash(cause);- const message =- squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();+ const message = squashed instanceof Error ? squashed.message.trim() : String(squashed).trim();return message.length > 0 ? message : Cause.pretty(cause);}@@ -330,10 +329,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<} satisfies OrchestrationCommand;}- if (- input.command.type === "project.meta.update" &&- input.command.workspaceRoot !== undefined- ) {+ if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {return {...input.command,workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),@@ -793,14 +789,16 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<relativePath: body.relativePath,path,});- yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(- Effect.mapError(- (cause) =>- new RouteRequestError({- message: `Failed to prepare workspace path: ${String(cause)}`,- }),- ),- );+ yield* fileSystem+ .makeDirectory(path.dirname(target.absolutePath), { recursive: true })+ .pipe(+ Effect.mapError(+ (cause) =>+ new RouteRequestError({+ message: `Failed to prepare workspace path: ${String(cause)}`,+ }),+ ),+ );yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(Effect.mapError((cause) =>diff --git a/apps/web/src/appSettings.test.ts b/apps/web/src/appSettings.test.tsindex 6c6cbac49..213e4cd3d 100644--- a/apps/web/src/appSettings.test.ts+++ b/apps/web/src/appSettings.test.ts@@ -61,23 +61,13 @@ describe("resolveAppModelSelection", () => {describe("getSlashModelOptions", () => {it("includes saved custom model slugs for /model command suggestions", () => {- const options = getSlashModelOptions(- "codex",- ["custom/internal-model"],- "",- "gpt-5.3-codex",- );+ const options = getSlashModelOptions("codex", ["custom/internal-model"], "", "gpt-5.3-codex");expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);});it("filters slash-model suggestions across built-in and custom model names", () => {- const options = getSlashModelOptions(- "codex",- ["openai/gpt-oss-120b"],- "oss",- "gpt-5.3-codex",- );+ const options = getSlashModelOptions("codex", ["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);});diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsxindex c6311ccac..b2c60b242 100644--- a/apps/web/src/components/BranchToolbar.tsx+++ b/apps/web/src/components/BranchToolbar.tsx@@ -130,9 +130,7 @@ export default function BranchToolbar({effectiveEnvMode={effectiveEnvMode}envLocked={envLocked}onSetThreadBranch={setThreadBranch}- {...(onCheckoutPullRequestRequest- ? { onCheckoutPullRequestRequest }- : {})}+ {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}/></div>diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsxindex dbef056ca..944627916 100644--- a/apps/web/src/components/BranchToolbarBranchSelector.tsx+++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx@@ -113,27 +113,23 @@ export function BranchToolbarBranchSelector({const prReference = parsePullRequestReference(trimmedBranchQuery);const isSelectingWorktreeBase =effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;- const checkoutPullRequestItemValue = prReference && onCheckoutPullRequestRequest- ? `__checkout_pull_request__:${prReference}`- : null;+ const checkoutPullRequestItemValue =+ prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);const createBranchItemValue = canCreateBranch? `__create_new_branch__:${trimmedBranchQuery}`: null;- const branchPickerItems = useMemo(- () => {- const items = [...branchNames];- if (createBranchItemValue && !hasExactBranchMatch) {- items.push(createBranchItemValue);- }- if (checkoutPullRequestItemValue) {- items.unshift(checkoutPullRequestItemValue);- }- return items;- },- [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch],- );+ const branchPickerItems = useMemo(() => {+ const items = [...branchNames];+ if (createBranchItemValue && !hasExactBranchMatch) {+ items.push(createBranchItemValue);+ }+ if (checkoutPullRequestItemValue) {+ items.unshift(checkoutPullRequestItemValue);+ }+ return items;+ }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);const filteredBranchPickerItems = useMemo(() =>normalizedDeferredBranchQuery.length === 0@@ -397,9 +393,7 @@ export function BranchToolbarBranchSelector({><div className="flex w-full items-center justify-between gap-2"><span className="truncate">{itemValue}</span>- {badge && (- <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>- )}+ {badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}</div></ComboboxItem>);diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsxindex 0f0250e48..8e02af232 100644--- a/apps/web/src/components/ChatView.browser.tsx+++ b/apps/web/src/components/ChatView.browser.tsx@@ -414,9 +414,9 @@ async function setViewport(viewport: ViewportSpec): Promise<void> {async function waitForProductionStyles(): Promise<void> {await vi.waitFor(() => {- expect(getComputedStyle(document.documentElement).getPropertyValue("--background").trim()).not.toBe(- "",- );+ expect(+ getComputedStyle(document.documentElement).getPropertyValue("--background").trim(),+ ).not.toBe("");expect(getComputedStyle(document.body).marginTop).toBe("0px");},{@@ -454,7 +454,9 @@ async function waitForComposerEditor(): Promise<HTMLElement> {);}-async function waitForInteractionModeButton(expectedLabel: "Chat" | "Plan"): Promise<HTMLButtonElement> {+async function waitForInteractionModeButton(+ expectedLabel: "Chat" | "Plan",+): Promise<HTMLButtonElement> {return waitForElement(() =>Array.from(document.querySelectorAll("button")).find(@@ -697,7 +699,9 @@ describe("ChatView timeline estimator parity (full app)", () => {});try {- const measurements: Array<UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }> = [];+ const measurements: Array<+ UserRowMeasurement & { viewport: ViewportSpec; estimatedHeightPx: number }+ > = [];for (const viewport of TEXT_VIEWPORT_MATRIX) {await mounted.setViewport(viewport);@@ -714,7 +718,10 @@ describe("ChatView timeline estimator parity (full app)", () => {measurements.push({ ...measurement, viewport, estimatedHeightPx });}- expect(new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx))).size).toBeGreaterThanOrEqual(3);+ expect(+ new Set(measurements.map((measurement) => Math.round(measurement.timelineWidthMeasuredPx)))+ .size,+ ).toBeGreaterThanOrEqual(3);const byMeasuredWidth = measurements.toSorted((left, right) => left.timelineWidthMeasuredPx - right.timelineWidthMeasuredPx,@@ -756,7 +763,8 @@ describe("ChatView timeline estimator parity (full app)", () => {{ timelineWidthPx: mobileMeasurement.timelineWidthMeasuredPx },);- const measuredDeltaPx = mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;+ const measuredDeltaPx =+ mobileMeasurement.measuredRowHeightPx - desktopMeasurement.measuredRowHeightPx;const estimatedDeltaPx = estimatedMobilePx - estimatedDesktopPx;expect(measuredDeltaPx).toBeGreaterThan(0);expect(estimatedDeltaPx).toBeGreaterThan(0);@@ -844,7 +852,9 @@ describe("ChatView timeline estimator parity (full app)", () => {await vi.waitFor(() => {- const openRequest = wsRequests.find((request) => request._tag === WS_METHODS.shellOpenInEditor);+ const openRequest = wsRequests.find(+ (request) => request._tag === WS_METHODS.shellOpenInEditor,+ );expect(openRequest).toMatchObject({_tag: WS_METHODS.shellOpenInEditor,cwd: "/repo/project",diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex ee3de304e..1bd167291 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -615,7 +615,9 @@ export default function ChatView({ threadId }: ChatViewProps) {const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);const clearDraftThread = useComposerDraftStore((store) => store.clearDraftThread);const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);- const getDraftThreadByProjectId = useComposerDraftStore((store) => store.getDraftThreadByProjectId);+ const getDraftThreadByProjectId = useComposerDraftStore(+ (store) => store.getDraftThreadByProjectId,+ );const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);const clearProjectDraftThreadId = useComposerDraftStore(@@ -657,9 +659,8 @@ export default function ChatView({ threadId }: ChatViewProps) {const [nowTick, setNowTick] = useState(() => Date.now());const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);- const [pullRequestDialogState, setPullRequestDialogState] = useState<PullRequestDialogState | null>(- null,- );+ const [pullRequestDialogState, setPullRequestDialogState] =+ useState<PullRequestDialogState | null>(null);const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<Record<string, string[]>>({});@@ -765,16 +766,19 @@ export default function ChatView({ threadId }: ChatViewProps) {const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);const activeProject = projects.find((p) => p.id === activeThread?.projectId);- const openPullRequestDialog = useCallback((reference?: string) => {- if (!canCheckoutPullRequestIntoThread) {- return;- }- setPullRequestDialogState({- initialReference: reference ?? null,- key: Date.now(),- });- setComposerHighlightedItemId(null);- }, [canCheckoutPullRequestIntoThread]);+ const openPullRequestDialog = useCallback(+ (reference?: string) => {+ if (!canCheckoutPullRequestIntoThread) {+ return;+ }+ setPullRequestDialogState({+ initialReference: reference ?? null,+ key: Date.now(),+ });+ setComposerHighlightedItemId(null);+ },+ [canCheckoutPullRequestIntoThread],+ );const closePullRequestDialog = useCallback(() => {setPullRequestDialogState(null);@@ -4131,7 +4135,8 @@ export default function ChatView({ threadId }: ChatViewProps) {onPrepared={handlePreparedPullRequestThread}/>) : null}- </div>{/* end chat column */}+ </div>+ {/* end chat column */}{/* Plan sidebar */}{planSidebarOpen ? (@@ -5744,10 +5749,7 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {}><span- className={cn(- "flex min-w-0 items-center gap-2",- props.compact ? "max-w-36" : undefined,- )}+ className={cn("flex min-w-0 items-center gap-2", props.compact ? "max-w-36" : undefined)}><ProviderIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground/70" /><span className="truncate">{selectedModelLabel}</span>diff --git a/apps/web/src/components/ComposerPromptEditor.tsx b/apps/web/src/components/ComposerPromptEditor.tsxindex 2c089dab0..8b1ca4dc7 100644--- a/apps/web/src/components/ComposerPromptEditor.tsx+++ b/apps/web/src/components/ComposerPromptEditor.tsx@@ -1,7 +1,4 @@-import {- LexicalComposer,- type InitialConfigType,-} from "@lexical/react/LexicalComposer";+import { LexicalComposer, type InitialConfigType } from "@lexical/react/LexicalComposer";import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";import { ContentEditable } from "@lexical/react/LexicalContentEditable";import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";@@ -331,12 +328,11 @@ function $setSelectionAtComposerOffset(nextOffset: number): void {const composerLength = $getComposerRootLength();const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));const remainingRef = { value: boundedOffset };- const point =- findSelectionPointAtOffset(root, remainingRef) ?? {- key: root.getKey(),- offset: root.getChildren().length,- type: "element" as const,- };+ const point = findSelectionPointAtOffset(root, remainingRef) ?? {+ key: root.getKey(),+ offset: root.getChildren().length,+ type: "element" as const,+ };const selection = $createRangeSelection();selection.anchor.set(point.key, point.offset, point.type);selection.focus.set(point.key, point.offset, point.type);@@ -724,7 +720,10 @@ function ComposerPromptEditorInner({editorState.read(() => {const nextValue = $getRoot().getTextContent();const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);- const nextCursor = clampCursor(nextValue, $readSelectionOffsetFromEditorState(fallbackCursor));+ const nextCursor = clampCursor(+ nextValue,+ $readSelectionOffsetFromEditorState(fallbackCursor),+ );const previousSnapshot = snapshotRef.current;if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {return;@@ -771,41 +770,42 @@ function ComposerPromptEditorInner({);}-export const ComposerPromptEditor = forwardRef<ComposerPromptEditorHandle, ComposerPromptEditorProps>(- function ComposerPromptEditor(- { value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },- ref,- ) {- const initialValueRef = useRef(value);- const initialConfig = useMemo<InitialConfigType>(- () => ({- namespace: "t3tools-composer-editor",- editable: true,- nodes: [ComposerMentionNode],- editorState: () => {- $setComposerEditorPrompt(initialValueRef.current);- },- onError: (error) => {- throw error;- },- }),- [],- );+export const ComposerPromptEditor = forwardRef<+ ComposerPromptEditorHandle,+ ComposerPromptEditorProps+>(function ComposerPromptEditor(+ { value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },+ ref,+) {+ const initialValueRef = useRef(value);+ const initialConfig = useMemo<InitialConfigType>(+ () => ({+ namespace: "t3tools-composer-editor",+ editable: true,+ nodes: [ComposerMentionNode],+ editorState: () => {+ $setComposerEditorPrompt(initialValueRef.current);+ },+ onError: (error) => {+ throw error;+ },+ }),+ [],+ );- return (- <LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>- <ComposerPromptEditorInner- value={value}- cursor={cursor}- disabled={disabled}- placeholder={placeholder}- onChange={onChange}- onPaste={onPaste}- editorRef={ref}- {...(onCommandKeyDown ? { onCommandKeyDown } : {})}- {...(className ? { className } : {})}- />- </LexicalComposer>- );- },-);+ return (+ <LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>+ <ComposerPromptEditorInner+ value={value}+ cursor={cursor}+ disabled={disabled}+ placeholder={placeholder}+ onChange={onChange}+ onPaste={onPaste}+ editorRef={ref}+ {...(onCommandKeyDown ? { onCommandKeyDown } : {})}+ {...(className ? { className } : {})}+ />+ </LexicalComposer>+ );+});diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsxindex 27248ce63..1293f51f7 100644--- a/apps/web/src/components/DiffPanel.tsx+++ b/apps/web/src/components/DiffPanel.tsx@@ -4,7 +4,14 @@ import { useQuery } from "@tanstack/react-query";import { useNavigate, useParams, useSearch } from "@tanstack/react-router";import { ThreadId, type TurnId } from "@t3tools/contracts";import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";-import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ type WheelEvent as ReactWheelEvent,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";import { cn } from "~/lib/utils";diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.tsindex 3755e1e80..48edad37c 100644--- a/apps/web/src/components/GitActionsControl.logic.test.ts+++ b/apps/web/src/components/GitActionsControl.logic.test.ts@@ -577,10 +577,7 @@ describe("when: branch has no upstream configured", () => {});it("buildMenuItems disables push and create PR when no commits are ahead", () => {- const items = buildMenuItems(- status({ hasUpstream: false, pr: null, aheadCount: 0 }),- false,- );+ const items = buildMenuItems(status({ hasUpstream: false, pr: null, aheadCount: 0 }), false);assert.deepEqual(items, [{id: "commit",@@ -627,10 +624,7 @@ describe("when: branch has no upstream configured", () => {});it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {- const items = buildMenuItems(- status({ hasUpstream: false, pr: null, aheadCount: 2 }),- false,- );+ const items = buildMenuItems(status({ hasUpstream: false, pr: null, aheadCount: 2 }), false);assert.deepEqual(items, [{id: "commit",diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.tsindex 86719e527..0aa8e9cd0 100644--- a/apps/web/src/components/GitActionsControl.logic.ts+++ b/apps/web/src/components/GitActionsControl.logic.ts@@ -123,12 +123,7 @@ export function buildMenuItems(const canCommit = !isBusy && hasChanges;const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;const canCreatePr =- !isBusy &&- hasBranch &&- !hasChanges &&- !hasOpenPr &&- gitStatus.aheadCount > 0 &&- !isBehind;+ !isBusy && hasBranch && !hasChanges && !hasOpenPr && gitStatus.aheadCount > 0 && !isBehind;const canOpenPr = !isBusy && hasOpenPr;return [diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsxindex 4f183e393..df4b18b23 100644--- a/apps/web/src/components/GitActionsControl.tsx+++ b/apps/web/src/components/GitActionsControl.tsx@@ -255,7 +255,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions}) => {const actionStatus = statusOverride ?? gitStatusForActions;const actionBranch = actionStatus?.branch ?? null;- const actionIsDefaultBranch = isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);+ const actionIsDefaultBranch =+ isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);const includesCommit =!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);if (@@ -331,7 +332,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsstopProgressUpdates();const resultToast = summarizeGitResult(result);- const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;+ const existingOpenPrUrl =+ actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;const prUrl = result.pr.url ?? existingOpenPrUrl;const shouldOfferPushCta = action === "commit" && result.commit.status === "created";const shouldOfferOpenPrCta =@@ -374,12 +376,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions},}: shouldOfferOpenPrCta- ? {- actionProps: {- children: "View PR",- onClick: () => {- const api = readNativeApi();- if (!api) return;+ ? {+ actionProps: {+ children: "View PR",+ onClick: () => {+ const api = readNativeApi();+ if (!api) return;closeResultToast();void api.shell.openExternal(prUrl);},@@ -424,7 +426,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsconst continuePendingDefaultBranchAction = useCallback(() => {if (!pendingDefaultBranchAction) return;- const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;+ const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =+ pendingDefaultBranchAction;setPendingDefaultBranchAction(null);void runGitActionWithToast({action,@@ -453,7 +456,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsconst checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {if (!pendingDefaultBranchAction) return;- const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;+ const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =+ pendingDefaultBranchAction;setPendingDefaultBranchAction(null);checkoutNewBranchAndRunAction({action,@@ -725,7 +729,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1"><span className="text-muted-foreground">Branch</span><span className="flex items-center justify-between gap-2">- <span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>+ <span className="font-medium">+ {gitStatusForActions?.branch ?? "(detached HEAD)"}+ </span>{isDefaultBranch && (<span className="text-right text-warning text-xs">Warning: default branch</span>)}diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsxindex d94d74c15..4e1a586d6 100644--- a/apps/web/src/components/Icons.tsx+++ b/apps/web/src/components/Icons.tsx@@ -74,10 +74,7 @@ export const VisualStudioCode: Icon = (props) => {filterUnits="userSpaceOnUse"><feFlood floodOpacity="0" result="BackgroundImageFix" />- <feColorMatrix- in="SourceAlpha"- values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"- />+ <feColorMatrix in="SourceAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" /><feOffset /><feGaussianBlur stdDeviation="4.167" /><feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />@@ -94,10 +91,7 @@ export const VisualStudioCode: Icon = (props) => {filterUnits="userSpaceOnUse"><feFlood floodOpacity="0" result="BackgroundImageFix" />- <feColorMatrix- in="SourceAlpha"- values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"- />+ <feColorMatrix in="SourceAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" /><feOffset /><feGaussianBlur stdDeviation="4.167" /><feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />@@ -185,28 +179,16 @@ export const Gemini: Icon = (props) => (<ellipse cx="19.5" cy="148.5" fill="#F6C013" rx="68.5" ry="72.5" /></g><g filter="url(#gemini__e)">- <path- fill="#FA4340"- d="M194 10.5C172 82.5 65.5 134.333 22.5 135L144-66l50 76.5Z"- />+ <path fill="#FA4340" d="M194 10.5C172 82.5 65.5 134.333 22.5 135L144-66l50 76.5Z" /></g><g filter="url(#gemini__f)">- <path- fill="#FA4340"- d="M190.5-12.5C168.5 59.5 62 111.333 19 112L140.5-89l50 76.5Z"- />+ <path fill="#FA4340" d="M190.5-12.5C168.5 59.5 62 111.333 19 112L140.5-89l50 76.5Z" /></g><g filter="url(#gemini__g)">- <path- fill="#14BB69"- d="M194.5 279.5C172.5 207.5 66 155.667 23 155l121.5 201 50-76.5Z"- />+ <path fill="#14BB69" d="M194.5 279.5C172.5 207.5 66 155.667 23 155l121.5 201 50-76.5Z" /></g><g filter="url(#gemini__h)">- <path- fill="#14BB69"- d="M196.5 320.5C174.5 248.5 68 196.667 25 196l121.5 201 50-76.5Z"- />+ <path fill="#14BB69" d="M196.5 320.5C174.5 248.5 68 196.667 25 196l121.5 201 50-76.5Z" /></g></g><defs>@@ -221,10 +203,7 @@ export const Gemini: Icon = (props) => (><feFlood floodOpacity="0" result="BackgroundImageFix" /><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />- <feGaussianBlur- result="effect1_foregroundBlur_69_17998"- stdDeviation="18"- />+ <feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="18" /></filter><filterid="gemini__c"@@ -237,10 +216,7 @@ export const Gemini: Icon = (props) => (><feFlood floodOpacity="0" result="BackgroundImageFix" /><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />- <feGaussianBlur- result="effect1_foregroundBlur_69_17998"- stdDeviation="32"- />+ <feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" /></filter><filterid="gemini__d"@@ -253,10 +229,7 @@ export const Gemini: Icon = (props) => (><feFlood floodOpacity="0" result="BackgroundImageFix" /><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />- <feGaussianBlur- result="effect1_foregroundBlur_69_17998"- stdDeviation="32"- />+ <feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" /></filter><filterid="gemini__e"@@ -269,10 +242,7 @@ export const Gemini: Icon = (props) => (><feFlood floodOpacity="0" result="BackgroundImageFix" /><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />- <feGaussianBlur- result="effect1_foregroundBlur_69_17998"- stdDeviation="32"- />+ <feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" /></filter><filterid="gemini__f"@@ -285,10 +255,7 @@ export const Gemini: Icon = (props) => (><feFlood floodOpacity="0" result="BackgroundImageFix" /><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />- <feGaussianBlur- result="effect1_foregroundBlur_69_17998"- stdDeviation="32"- />+ <feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" /></filter><filterid="gemini__g"@@ -301,10 +268,7 @@ export const Gemini: Icon = (props) => (><feFlood floodOpacity="0" result="BackgroundImageFix" /><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />- <feGaussianBlur- result="effect1_foregroundBlur_69_17998"- stdDeviation="32"- />+ <feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" /></filter><filterid="gemini__h"@@ -317,10 +281,7 @@ export const Gemini: Icon = (props) => (><feFlood floodOpacity="0" result="BackgroundImageFix" /><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />- <feGaussianBlur- result="effect1_foregroundBlur_69_17998"- stdDeviation="32"- />+ <feGaussianBlur result="effect1_foregroundBlur_69_17998" stdDeviation="32" /></filter></defs></svg>diff --git a/apps/web/src/components/PlanSidebar.tsx b/apps/web/src/components/PlanSidebar.tsxindex b2a9744f0..c465f3989 100644--- a/apps/web/src/components/PlanSidebar.tsx+++ b/apps/web/src/components/PlanSidebar.tsx@@ -106,8 +106,7 @@ const PlanSidebar = memo(function PlanSidebar({toastManager.add({type: "error",title: "Could not save plan",- description:- error instanceof Error ? error.message : "An error occurred.",+ description: error instanceof Error ? error.message : "An error occurred.",});}).then(@@ -199,9 +198,7 @@ const PlanSidebar = memo(function PlanSidebar({step.status === "completed" && "bg-emerald-500/5",)}>- <div className="mt-0.5">- {stepStatusIcon(step.status)}- </div>+ <div className="mt-0.5">{stepStatusIcon(step.status)}</div><pclassName={cn("text-[13px] leading-snug",@@ -251,9 +248,7 @@ const PlanSidebar = memo(function PlanSidebar({{/* Empty state */}{!activePlan && !planMarkdown ? (<div className="flex flex-col items-center justify-center py-12 text-center">- <p className="text-[13px] text-muted-foreground/40">- No active plan yet.- </p>+ <p className="text-[13px] text-muted-foreground/40">No active plan yet.</p><p className="mt-1 text-[11px] text-muted-foreground/30">Plans will appear here when generated.</p>diff --git a/apps/web/src/components/PullRequestThreadDialog.tsx b/apps/web/src/components/PullRequestThreadDialog.tsxindex ced24aca7..8b1ed5122 100644--- a/apps/web/src/components/PullRequestThreadDialog.tsx+++ b/apps/web/src/components/PullRequestThreadDialog.tsx@@ -116,56 +116,58 @@ export function PullRequestThreadDialog({}}, [resolvedPullRequest?.state]);- const handleConfirm = useCallback(async (mode: "local" | "worktree") => {- if (!parsedReference) {- setReferenceDirty(true);- return;- }- if (!parsedReference || !resolvedPullRequest || !cwd) {- return;- }- setPreparingMode(mode);- try {- const result = await preparePullRequestThreadMutation.mutateAsync({- reference: parsedReference,- mode,- });- await onPrepared({- branch: result.branch,- worktreePath: result.worktreePath,- });- onOpenChange(false);- } finally {- setPreparingMode(null);- }- }, [- cwd,- onOpenChange,- onPrepared,- parsedReference,- preparePullRequestThreadMutation,- resolvedPullRequest,- ]);+ const handleConfirm = useCallback(+ async (mode: "local" | "worktree") => {+ if (!parsedReference) {+ setReferenceDirty(true);+ return;+ }+ if (!parsedReference || !resolvedPullRequest || !cwd) {+ return;+ }+ setPreparingMode(mode);+ try {+ const result = await preparePullRequestThreadMutation.mutateAsync({+ reference: parsedReference,+ mode,+ });+ await onPrepared({+ branch: result.branch,+ worktreePath: result.worktreePath,+ });+ onOpenChange(false);+ } finally {+ setPreparingMode(null);+ }+ },+ [+ cwd,+ onOpenChange,+ onPrepared,+ parsedReference,+ preparePullRequestThreadMutation,+ resolvedPullRequest,+ ],+ );- const validationMessage =- !referenceDirty- ? null- : reference.trim().length === 0- ? "Paste a GitHub pull request URL or enter 123 / #123."- : parsedReference === null- ? "Use a GitHub pull request URL, 123, or #123."- : null;+ const validationMessage = !referenceDirty+ ? null+ : reference.trim().length === 0+ ? "Paste a GitHub pull request URL or enter 123 / #123."+ : parsedReference === null+ ? "Use a GitHub pull request URL, 123, or #123."+ : null;const errorMessage =validationMessage ??(resolvedPullRequest === null && resolvePullRequestQuery.isError- ? (resolvePullRequestQuery.error instanceof Error- ? resolvePullRequestQuery.error.message- : "Failed to resolve pull request.")- : (preparePullRequestThreadMutation.error instanceof Error- ? preparePullRequestThreadMutation.error.message- : preparePullRequestThreadMutation.error- ? "Failed to prepare pull request thread."- : null));+ ? resolvePullRequestQuery.error instanceof Error+ ? resolvePullRequestQuery.error.message+ : "Failed to resolve pull request."+ : preparePullRequestThreadMutation.error instanceof Error+ ? preparePullRequestThreadMutation.error.message+ : preparePullRequestThreadMutation.error+ ? "Failed to prepare pull request thread."+ : null);return (<Dialogdiff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 379d7b60e..f1afa0f64 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -1,8 +1,7 @@import type { Thread } from "../types";import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";-export const THREAD_SELECTION_SAFE_SELECTOR =- "[data-thread-item], [data-thread-selection-safe]";+export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";export interface ThreadStatusPill {label:diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 88e9d674b..6a07a667a 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -83,10 +83,7 @@ import {import { useThreadSelectionStore } from "../threadSelectionStore";import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";import { isNonEmpty as isNonEmptyString } from "effect/String";-import {- resolveThreadStatusPill,- shouldClearThreadSelectionOnMouseDown,-} from "./Sidebar.logic";+import { resolveThreadStatusPill, shouldClearThreadSelectionOnMouseDown } from "./Sidebar.logic";const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];const THREAD_PREVIEW_LIMIT = 6;@@ -897,7 +894,14 @@ export default function Sidebar() {params: { threadId },});},- [clearSelection, navigate, rangeSelectTo, selectedThreadIds.size, setSelectionAnchor, toggleThreadSelection],+ [+ clearSelection,+ navigate,+ rangeSelectTo,+ selectedThreadIds.size,+ setSelectionAnchor,+ toggleThreadSelection,+ ],);const handleProjectContextMenu = useCallback(@@ -1077,7 +1081,16 @@ export default function Sidebar() {window.removeEventListener("keydown", onWindowKeyDown);window.removeEventListener("mousedown", onMouseDown);};- }, [clearSelection, getDraftThread, handleNewThread, keybindings, projects, routeThreadId, selectedThreadIds.size, threads]);+ }, [+ clearSelection,+ getDraftThread,+ handleNewThread,+ keybindings,+ projects,+ routeThreadId,+ selectedThreadIds.size,+ threads,+ ]);useEffect(() => {if (!isElectron) return;@@ -1403,7 +1416,8 @@ export default function Sidebar() {const projectThreads = threads.filter((thread) => thread.projectId === project.id).toSorted((a, b) => {- const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();+ const byDate =+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();if (byDate !== 0) return byDate;return b.id.localeCompare(a.id);});@@ -1418,10 +1432,7 @@ export default function Sidebar() {return (<SortableProjectItem key={project.id} projectId={project.id}>{(dragHandleProps) => (- <Collapsible- className="group/collapsible"- open={project.expanded}- >+ <Collapsible className="group/collapsible" open={project.expanded}><div className="group/project-header relative"><SidebarMenuButtonsize="sm"@@ -1481,193 +1492,222 @@ export default function Sidebar() {<CollapsibleContent keepMounted><SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0.5 px-1.5 py-0">- {visibleThreads.map((thread) => {- const isActive = routeThreadId === thread.id;- const isSelected = selectedThreadIds.has(thread.id);- const isHighlighted = isActive || isSelected;- const threadStatus = resolveThreadStatusPill({- thread,- hasPendingApprovals: pendingApprovalByThreadId.get(thread.id) === true,- hasPendingUserInput: pendingUserInputByThreadId.get(thread.id) === true,- });- const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);- const terminalStatus = terminalStatusFromRunningIds(- selectThreadTerminalState(terminalStateByThreadId, thread.id)- .runningTerminalIds,- );-- return (- <SidebarMenuSubItem key={thread.id} className="w-full" data-thread-item>- <SidebarMenuSubButton- render={<div role="button" tabIndex={0} />}- size="sm"- isActive={isActive}- className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none hover:bg-accent hover:text-foreground focus-visible:ring-0 ${- isSelected- ? "bg-primary/15 text-foreground dark:bg-primary/10"- : isActive- ? "bg-accent/85 text-foreground font-medium dark:bg-accent/55"- : "text-muted-foreground"- }`}- onClick={(event) => {- handleThreadClick(event, thread.id, orderedProjectThreadIds);- }}- onKeyDown={(event) => {- if (event.key !== "Enter" && event.key !== " ") return;- event.preventDefault();+ {visibleThreads.map((thread) => {+ const isActive = routeThreadId === thread.id;+ const isSelected = selectedThreadIds.has(thread.id);+ const isHighlighted = isActive || isSelected;+ const threadStatus = resolveThreadStatusPill({+ thread,+ hasPendingApprovals:+ pendingApprovalByThreadId.get(thread.id) === true,+ hasPendingUserInput:+ pendingUserInputByThreadId.get(thread.id) === true,+ });+ const prStatus = prStatusIndicator(+ prByThreadId.get(thread.id) ?? null,+ );+ const terminalStatus = terminalStatusFromRunningIds(+ selectThreadTerminalState(terminalStateByThreadId, thread.id)+ .runningTerminalIds,+ );++ return (+ <SidebarMenuSubItem+ key={thread.id}+ className="w-full"+ data-thread-item+ >+ <SidebarMenuSubButton+ render={<div role="button" tabIndex={0} />}+ size="sm"+ isActive={isActive}+ className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none hover:bg-accent hover:text-foreground focus-visible:ring-0 ${+ isSelected+ ? "bg-primary/15 text-foreground dark:bg-primary/10"+ : isActive+ ? "bg-accent/85 text-foreground font-medium dark:bg-accent/55"+ : "text-muted-foreground"+ }`}+ onClick={(event) => {+ handleThreadClick(+ event,+ thread.id,+ orderedProjectThreadIds,+ );+ }}+ onKeyDown={(event) => {+ if (event.key !== "Enter" && event.key !== " ") return;+ event.preventDefault();+ if (selectedThreadIds.size > 0) {+ clearSelection();+ }+ setSelectionAnchor(thread.id);+ void navigate({+ to: "/$threadId",+ params: { threadId: thread.id },+ });+ }}+ onContextMenu={(event) => {+ event.preventDefault();+ if (+ selectedThreadIds.size > 0 &&+ selectedThreadIds.has(thread.id)+ ) {+ void handleMultiSelectContextMenu({+ x: event.clientX,+ y: event.clientY,+ });+ } else {if (selectedThreadIds.size > 0) {clearSelection();}- setSelectionAnchor(thread.id);- void navigate({- to: "/$threadId",- params: { threadId: thread.id },+ void handleThreadContextMenu(thread.id, {+ x: event.clientX,+ y: event.clientY,});- }}- onContextMenu={(event) => {- event.preventDefault();- if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {- void handleMultiSelectContextMenu({- x: event.clientX,- y: event.clientY,- });- } else {- if (selectedThreadIds.size > 0) {- clearSelection();- }- void handleThreadContextMenu(thread.id, {- x: event.clientX,- y: event.clientY,- });- }- }}- >- <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">- {prStatus && (- <Tooltip>- <TooltipTrigger- render={- <button- type="button"- aria-label={prStatus.tooltip}- className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}- onClick={(event) => {- openPrLink(event, prStatus.url);- }}- >- <GitPullRequestIcon className="size-3" />- </button>- }- />- <TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>- </Tooltip>- )}- {threadStatus && (- <span- className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}- >- <span- className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${- threadStatus.pulse ? "animate-pulse" : ""- }`}- />- <span className="hidden md:inline">{threadStatus.label}</span>- </span>- )}- {renamingThreadId === thread.id ? (- <input- ref={(el) => {- if (el && renamingInputRef.current !== el) {- renamingInputRef.current = el;- el.focus();- el.select();- }- }}- className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"- value={renamingTitle}- onChange={(e) => setRenamingTitle(e.target.value)}- onKeyDown={(e) => {- e.stopPropagation();- if (e.key === "Enter") {- e.preventDefault();- renamingCommittedRef.current = true;- void commitRename(thread.id, renamingTitle, thread.title);- } else if (e.key === "Escape") {- e.preventDefault();- renamingCommittedRef.current = true;- cancelRename();- }- }}- onBlur={() => {- if (!renamingCommittedRef.current) {- void commitRename(thread.id, renamingTitle, thread.title);- }- }}- onClick={(e) => e.stopPropagation()}+ }+ }}+ >+ <div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">+ {prStatus && (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ aria-label={prStatus.tooltip}+ className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}+ onClick={(event) => {+ openPrLink(event, prStatus.url);+ }}+ >+ <GitPullRequestIcon className="size-3" />+ </button>+ }/>- ) : (- <span className="min-w-0 flex-1 truncate text-xs">- {thread.title}- </span>- )}- </div>- <div className="ml-auto flex shrink-0 items-center gap-1.5">- {terminalStatus && (+ <TooltipPopup side="top">+ {prStatus.tooltip}+ </TooltipPopup>+ </Tooltip>+ )}+ {threadStatus && (+ <span+ className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}+ ><span- role="img"- aria-label={terminalStatus.label}- title={terminalStatus.label}- className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}- >- <TerminalIcon- className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}- />+ className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${+ threadStatus.pulse ? "animate-pulse" : ""+ }`}+ />+ <span className="hidden md:inline">+ {threadStatus.label}</span>- )}+ </span>+ )}+ {renamingThreadId === thread.id ? (+ <input+ ref={(el) => {+ if (el && renamingInputRef.current !== el) {+ renamingInputRef.current = el;+ el.focus();+ el.select();+ }+ }}+ className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"+ value={renamingTitle}+ onChange={(e) => setRenamingTitle(e.target.value)}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter") {+ e.preventDefault();+ renamingCommittedRef.current = true;+ void commitRename(+ thread.id,+ renamingTitle,+ thread.title,+ );+ } else if (e.key === "Escape") {+ e.preventDefault();+ renamingCommittedRef.current = true;+ cancelRename();+ }+ }}+ onBlur={() => {+ if (!renamingCommittedRef.current) {+ void commitRename(+ thread.id,+ renamingTitle,+ thread.title,+ );+ }+ }}+ onClick={(e) => e.stopPropagation()}+ />+ ) : (+ <span className="min-w-0 flex-1 truncate text-xs">+ {thread.title}+ </span>+ )}+ </div>+ <div className="ml-auto flex shrink-0 items-center gap-1.5">+ {terminalStatus && (<span- className={`text-[10px] ${- isHighlighted ? "text-foreground/65" : "text-muted-foreground/40"- }`}+ role="img"+ aria-label={terminalStatus.label}+ title={terminalStatus.label}+ className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}>- {formatRelativeTime(thread.createdAt)}+ <TerminalIcon+ className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}+ /></span>- </div>- </SidebarMenuSubButton>- </SidebarMenuSubItem>- );- })}-- {hasHiddenThreads && !isThreadListExpanded && (- <SidebarMenuSubItem className="w-full">- <SidebarMenuSubButton- render={<button type="button" />}- data-thread-selection-safe- size="sm"- className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"- onClick={() => {- expandThreadListForProject(project.id);- }}- >- <span>Show more</span>+ )}+ <span+ className={`text-[10px] ${+ isHighlighted+ ? "text-foreground/65"+ : "text-muted-foreground/40"+ }`}+ >+ {formatRelativeTime(thread.createdAt)}+ </span>+ </div></SidebarMenuSubButton></SidebarMenuSubItem>- )}- {hasHiddenThreads && isThreadListExpanded && (- <SidebarMenuSubItem className="w-full">- <SidebarMenuSubButton- render={<button type="button" />}- data-thread-selection-safe- size="sm"- className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"- onClick={() => {- collapseThreadListForProject(project.id);- }}- >- <span>Show less</span>- </SidebarMenuSubButton>- </SidebarMenuSubItem>- )}- </SidebarMenuSub>+ );+ })}++ {hasHiddenThreads && !isThreadListExpanded && (+ <SidebarMenuSubItem className="w-full">+ <SidebarMenuSubButton+ render={<button type="button" />}+ data-thread-selection-safe+ size="sm"+ className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"+ onClick={() => {+ expandThreadListForProject(project.id);+ }}+ >+ <span>Show more</span>+ </SidebarMenuSubButton>+ </SidebarMenuSubItem>+ )}+ {hasHiddenThreads && isThreadListExpanded && (+ <SidebarMenuSubItem className="w-full">+ <SidebarMenuSubButton+ render={<button type="button" />}+ data-thread-selection-safe+ size="sm"+ className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"+ onClick={() => {+ collapseThreadListForProject(project.id);+ }}+ >+ <span>Show less</span>+ </SidebarMenuSubButton>+ </SidebarMenuSubItem>+ )}+ </SidebarMenuSub></CollapsibleContent></Collapsible>)}diff --git a/apps/web/src/components/composerFooterLayout.test.ts b/apps/web/src/components/composerFooterLayout.test.tsindex d5325f5bd..717e2623d 100644--- a/apps/web/src/components/composerFooterLayout.test.ts+++ b/apps/web/src/components/composerFooterLayout.test.ts@@ -17,9 +17,7 @@ describe("shouldUseCompactComposerFooter", () => {it("stays expanded at and above the breakpoint", () => {expect(shouldUseCompactComposerFooter(COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX)).toBe(false);- expect(shouldUseCompactComposerFooter(COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX + 48)).toBe(- false,- );+ expect(shouldUseCompactComposerFooter(COMPOSER_FOOTER_COMPACT_BREAKPOINT_PX + 48)).toBe(false);});it("uses a higher breakpoint for wide action states", () => {diff --git a/apps/web/src/components/desktopUpdate.logic.test.ts b/apps/web/src/components/desktopUpdate.logic.test.tsindex 7fd362bf1..984eebd6b 100644--- a/apps/web/src/components/desktopUpdate.logic.test.ts+++ b/apps/web/src/components/desktopUpdate.logic.test.ts@@ -31,7 +31,11 @@ const baseState: DesktopUpdateState = {describe("desktop update button state", () => {it("shows a download action when an update is available", () => {- const state: DesktopUpdateState = { ...baseState, status: "available", availableVersion: "1.1.0" };+ const state: DesktopUpdateState = {+ ...baseState,+ status: "available",+ availableVersion: "1.1.0",+ };expect(shouldShowDesktopUpdateButton(state)).toBe(true);expect(resolveDesktopUpdateButtonAction(state)).toBe("download");});diff --git a/apps/web/src/components/ui/scroll-area.tsx b/apps/web/src/components/ui/scroll-area.tsxindex f8d2670b2..50deb1ba8 100644--- a/apps/web/src/components/ui/scroll-area.tsx+++ b/apps/web/src/components/ui/scroll-area.tsx@@ -24,7 +24,8 @@ function ScrollArea({scrollFade &&"mask-t-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-start)))] mask-b-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-y-end)))] mask-l-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-start)))] mask-r-from-[calc(100%-min(var(--fade-size),var(--scroll-area-overflow-x-end)))] [--fade-size:1.5rem]",scrollbarGutter && "data-has-overflow-y:pe-2.5 data-has-overflow-x:pb-2.5",- hideScrollbars && "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",+ hideScrollbars &&+ "[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",)}data-slot="scroll-area-viewport">diff --git a/apps/web/src/components/ui/toast.logic.test.ts b/apps/web/src/components/ui/toast.logic.test.tsindex c0a5f79f7..4e4595f73 100644--- a/apps/web/src/components/ui/toast.logic.test.ts+++ b/apps/web/src/components/ui/toast.logic.test.ts@@ -17,7 +17,11 @@ describe("shouldHideCollapsedToastContent", () => {describe("buildVisibleToastLayout", () => {it("computes indices and offsets from the visible subset", () => {- const visibleToasts = [{ id: "a", height: 48 }, { id: "b", height: 72 }, { id: "c", height: 24 }];+ const visibleToasts = [+ { id: "a", height: 48 },+ { id: "b", height: 72 },+ { id: "c", height: 24 },+ ];const layout = buildVisibleToastLayout(visibleToasts);@@ -37,7 +41,11 @@ describe("buildVisibleToastLayout", () => {});it("treats missing heights as zero", () => {- const layout = buildVisibleToastLayout([{ id: "a" }, { id: "b", height: undefined }, { id: "c", height: 30 }]);+ const layout = buildVisibleToastLayout([+ { id: "a" },+ { id: "b", height: undefined },+ { id: "c", height: 30 },+ ]);assert.equal(layout.frontmostHeight, 0);assert.deepEqual(diff --git a/apps/web/src/composer-logic.ts b/apps/web/src/composer-logic.tsindex 9bb30132a..70b3567c3 100644--- a/apps/web/src/composer-logic.ts+++ b/apps/web/src/composer-logic.ts@@ -10,11 +10,7 @@ export interface ComposerTrigger {rangeEnd: number;}-const SLASH_COMMANDS: readonly ComposerSlashCommand[] = [- "model",- "plan",- "default",-];+const SLASH_COMMANDS: readonly ComposerSlashCommand[] = ["model", "plan", "default"];function clampCursor(text: string, cursor: number): number {if (!Number.isFinite(cursor)) return text.length;@@ -65,7 +61,9 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)return expandedCursor;}-function collapsedSegmentLength(segment: { type: "text"; text: string } | { type: "mention" }): number {+function collapsedSegmentLength(+ segment: { type: "text"; text: string } | { type: "mention" },+): number {return segment.type === "mention" ? 1 : segment.text.length;}@@ -164,10 +162,9 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos};}-export function parseStandaloneComposerSlashCommand(text: string): Exclude<- ComposerSlashCommand,- "model"-> | null {+export function parseStandaloneComposerSlashCommand(+ text: string,+): Exclude<ComposerSlashCommand, "model"> | null {const match = /^\/(plan|default)\s*$/i.exec(text.trim());if (!match) {return null;diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.tsindex 2bcd9cbbc..927a16060 100644--- a/apps/web/src/composerDraftStore.test.ts+++ b/apps/web/src/composerDraftStore.test.ts@@ -252,9 +252,9 @@ describe("composerDraftStore project draft thread mapping", () => {store.clearProjectDraftThreadId(projectId);expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();- expect(useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId).toBe(- threadId,- );+ expect(+ useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId,+ ).toBe(threadId);expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");});@@ -380,7 +380,9 @@ describe("composerDraftStore setModel", () => {store.setModel(threadId, "gpt-5.3-codex");- expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe("gpt-5.3-codex");+ expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe(+ "gpt-5.3-codex",+ );});});diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.tsindex 0369b9773..1902aa6c8 100644--- a/apps/web/src/composerDraftStore.ts+++ b/apps/web/src/composerDraftStore.ts@@ -9,11 +9,7 @@ import {type RuntimeMode,} from "@t3tools/contracts";import { normalizeModelSlug } from "@t3tools/shared/model";-import {- DEFAULT_INTERACTION_MODE,- DEFAULT_RUNTIME_MODE,- type ChatImageAttachment,-} from "./types";+import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";import { Debouncer } from "@tanstack/react-pacer";import { create } from "zustand";import { createJSONStorage, persist, type StateStorage } from "zustand/middleware";@@ -495,8 +491,7 @@ function hydreatePersistedComposerImageAttachment(attachment: PersistedComposerImageAttachment,): File | null {const commaIndex = attachment.dataUrl.indexOf(",");- const header =- commaIndex === -1 ? attachment.dataUrl : attachment.dataUrl.slice(0, commaIndex);+ const header = commaIndex === -1 ? attachment.dataUrl : attachment.dataUrl.slice(0, commaIndex);const payload = commaIndex === -1 ? "" : attachment.dataUrl.slice(commaIndex + 1);if (payload.length === 0) {return null;@@ -605,7 +600,8 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(const nextDraftThread: DraftThreadState = {projectId,createdAt: options?.createdAt ?? existingThread?.createdAt ?? new Date().toISOString(),- runtimeMode: options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,+ runtimeMode:+ options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,interactionMode:options?.interactionMode ??existingThread?.interactionMode ??@@ -673,7 +669,9 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(return state;}const nextWorktreePath =- options.worktreePath === undefined ? existing.worktreePath : (options.worktreePath ?? null);+ options.worktreePath === undefined+ ? existing.worktreePath+ : (options.worktreePath ?? null);const nextDraftThread: DraftThreadState = {projectId: nextProjectId,createdAt:@@ -685,8 +683,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(branch: options.branch === undefined ? existing.branch : (options.branch ?? null),worktreePath: nextWorktreePath,envMode:- options.envMode ??- (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),+ options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),};const isUnchanged =nextDraftThread.projectId === existing.projectId &&diff --git a/apps/web/src/lib/gitReactQuery.ts b/apps/web/src/lib/gitReactQuery.tsindex b574c9364..fe0c4705b 100644--- a/apps/web/src/lib/gitReactQuery.ts+++ b/apps/web/src/lib/gitReactQuery.ts@@ -196,13 +196,7 @@ export function gitPreparePullRequestThreadMutationOptions(input: {queryClient: QueryClient;}) {return mutationOptions({- mutationFn: async ({- reference,- mode,- }: {- reference: string;- mode: "local" | "worktree";- }) => {+ mutationFn: async ({ reference, mode }: { reference: string; mode: "local" | "worktree" }) => {const api = ensureNativeApi();if (!input.cwd) throw new Error("Pull request thread preparation is unavailable.");return api.git.preparePullRequestThread({diff --git a/apps/web/src/lib/turnDiffTree.test.ts b/apps/web/src/lib/turnDiffTree.test.tsindex 5778dca3a..6389fc3ee 100644--- a/apps/web/src/lib/turnDiffTree.test.ts+++ b/apps/web/src/lib/turnDiffTree.test.ts@@ -91,7 +91,9 @@ describe("buildTurnDiffTree", () => {});it("normalizes file paths with windows separators", () => {- const tree = buildTurnDiffTree([{ path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 }]);+ const tree = buildTurnDiffTree([+ { path: "apps\\web\\src\\index.ts", additions: 2, deletions: 1 },+ ]);expect(tree).toEqual([{@@ -157,7 +159,8 @@ describe("buildTurnDiffTree", () => {expect(tree).toHaveLength(2);const directoryNodes = tree.filter(- (node): node is Extract<(typeof tree)[number], { kind: "directory" }> => node.kind === "directory",+ (node): node is Extract<(typeof tree)[number], { kind: "directory" }> =>+ node.kind === "directory",);expect(directoryNodes.map((node) => node.name).toSorted()).toEqual([" a", "a"]);expect(directoryNodes.map((node) => node.path).toSorted()).toEqual([" a", "a"]);diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.tsindex dd592bd62..86e41285a 100644--- a/apps/web/src/pendingUserInput.ts+++ b/apps/web/src/pendingUserInput.ts@@ -95,9 +95,7 @@ export function derivePendingUserInputProgress(questionIndex: number,): PendingUserInputProgress {const normalizedQuestionIndex =- questions.length === 0- ? 0- : Math.max(0, Math.min(questionIndex, questions.length - 1));+ questions.length === 0 ? 0 : Math.max(0, Math.min(questionIndex, questions.length - 1));const activeQuestion = questions[normalizedQuestionIndex] ?? null;const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;const resolvedAnswer = resolvePendingUserInputAnswer(activeDraft);diff --git a/apps/web/src/proposedPlan.test.ts b/apps/web/src/proposedPlan.test.tsindex e5e917bd4..63f95d413 100644--- a/apps/web/src/proposedPlan.test.ts+++ b/apps/web/src/proposedPlan.test.ts@@ -31,9 +31,12 @@ describe("buildPlanImplementationPrompt", () => {describe("buildCollapsedProposedPlanPreviewMarkdown", () => {it("drops the redundant title heading and preserves the following markdown lines", () => {expect(- buildCollapsedProposedPlanPreviewMarkdown("# Integrate RPC\n\n## Summary\n\n- step 1\n- step 2", {- maxLines: 4,- }),+ buildCollapsedProposedPlanPreviewMarkdown(+ "# Integrate RPC\n\n## Summary\n\n- step 1\n- step 2",+ {+ maxLines: 4,+ },+ ),).toBe("- step 1\n- step 2");});diff --git a/apps/web/src/proposedPlan.ts b/apps/web/src/proposedPlan.tsindex 8a5f18b6f..48186392e 100644--- a/apps/web/src/proposedPlan.ts+++ b/apps/web/src/proposedPlan.ts@@ -5,8 +5,7 @@ export function proposedPlanTitle(planMarkdown: string): string | null {export function stripDisplayedPlanMarkdown(planMarkdown: string): string {const lines = planMarkdown.trimEnd().split(/\r?\n/);- const sourceLines =- lines[0] && /^\s{0,3}#{1,6}\s+/.test(lines[0]) ? lines.slice(1) : [...lines];+ const sourceLines = lines[0] && /^\s{0,3}#{1,6}\s+/.test(lines[0]) ? lines.slice(1) : [...lines];while (sourceLines[0]?.trim().length === 0) {sourceLines.shift();}@@ -75,10 +74,7 @@ export function buildPlanImplementationPrompt(planMarkdown: string): string {return `PLEASE IMPLEMENT THIS PLAN:\n${planMarkdown.trim()}`;}-export function resolvePlanFollowUpSubmission(input: {- draftText: string;- planMarkdown: string;-}): {+export function resolvePlanFollowUpSubmission(input: { draftText: string; planMarkdown: string }): {text: string;interactionMode: "default" | "plan";} {diff --git a/apps/web/src/pullRequestReference.test.ts b/apps/web/src/pullRequestReference.test.tsindex 7b1c27701..60bb7b12f 100644--- a/apps/web/src/pullRequestReference.test.ts+++ b/apps/web/src/pullRequestReference.test.ts@@ -4,9 +4,9 @@ import { parsePullRequestReference } from "./pullRequestReference";describe("parsePullRequestReference", () => {it("accepts GitHub pull request URLs", () => {- expect(- parsePullRequestReference("https://github.com/pingdotgg/t3code/pull/42"),- ).toBe("https://github.com/pingdotgg/t3code/pull/42");+ expect(parsePullRequestReference("https://github.com/pingdotgg/t3code/pull/42")).toBe(+ "https://github.com/pingdotgg/t3code/pull/42",+ );});it("accepts raw numbers", () => {diff --git a/apps/web/src/routes/_chat.$threadId.tsx b/apps/web/src/routes/_chat.$threadId.tsxindex ccd200277..57b8ad43b 100644--- a/apps/web/src/routes/_chat.$threadId.tsx+++ b/apps/web/src/routes/_chat.$threadId.tsx@@ -92,7 +92,9 @@ const DiffPanelInlineSidebar = (props: {composerViewport.clientWidth - viewportPaddingLeft - viewportPaddingRight,);const formRect = composerForm.getBoundingClientRect();- const composerFooter = composerForm.querySelector<HTMLElement>("[data-chat-composer-footer='true']");+ const composerFooter = composerForm.querySelector<HTMLElement>(+ "[data-chat-composer-footer='true']",+ );const composerRightActions = composerForm.querySelector<HTMLElement>("[data-chat-composer-actions='right']",);@@ -103,9 +105,7 @@ const DiffPanelInlineSidebar = (props: {0: 0;const minimumComposerWidth =- COMPOSER_COMPACT_MIN_LEFT_CONTROLS_WIDTH_PX +- composerRightActionsWidth +- composerFooterGap;+ COMPOSER_COMPACT_MIN_LEFT_CONTROLS_WIDTH_PX + composerRightActionsWidth + composerFooterGap;const hasComposerOverflow = composerForm.scrollWidth > composerForm.clientWidth + 0.5;const overflowsViewport = formRect.width > viewportContentWidth + 0.5;const violatesMinimumComposerWidth = composerForm.clientWidth + 0.5 < minimumComposerWidth;@@ -156,8 +156,8 @@ function ChatThreadRouteView() {});const search = Route.useSearch();const threadExists = useStore((store) => store.threads.some((thread) => thread.id === threadId));- const draftThreadExists = useComposerDraftStore(- (store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),+ const draftThreadExists = useComposerDraftStore((store) =>+ Object.hasOwn(store.draftThreadsByThreadId, threadId),);const routeThreadExists = threadExists || draftThreadExists;const diffOpen = search.diff === "1";diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsxindex 8dfeb210f..024553022 100644--- a/apps/web/src/routes/_chat.settings.tsx+++ b/apps/web/src/routes/_chat.settings.tsx@@ -115,54 +115,62 @@ function SettingsRouteView() {});}, [keybindingsConfigPath]);- const addCustomModel = useCallback((provider: ProviderKind) => {- const customModelInput = customModelInputByProvider[provider];- const customModels = getCustomModelsForProvider(settings, provider);- const normalized = normalizeModelSlug(customModelInput, provider);- if (!normalized) {- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: "Enter a model slug.",- }));- return;- }- if (getModelOptions(provider).some((option) => option.slug === normalized)) {- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: "That model is already built in.",- }));- return;- }- if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {- setCustomModelErrorByProvider((existing) => ({+ const addCustomModel = useCallback(+ (provider: ProviderKind) => {+ const customModelInput = customModelInputByProvider[provider];+ const customModels = getCustomModelsForProvider(settings, provider);+ const normalized = normalizeModelSlug(customModelInput, provider);+ if (!normalized) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: "Enter a model slug.",+ }));+ return;+ }+ if (getModelOptions(provider).some((option) => option.slug === normalized)) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: "That model is already built in.",+ }));+ return;+ }+ if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: `Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`,+ }));+ return;+ }+ if (customModels.includes(normalized)) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: "That custom model is already saved.",+ }));+ return;+ }++ updateSettings(patchCustomModels(provider, [...customModels, normalized]));+ setCustomModelInputByProvider((existing) => ({...existing,- [provider]: `Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`,+ [provider]: "",}));- return;- }- if (customModels.includes(normalized)) {setCustomModelErrorByProvider((existing) => ({...existing,- [provider]: "That custom model is already saved.",+ [provider]: null,}));- return;- }-- updateSettings(patchCustomModels(provider, [...customModels, normalized]));- setCustomModelInputByProvider((existing) => ({- ...existing,- [provider]: "",- }));- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: null,- }));- }, [customModelInputByProvider, settings, updateSettings]);+ },+ [customModelInputByProvider, settings, updateSettings],+ );const removeCustomModel = useCallback((provider: ProviderKind, slug: string) => {const customModels = getCustomModelsForProvider(settings, provider);- updateSettings(patchCustomModels(provider, customModels.filter((model) => model !== slug)));+ updateSettings(+ patchCustomModels(+ provider,+ customModels.filter((model) => model !== slug),+ ),+ );setCustomModelErrorByProvider((existing) => ({...existing,[provider]: null,@@ -381,10 +389,9 @@ function SettingsRouteView() {variant="outline"onClick={() =>updateSettings(- patchCustomModels(- provider,- [...getDefaultCustomModelsForProvider(defaults, provider)],- ),+ patchCustomModels(provider, [+ ...getDefaultCustomModelsForProvider(defaults, provider),+ ]),)}>diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex e9351ca2b..aa8f3ffc3 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -8,7 +8,13 @@ import {type TurnId,} from "@t3tools/contracts";-import type { ChatMessage, ProposedPlan, SessionPhase, ThreadSession, TurnDiffSummary } from "./types";+import type {+ ChatMessage,+ ProposedPlan,+ SessionPhase,+ ThreadSession,+ TurnDiffSummary,+} from "./types";export type ProviderPickerKind = ProviderKind | "claudeCode" | "cursor";@@ -138,9 +144,7 @@ export function deriveActiveWorkStartedAt(return sendStartedAt;}-function requestKindFromRequestType(- requestType: unknown,-): PendingApproval["requestKind"] | null {+function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {switch (requestType) {case "command_execution_approval":case "exec_command_approval":@@ -333,9 +337,7 @@ export function deriveActivePlanState(return null;}const status =- record.status === "completed" || record.status === "inProgress"- ? record.status- : "pending";+ record.status === "completed" || record.status === "inProgress" ? record.status : "pending";return {step: record.step,status,@@ -355,7 +357,9 @@ export function deriveActivePlanState(return {createdAt: latest.createdAt,turnId: latest.turnId,- ...(payload && "explanation" in payload ? { explanation: payload.explanation as string | null } : {}),+ ...(payload && "explanation" in payload+ ? { explanation: payload.explanation as string | null }+ : {}),steps,};}@@ -487,12 +491,7 @@ function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {target.push(normalized);}-function collectChangedFiles(- value: unknown,- target: string[],- seen: Set<string>,- depth: number,-) {+function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {if (depth > 4 || target.length >= 12) {return;}diff --git a/apps/web/src/store.ts b/apps/web/src/store.tsindex 0dbd025aa..faebe4b0f 100644--- a/apps/web/src/store.ts+++ b/apps/web/src/store.ts@@ -124,7 +124,9 @@ function mapProjectsFromReadModel(const previousById = new Map(previous.map((project) => [project.id, project] as const));const previousByCwd = new Map(previous.map((project) => [project.cwd, project] as const));const previousOrderById = new Map(previous.map((project, index) => [project.id, index] as const));- const previousOrderByCwd = new Map(previous.map((project, index) => [project.cwd, index] as const));+ const previousOrderByCwd = new Map(+ previous.map((project, index) => [project.cwd, index] as const),+ );const persistedOrderByCwd = new Map(persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const),);@@ -150,7 +152,8 @@ function mapProjectsFromReadModel(return mappedProjects.map((project, incomingIndex) => {- const previousIndex = previousOrderById.get(project.id) ?? previousOrderByCwd.get(project.cwd);+ const previousIndex =+ previousOrderById.get(project.id) ?? previousOrderByCwd.get(project.cwd);const persistedIndex = usePersistedOrder ? persistedOrderByCwd.get(project.cwd) : undefined;const orderIndex =previousIndex ??diff --git a/apps/web/src/terminalStateStore.test.ts b/apps/web/src/terminalStateStore.test.tsindex f91a40139..1f48b1693 100644--- a/apps/web/src/terminalStateStore.test.ts+++ b/apps/web/src/terminalStateStore.test.ts@@ -14,7 +14,10 @@ describe("terminalStateStore actions", () => {});it("returns a closed default terminal state for unknown threads", () => {- const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);+ const terminalState = selectThreadTerminalState(+ useTerminalStateStore.getState().terminalStateByThreadId,+ THREAD_ID,+ );expect(terminalState).toEqual({terminalOpen: false,terminalHeight: 280,@@ -31,7 +34,10 @@ describe("terminalStateStore actions", () => {store.setTerminalOpen(THREAD_ID, true);store.splitTerminal(THREAD_ID, "terminal-2");- const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);+ const terminalState = selectThreadTerminalState(+ useTerminalStateStore.getState().terminalStateByThreadId,+ THREAD_ID,+ );expect(terminalState.terminalOpen).toBe(true);expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);expect(terminalState.activeTerminalId).toBe("terminal-2");@@ -43,7 +49,10 @@ describe("terminalStateStore actions", () => {it("creates new terminals in a separate group", () => {useTerminalStateStore.getState().newTerminal(THREAD_ID, "terminal-2");- const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);+ const terminalState = selectThreadTerminalState(+ useTerminalStateStore.getState().terminalStateByThreadId,+ THREAD_ID,+ );expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);expect(terminalState.activeTerminalId).toBe("terminal-2");expect(terminalState.activeTerminalGroupId).toBe("group-terminal-2");@@ -57,12 +66,16 @@ describe("terminalStateStore actions", () => {const store = useTerminalStateStore.getState();store.splitTerminal(THREAD_ID, "terminal-2");store.setTerminalActivity(THREAD_ID, "terminal-2", true);- expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([- "terminal-2",- ]);+ expect(+ selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)+ .runningTerminalIds,+ ).toEqual(["terminal-2"]);store.setTerminalActivity(THREAD_ID, "terminal-2", false);- expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([]);+ expect(+ selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)+ .runningTerminalIds,+ ).toEqual([]);});it("resets to default and clears persisted entry when closing the last terminal", () => {@@ -70,7 +83,10 @@ describe("terminalStateStore actions", () => {store.closeTerminal(THREAD_ID, "default");expect(useTerminalStateStore.getState().terminalStateByThreadId[THREAD_ID]).toBeUndefined();- expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).terminalIds).toEqual(["default"]);+ expect(+ selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID)+ .terminalIds,+ ).toEqual(["default"]);});it("keeps a valid active terminal after closing an active split terminal", () => {@@ -79,7 +95,10 @@ describe("terminalStateStore actions", () => {store.splitTerminal(THREAD_ID, "terminal-3");store.closeTerminal(THREAD_ID, "terminal-3");- const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);+ const terminalState = selectThreadTerminalState(+ useTerminalStateStore.getState().terminalStateByThreadId,+ THREAD_ID,+ );expect(terminalState.activeTerminalId).toBe("terminal-2");expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);expect(terminalState.terminalGroups).toEqual([diff --git a/apps/web/src/terminalStateStore.ts b/apps/web/src/terminalStateStore.tsindex 5f65dca3a..cf1ea8446 100644--- a/apps/web/src/terminalStateStore.ts+++ b/apps/web/src/terminalStateStore.ts@@ -35,7 +35,10 @@ function normalizeTerminalIds(terminalIds: string[]): string[] {return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];}-function normalizeRunningTerminalIds(runningTerminalIds: string[], terminalIds: string[]): string[] {+function normalizeRunningTerminalIds(+ runningTerminalIds: string[],+ terminalIds: string[],+): string[] {if (runningTerminalIds.length === 0) return [];const validTerminalIdSet = new Set(terminalIds);return [...new Set(runningTerminalIds)]@@ -58,7 +61,10 @@ function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): stringreturn candidate;}-function findGroupIndexByTerminalId(terminalGroups: ThreadTerminalGroup[], terminalId: string): number {+function findGroupIndexByTerminalId(+ terminalGroups: ThreadTerminalGroup[],+ terminalId: string,+): number {return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));}@@ -183,7 +189,9 @@ function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTermina? state.activeTerminalId: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);- const activeGroupIdFromState = terminalGroups.some((group) => group.id === state.activeTerminalGroupId)+ const activeGroupIdFromState = terminalGroups.some(+ (group) => group.id === state.activeTerminalGroupId,+ )? state.activeTerminalGroupId: null;const activeGroupIdFromTerminal =@@ -239,14 +247,16 @@ function upsertTerminalIntoGroups(return normalized;}- const terminalIds = isNewTerminal ? [...normalized.terminalIds, terminalId] : normalized.terminalIds;+ const terminalIds = isNewTerminal+ ? [...normalized.terminalIds, terminalId]+ : normalized.terminalIds;const terminalGroups = copyTerminalGroups(normalized.terminalGroups);const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);if (existingGroupIndex >= 0) {- terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[existingGroupIndex]!.terminalIds.filter(- (id) => id !== terminalId,- );+ terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[+ existingGroupIndex+ ]!.terminalIds.filter((id) => id !== terminalId);if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {terminalGroups.splice(existingGroupIndex, 1);}@@ -266,13 +276,18 @@ function upsertTerminalIntoGroups(});}- let activeGroupIndex = terminalGroups.findIndex((group) => group.id === normalized.activeTerminalGroupId);+ let activeGroupIndex = terminalGroups.findIndex(+ (group) => group.id === normalized.activeTerminalGroupId,+ );if (activeGroupIndex < 0) {activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);}if (activeGroupIndex < 0) {const usedGroupIds = new Set(terminalGroups.map((group) => group.id));- const nextGroupId = assignUniqueGroupId(fallbackGroupId(normalized.activeTerminalId), usedGroupIds);+ const nextGroupId = assignUniqueGroupId(+ fallbackGroupId(normalized.activeTerminalId),+ usedGroupIds,+ );terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });activeGroupIndex = terminalGroups.length - 1;}@@ -323,7 +338,10 @@ function newThreadTerminal(state: ThreadTerminalState, terminalId: string): Threreturn upsertTerminalIntoGroups(state, terminalId, "new");}-function setThreadActiveTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {+function setThreadActiveTerminal(+ state: ThreadTerminalState,+ terminalId: string,+): ThreadTerminalState {const normalized = normalizeThreadTerminalState(state);if (!normalized.terminalIds.includes(terminalId)) {return normalized;diff --git a/apps/web/src/wsNativeApi.test.ts b/apps/web/src/wsNativeApi.test.tsindex 142174fb0..2267cafd7 100644--- a/apps/web/src/wsNativeApi.test.ts+++ b/apps/web/src/wsNativeApi.test.ts@@ -12,12 +12,13 @@ import {import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const requestMock = vi.fn<(...args: Array<unknown>) => Promise<unknown>>();-const showContextMenuFallbackMock = vi.fn<- <T extends string>(- items: readonly ContextMenuItem<T>[],- position?: { x: number; y: number },- ) => Promise<T | null>->();+const showContextMenuFallbackMock =+ vi.fn<+ <T extends string>(+ items: readonly ContextMenuItem<T>[],+ position?: { x: number; y: number },+ ) => Promise<T | null>+ >();const channelListeners = new Map<string, Set<(data: unknown) => void>>();const subscribeMock = vi.fn<(channel: string, listener: (data: unknown) => void) => () => void>((channel, listener) => {@@ -400,10 +401,10 @@ describe("wsNativeApi", () => {const { createWsNativeApi } = await import("./wsNativeApi");const api = createWsNativeApi();- await api.contextMenu.show(- [{ id: "delete", label: "Delete", destructive: true }],- { x: 20, y: 30 },- );+ await api.contextMenu.show([{ id: "delete", label: "Delete", destructive: true }], {+ x: 20,+ y: 30,+ });expect(showContextMenuFallbackMock).toHaveBeenCalledWith([{ id: "delete", label: "Delete", destructive: true }],diff --git a/package.json b/package.jsonindex 1ae432d4c..56f5b8cca 100644--- a/package.json+++ b/package.json@@ -38,6 +38,7 @@"test": "turbo run test","test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop","fmt": "oxfmt",+ "fmt:check": "oxfmt --check","build:contracts": "turbo run build --filter=@t3tools/contracts","dist:desktop:artifact": "node scripts/build-desktop-artifact.ts","dist:desktop:dmg": "node scripts/build-desktop-artifact.ts --platform mac --target dmg",diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.tsindex 398dc2523..b3775504f 100644--- a/packages/contracts/src/git.test.ts+++ b/packages/contracts/src/git.test.ts@@ -8,7 +8,9 @@ import {} from "./git";const decodeCreateWorktreeInput = Schema.decodeUnknownSync(GitCreateWorktreeInput);-const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(GitPreparePullRequestThreadInput);+const decodePreparePullRequestThreadInput = Schema.decodeUnknownSync(+ GitPreparePullRequestThreadInput,+);const decodeResolvePullRequestResult = Schema.decodeUnknownSync(GitResolvePullRequestResult);describe("GitCreateWorktreeInput", () => {diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.tsindex f22bbca79..ae1eeeb5b 100644--- a/packages/contracts/src/git.ts+++ b/packages/contracts/src/git.ts@@ -14,11 +14,7 @@ const GitPushStepStatus = Schema.Literals(["skipped_up_to_date",]);const GitBranchStepStatus = Schema.Literals(["created", "skipped_not_requested"]);-const GitPrStepStatus = Schema.Literals([- "created",- "opened_existing",- "skipped_not_requested",-]);+const GitPrStepStatus = Schema.Literals(["created", "opened_existing", "skipped_not_requested"]);const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);const GitPullRequestReference = TrimmedNonEmptyStringSchema;const GitPullRequestState = Schema.Literals(["open", "closed", "merged"]);diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex ecc59f0b9..17c5eb21d 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -266,9 +266,7 @@ export const OrchestrationThread = Schema.Struct({updatedAt: IsoDateTime,deletedAt: Schema.NullOr(IsoDateTime),messages: Schema.Array(OrchestrationMessage),- proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(- Schema.withDecodingDefault(() => []),- ),+ proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(Schema.withDecodingDefault(() => [])),activities: Schema.Array(OrchestrationThreadActivity),checkpoints: Schema.Array(OrchestrationCheckpointSummary),session: Schema.NullOr(OrchestrationSession),diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.tsindex 4d1450bac..090325330 100644--- a/packages/contracts/src/project.ts+++ b/packages/contracts/src/project.ts@@ -28,9 +28,7 @@ export type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;export const ProjectWriteFileInput = Schema.Struct({cwd: TrimmedNonEmptyString,- relativePath: TrimmedNonEmptyString.check(- Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH),- ),+ relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH)),contents: Schema.String,});export type ProjectWriteFileInput = typeof ProjectWriteFileInput.Type;diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.tsindex 903bb5da7..96edded85 100644--- a/packages/contracts/src/providerRuntime.ts+++ b/packages/contracts/src/providerRuntime.ts@@ -61,12 +61,7 @@ const RuntimeThreadState = Schema.Literals([]);export type RuntimeThreadState = typeof RuntimeThreadState.Type;-const RuntimeTurnState = Schema.Literals([- "completed",- "failed",- "interrupted",- "cancelled",-]);+const RuntimeTurnState = Schema.Literals(["completed", "failed", "interrupted", "cancelled"]);export type RuntimeTurnState = typeof RuntimeTurnState.Type;const RuntimePlanStepStatus = Schema.Literals(["pending", "inProgress", "completed"]);@@ -573,14 +568,16 @@ const ProviderRuntimeSessionConfiguredEvent = Schema.Struct({type: SessionConfiguredType,payload: SessionConfiguredPayload,});-export type ProviderRuntimeSessionConfiguredEvent = typeof ProviderRuntimeSessionConfiguredEvent.Type;+export type ProviderRuntimeSessionConfiguredEvent =+ typeof ProviderRuntimeSessionConfiguredEvent.Type;const ProviderRuntimeSessionStateChangedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,type: SessionStateChangedType,payload: SessionStateChangedPayload,});-export type ProviderRuntimeSessionStateChangedEvent = typeof ProviderRuntimeSessionStateChangedEvent.Type;+export type ProviderRuntimeSessionStateChangedEvent =+ typeof ProviderRuntimeSessionStateChangedEvent.Type;const ProviderRuntimeSessionExitedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,@@ -601,14 +598,16 @@ const ProviderRuntimeThreadStateChangedEvent = Schema.Struct({type: ThreadStateChangedType,payload: ThreadStateChangedPayload,});-export type ProviderRuntimeThreadStateChangedEvent = typeof ProviderRuntimeThreadStateChangedEvent.Type;+export type ProviderRuntimeThreadStateChangedEvent =+ typeof ProviderRuntimeThreadStateChangedEvent.Type;const ProviderRuntimeThreadMetadataUpdatedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,type: ThreadMetadataUpdatedType,payload: ThreadMetadataUpdatedPayload,});-export type ProviderRuntimeThreadMetadataUpdatedEvent = typeof ProviderRuntimeThreadMetadataUpdatedEvent.Type;+export type ProviderRuntimeThreadMetadataUpdatedEvent =+ typeof ProviderRuntimeThreadMetadataUpdatedEvent.Type;const ProviderRuntimeThreadTokenUsageUpdatedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,@@ -764,7 +763,8 @@ const ProviderRuntimeUserInputResolvedEvent = Schema.Struct({type: UserInputResolvedType,payload: UserInputResolvedPayload,});-export type ProviderRuntimeUserInputResolvedEvent = typeof ProviderRuntimeUserInputResolvedEvent.Type;+export type ProviderRuntimeUserInputResolvedEvent =+ typeof ProviderRuntimeUserInputResolvedEvent.Type;const ProviderRuntimeTaskStartedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,@@ -856,7 +856,8 @@ const ProviderRuntimeMcpOauthCompletedEvent = Schema.Struct({type: McpOauthCompletedType,payload: McpOauthCompletedPayload,});-export type ProviderRuntimeMcpOauthCompletedEvent = typeof ProviderRuntimeMcpOauthCompletedEvent.Type;+export type ProviderRuntimeMcpOauthCompletedEvent =+ typeof ProviderRuntimeMcpOauthCompletedEvent.Type;const ProviderRuntimeModelReroutedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,@@ -877,7 +878,8 @@ const ProviderRuntimeDeprecationNoticeEvent = Schema.Struct({type: DeprecationNoticeType,payload: DeprecationNoticePayload,});-export type ProviderRuntimeDeprecationNoticeEvent = typeof ProviderRuntimeDeprecationNoticeEvent.Type;+export type ProviderRuntimeDeprecationNoticeEvent =+ typeof ProviderRuntimeDeprecationNoticeEvent.Type;const ProviderRuntimeFilesPersistedEvent = Schema.Struct({...ProviderRuntimeEventBase.fields,@@ -969,12 +971,7 @@ const ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEventexport type ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;// Legacy helper aliases retained for adapters/tests.-const ProviderRuntimeToolKind = Schema.Literals([- "command",- "file-read",- "file-change",- "other",-]);+const ProviderRuntimeToolKind = Schema.Literals(["command", "file-read", "file-change", "other"]);export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;export const ProviderRuntimeTurnStatus = RuntimeTurnState;diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.tsindex 83006988b..f659725c7 100644--- a/packages/shared/src/shell.test.ts+++ b/packages/shared/src/shell.test.ts@@ -5,7 +5,9 @@ import { extractPathFromShellOutput, readPathFromLoginShell } from "./shell";describe("extractPathFromShellOutput", () => {it("extracts the path between capture markers", () => {expect(- extractPathFromShellOutput("__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\n"),+ extractPathFromShellOutput(+ "__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\n",+ ),).toBe("/opt/homebrew/bin:/usr/bin");});diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.tsindex c44109fae..aebf11d5c 100644--- a/scripts/build-desktop-artifact.ts+++ b/scripts/build-desktop-artifact.ts@@ -23,8 +23,10 @@ const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);const RepoRoot = Effect.service(Path.Path).pipe(Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),);-const ProductionMacIconSource = Effect.zipWith(RepoRoot, Effect.service(Path.Path), (repoRoot, path) =>- path.join(repoRoot, BRAND_ASSET_PATHS.productionMacIconPng),+const ProductionMacIconSource = Effect.zipWith(+ RepoRoot,+ Effect.service(Path.Path),+ (repoRoot, path) => path.join(repoRoot, BRAND_ASSET_PATHS.productionMacIconPng),);const ProductionLinuxIconSource = Effect.zipWith(RepoRoot,diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.tsindex 89d7a104c..3815c4a3b 100644--- a/scripts/dev-runner.ts+++ b/scripts/dev-runner.ts@@ -399,9 +399,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {const envOverrides = {noBrowser: readOptionalBooleanEnv("T3CODE_NO_BROWSER"),- autoBootstrapProjectFromCwd: readOptionalBooleanEnv(- "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD",- ),+ autoBootstrapProjectFromCwd: readOptionalBooleanEnv("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD"),logWebSocketEvents: readOptionalBooleanEnv("T3CODE_LOG_WS_EVENTS"),};diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.tsindex 9e7595e61..bf9d9f5c6 100644--- a/scripts/release-smoke.ts+++ b/scripts/release-smoke.ts@@ -82,7 +82,12 @@ try {execFileSync(process.execPath,- [resolve(repoRoot, "scripts/update-release-package-versions.ts"), "9.9.9-smoke.0", "--root", tempRoot],+ [+ resolve(repoRoot, "scripts/update-release-package-versions.ts"),+ "9.9.9-smoke.0",+ "--root",+ tempRoot,+ ],{cwd: repoRoot,stdio: "inherit",@@ -95,17 +100,33 @@ try {});const lockfile = readFileSync(resolve(tempRoot, "bun.lock"), "utf8");- assertContains(lockfile, `"version": "9.9.9-smoke.0"`, "Expected bun.lock to contain the smoke version.");+ assertContains(+ lockfile,+ `"version": "9.9.9-smoke.0"`,+ "Expected bun.lock to contain the smoke version.",+ );const { arm64Path, x64Path } = writeMacManifestFixtures(tempRoot);- execFileSync(process.execPath, [resolve(repoRoot, "scripts/merge-mac-update-manifests.ts"), arm64Path, x64Path], {- cwd: repoRoot,- stdio: "inherit",- });+ execFileSync(+ process.execPath,+ [resolve(repoRoot, "scripts/merge-mac-update-manifests.ts"), arm64Path, x64Path],+ {+ cwd: repoRoot,+ stdio: "inherit",+ },+ );const mergedManifest = readFileSync(arm64Path, "utf8");- assertContains(mergedManifest, "T3-Code-9.9.9-smoke.0-arm64.zip", "Merged manifest is missing the arm64 asset.");- assertContains(mergedManifest, "T3-Code-9.9.9-smoke.0-x64.zip", "Merged manifest is missing the x64 asset.");+ assertContains(+ mergedManifest,+ "T3-Code-9.9.9-smoke.0-arm64.zip",+ "Merged manifest is missing the arm64 asset.",+ );+ assertContains(+ mergedManifest,+ "T3-Code-9.9.9-smoke.0-x64.zip",+ "Merged manifest is missing the x64 asset.",+ );console.log("Release smoke checks passed.");} finally {diff --git a/scripts/update-release-package-versions.ts b/scripts/update-release-package-versions.tsindex 7cdf13dd3..b860b85e8 100644--- a/scripts/update-release-package-versions.ts+++ b/scripts/update-release-package-versions.ts@@ -88,7 +88,8 @@ function parseArgs(argv: ReadonlyArray<string>): {return { version, rootDir, writeGithubOutput };}-const isMain = process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url);+const isMain =+ process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url);if (isMain) {const { version, rootDir, writeGithubOutput } = parseArgs(process.argv.slice(2));