Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0d4a38f079 | ||
|
|
f3b65dbedf | ||
|
|
38667d323c | ||
|
|
e829f971ce | ||
|
|
37cd7be09b | ||
|
|
aa6412c3ba | ||
|
|
04d86b0559 | ||
|
|
d4447da322 | ||
|
|
2512721b13 | ||
|
|
07d5dc1f25 | ||
|
|
3125dd80a7 | ||
|
|
25579c9942 | ||
|
|
5caae992e3 | ||
|
|
beb9201f5d | ||
|
|
c129be5e21 | ||
|
|
5aaae6cb60 | ||
|
|
8b94f007f2 | ||
|
|
80ce01b8e6 |
No files matched your search
@@ -17,12 +17,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
bun-version: 1.3.9
|
||||
|
||||
- name: Cache Bun and Turbo
|
||||
uses: actions/cache@v4
|
||||
|
||||
@@ -10,4 +10,3 @@ packages/*/dist
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
+1
-2
@@ -6,8 +6,7 @@
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
"*.tsbuildinfo"
|
||||
],
|
||||
"experimentalSortPackageJson": {}
|
||||
}
|
||||
+1
-8
@@ -1,13 +1,6 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
"dist",
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
],
|
||||
"ignorePatterns": ["dist", "dist-electron", "node_modules", "bun.lock", "*.tsbuildinfo"],
|
||||
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
|
||||
"categories": {
|
||||
"correctness": "warn",
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
|
||||
|
||||
PR 1: Service contracts + error taxonomy
|
||||
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs.
|
||||
Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).
|
||||
No behavior change yet, just interfaces and compile-time wiring points.
|
||||
PR 2: CheckpointStore Effect adapter
|
||||
Wrap current filesystemCheckpointStore behind CheckpointStoreLive (adapter).
|
||||
Map all thrown/Promise errors to tagged errors.
|
||||
Add service tests proving parity for isGitRepository, capture, restore, diff, prune.
|
||||
PR 3: CodexService Effect adapter
|
||||
Wrap current CodexAppServerManager behind CodexServiceLive (adapter).
|
||||
Convert public API to Effect return types with typed errors.
|
||||
Preserve existing EventEmitter internally for now, but expose Effect-friendly subscribe API.
|
||||
PR 4: ProviderService Effect adapter
|
||||
Wrap current ProviderManager behind ProviderServiceLive (adapter).
|
||||
Provider methods become Effect methods with typed errors.
|
||||
Route emitted provider events through an Effect PubSub surface.
|
||||
PR 5: wsServer migration to Effect services
|
||||
Stop instantiating provider/codex classes directly in wsServer.
|
||||
Resolve ProviderService (and related services) from one runtime/layer graph.
|
||||
Keep WS contract behavior identical.
|
||||
PR 6: Native CheckpointStore implementation
|
||||
Refactor checkpoint internals from Promise/throws to native Effect.
|
||||
Replace ad-hoc locking with Effect concurrency primitive (keyed lock/semaphore/queue).
|
||||
Keep adapter tests plus new failure-path tests.
|
||||
PR 7: Codex transport/RPC core as native Effect
|
||||
Split codex into scoped process layer + RPC request/response layer + session registry.
|
||||
Replace timeout/pending maps with Deferred + Effect timeout/finalizer semantics.
|
||||
Keep protocol behavior and ordering guarantees.
|
||||
PR 8: Codex protocol decoding hardening
|
||||
Replace ad-hoc unknown parsing with runtime schema decoding for inbound/outbound protocol shapes.
|
||||
Map decode failures to typed tagged errors (with root cause).
|
||||
Add regression tests for malformed/partial protocol messages.
|
||||
PR 9: Native ProviderService orchestration
|
||||
Rebuild provider logic in Effect using CodexService + CheckpointStore dependencies.
|
||||
Move event fanout, checkpoint capture/revert orchestration, thread-log routing to Effect state/services.
|
||||
Remove throw-based flow entirely from provider path.
|
||||
PR 10: Cleanup + deprecation removal
|
||||
Remove legacy class implementations/adapters once parity is proven.
|
||||
Finalize layer composition and startup graph docs.
|
||||
Add architecture notes for service boundaries and error model.
|
||||
@@ -1,58 +0,0 @@
|
||||
# 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.
|
||||
- Forward provider events by subscribing to `ProviderService.subscribeToEvents`.
|
||||
- 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:
|
||||
- root checkpoint created at session initialization before agent modifications
|
||||
- each completed turn captures filesystem checkpoint and persists metadata
|
||||
- no after-the-fact metadata rebuild/sync
|
||||
- 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`
|
||||
- session registry/state
|
||||
- Keep `CodexAdapter` contract stable while swapping internals.
|
||||
- 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.
|
||||
@@ -1,110 +0,0 @@
|
||||
# ProviderService Integration Test Plan
|
||||
|
||||
Goal:
|
||||
- Validate end-to-end `ProviderService` behavior with real layers:
|
||||
- `ProviderServiceLive`
|
||||
- `CheckpointServiceLive`
|
||||
- `CheckpointStoreLive`
|
||||
- `CheckpointRepositoryLive` (sqlite in-memory)
|
||||
- `ProviderSessionDirectoryLive`
|
||||
- Only fake the adapter event source (deterministic Codex-like stream).
|
||||
- Avoid mocking checkpointing/persistence orchestration logic.
|
||||
|
||||
## Test Harness
|
||||
|
||||
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
|
||||
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
|
||||
- Internal state:
|
||||
- session registry (session + cwd + threadId)
|
||||
- thread snapshot store (`threadId`, `turns`)
|
||||
- event subscribers
|
||||
- Behavior:
|
||||
- `startSession`: creates session with threadId.
|
||||
- `sendTurn`: appends a deterministic turn snapshot and emits ordered events:
|
||||
- `turn/started`
|
||||
- `item/started` / `item/completed` (tool + approval variants depending on scenario)
|
||||
- `item/agentMessage/delta` chunks
|
||||
- `turn/completed`
|
||||
- optional "mutator" callback per turn to change workspace files before completion.
|
||||
- `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
|
||||
- Arrange:
|
||||
- start provider session in git repo.
|
||||
- Assert:
|
||||
- `provider_checkpoints` contains root row (turn 0).
|
||||
- checkpoint ref exists in git.
|
||||
- second `startSession` for new session creates a new independent root.
|
||||
|
||||
2) Turn without filesystem change
|
||||
- Arrange:
|
||||
- emit normal turn events, no file mutation.
|
||||
- Assert:
|
||||
- provider subscribers receive:
|
||||
- `turn/started`
|
||||
- `turn/completed`
|
||||
- synthetic `checkpoint/captured`
|
||||
- `listCheckpoints` returns root + turn 1.
|
||||
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
|
||||
|
||||
3) Turn with filesystem change
|
||||
- Arrange:
|
||||
- mutate `README.md` during turn.
|
||||
- Assert:
|
||||
- `listCheckpoints` returns root + turn 1.
|
||||
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
|
||||
- persisted checkpoint metadata includes non-empty `checkpointRef`.
|
||||
|
||||
4) Multi-turn sequencing and checkpoint monotonicity
|
||||
- Arrange:
|
||||
- turn 1: no file change
|
||||
- turn 2: file change
|
||||
- turn 3: file change
|
||||
- Assert:
|
||||
- turn counts are monotonic and contiguous in DB (0,1,2,3).
|
||||
- latest checkpoint is marked current.
|
||||
- diffs for adjacent turns map to expected filesystem deltas.
|
||||
|
||||
5) Revert to checkpoint
|
||||
- Arrange:
|
||||
- execute 3 turns with at least one file-changing turn.
|
||||
- call `revertToCheckpoint(turnCount=1)`.
|
||||
- Assert:
|
||||
- workspace content matches turn 1 state.
|
||||
- adapter `rollbackThread` called with `numTurns=2`.
|
||||
- DB rows for turns >1 are removed.
|
||||
- later refs are deleted from git.
|
||||
|
||||
6) Capture failure surface
|
||||
- Arrange:
|
||||
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
|
||||
- Assert:
|
||||
- `ProviderService` emits `checkpoint/captureError`.
|
||||
- no partial metadata/ref divergence is left behind.
|
||||
|
||||
## 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:
|
||||
- `turn/started`, tool events, `turn/completed`, `checkpoint/captured`.
|
||||
- Assert orchestration projection still updates assistant message and turn diff summary.
|
||||
|
||||
## Proposed PR Split
|
||||
|
||||
PR 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.
|
||||
@@ -1,215 +0,0 @@
|
||||
# Server-Authoritative Event-Sourcing Cleanup Plan
|
||||
|
||||
Goal:
|
||||
- Move to a cleaner service architecture with:
|
||||
- durable, server-authoritative event sourcing
|
||||
- strict command routing/validation
|
||||
- pluggable provider adapters
|
||||
- explicit separation between transport, domain orchestration, provider runtime, and persistence
|
||||
|
||||
## Target Service Graph (ASCII)
|
||||
|
||||
```text
|
||||
+---------------------------+
|
||||
| wsServer |
|
||||
| transport |
|
||||
+---------------------------+
|
||||
| orchestration.dispatchCommand
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationCommandRouter |
|
||||
+-------------------------------------------+
|
||||
|
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationCommandHandlers |
|
||||
+-------------------------------------------+
|
||||
|
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationEventStore |
|
||||
+-------------------------------------------+
|
||||
|
|
||||
v
|
||||
+-------------------------------------------+
|
||||
| OrchestrationProjectionService |
|
||||
+-------------------------------------------+
|
||||
| snapshot/replay
|
||||
+---------------------------> wsServer
|
||||
|
||||
|
||||
wsServer -- providers.* RPC --> +---------------------------+
|
||||
| ProviderService |
|
||||
+---------------------------+
|
||||
| |
|
||||
v v
|
||||
+-------------------+ +-------------------------+
|
||||
| ProviderSession | | ProviderAdapterRegistry |
|
||||
| Registry (durable)| +-------------------------+
|
||||
+-------------------+ |
|
||||
^ v
|
||||
| +-------------------------+
|
||||
| | ProviderAdapter(s) |
|
||||
| +-------------------------+
|
||||
| |
|
||||
| runtime events v
|
||||
| +---------------------------+
|
||||
+----------| ProviderRuntimeIngestion |
|
||||
+---------------------------+
|
||||
| | |
|
||||
v v v
|
||||
Router Session Checkpoint
|
||||
Registry Service
|
||||
|
||||
+-------------------------------------------+
|
||||
| CheckpointService |
|
||||
+-------------------------------------------+
|
||||
| | |
|
||||
v v v
|
||||
+--------------------+ +-------------+ +-------------------+
|
||||
| CheckpointCatalog | | Checkpoint | | ProviderAdapter(s)|
|
||||
| (durable) | | Store (git) | | (read/rollback) |
|
||||
+--------------------+ +-------------+ +-------------------+
|
||||
|
|
||||
v
|
||||
+------+
|
||||
|SQLite|
|
||||
+------+
|
||||
|
||||
OrchestrationEventStore ------> SQLite
|
||||
OrchestrationProjectionService -> SQLite
|
||||
ProviderSessionRegistry ------> SQLite
|
||||
CheckpointCatalog ------> SQLite
|
||||
```
|
||||
|
||||
## Commit Series
|
||||
|
||||
### Commit 1: Split public vs system orchestration command contracts
|
||||
- Create separate schemas/types:
|
||||
- `ClientOrchestrationCommandSchema`
|
||||
- `SystemOrchestrationCommandSchema`
|
||||
- `OrchestrationCommandSchema = union(client, system)`
|
||||
- Ensure client transport can only submit client commands.
|
||||
- Keep system commands for server-internal workflows only.
|
||||
- Expected files:
|
||||
- `packages/contracts/src/orchestration.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- orchestration/service tests
|
||||
- Tests:
|
||||
- reject system-only command via WS dispatch path
|
||||
- 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.).
|
||||
- Expected files:
|
||||
- `apps/server/src/orchestration/Services/CommandRouter.ts` (new)
|
||||
- `apps/server/src/orchestration/Layers/CommandRouter.ts` (new)
|
||||
- `apps/server/src/orchestration/Layer.ts`
|
||||
- `apps/server/src/orchestration/reducer.ts` (only if needed for event payload changes)
|
||||
- Tests:
|
||||
- router validation and invariant failures
|
||||
- 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.
|
||||
- Expected files:
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (new migration)
|
||||
- `apps/server/src/persistence/Services/OrchestrationEvents.ts`
|
||||
- `apps/server/src/persistence/Layers/OrchestrationEvents.ts`
|
||||
- Tests:
|
||||
- duplicate command ID append returns same event/sequence (or explicit idempotent behavior)
|
||||
- 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
|
||||
- dispatches through router/engine
|
||||
- Remove provider-to-orchestration state mutation logic from `wsServer`.
|
||||
- Expected files:
|
||||
- `apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts` (new)
|
||||
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (new)
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- Tests:
|
||||
- ingestion service mapping tests (turn started/completed, message delta/completed, runtime error)
|
||||
- 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.
|
||||
- Expected files:
|
||||
- `apps/server/src/provider/Services/ProviderSessionDirectory.ts` (or new SessionRegistry service)
|
||||
- `apps/server/src/provider/Layers/ProviderSessionDirectory.ts`
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (new table/indexes)
|
||||
- provider persistence tests
|
||||
- Tests:
|
||||
- survives server restart with correct mapping
|
||||
- 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.
|
||||
- Expected files:
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (checkpoint schema migration)
|
||||
- `apps/server/src/persistence/Services/Checkpoints.ts`
|
||||
- `apps/server/src/persistence/Layers/Checkpoints.ts`
|
||||
- `apps/server/src/checkpointing/Layers/CheckpointService.ts`
|
||||
- Tests:
|
||||
- resume/new session over same thread sees same checkpoint history
|
||||
- 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).
|
||||
- Expected files:
|
||||
- `apps/server/src/persistence/Migrations/00x_*.ts` (projection tables)
|
||||
- `apps/server/src/orchestration/*` projection service/layer
|
||||
- `apps/server/src/wsServer.ts` (snapshot/replay path wiring)
|
||||
- Tests:
|
||||
- cold boot snapshot load without replaying full history in process
|
||||
- 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.
|
||||
- Expected files:
|
||||
- `apps/server/src/provider/Layers/ProviderService.ts`
|
||||
- new orchestration/checkpoint runtime coordinator service(s)
|
||||
- Tests:
|
||||
- provider service routing stays intact
|
||||
- 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
|
||||
- RPC Input/Output (both for routeRequest and command handler)
|
||||
- Event payloads
|
||||
- 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)
|
||||
- Look over effect services for unused methods, errors, etc
|
||||
- Update architecture docs with final service boundaries and boot/runtime graph.
|
||||
- Expected files:
|
||||
- legacy files + references
|
||||
- `AGENTS.md`/docs as needed
|
||||
- `.plans` docs linkage
|
||||
- Tests:
|
||||
- full server integration suite passes on Effect-only path
|
||||
- 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.
|
||||
@@ -1,10 +0,0 @@
|
||||
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)
|
||||
- ...
|
||||
@@ -1,145 +0,0 @@
|
||||
# PR #89 Review Remediation Plan (Phased)
|
||||
|
||||
## How To Use These Files
|
||||
|
||||
- Working checklist with updateable status per item (single source of truth): `.plans/16c-pr89-remediation-checklist.md`
|
||||
- This file (`16-pr89-review-remediation-phases.md`): phase strategy and grouping.
|
||||
|
||||
## Scope
|
||||
|
||||
- Source: GitHub review comments on PR #89 (`Add server-side orchestration engine with event sourcing`).
|
||||
- Triage baseline used here:
|
||||
- Total threads: 185
|
||||
- Outdated: 94 (excluded)
|
||||
- Active unresolved: 85
|
||||
- Invalid/false-positive: 3 (excluded)
|
||||
- Duplicate reposts: collapsed
|
||||
- Unique actionable findings after filtering: 58
|
||||
- Post-rewrite validity audit: 5 additional stale items marked invalid, leaving 53 actionable (`34 valid` + `19 partially-valid`)
|
||||
|
||||
## Phase 0: Canonical Triage Lock
|
||||
|
||||
- Create a single tracking checklist for the 53 currently actionable findings.
|
||||
- Map every duplicate thread to its canonical item.
|
||||
- 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 Wiring
|
||||
|
||||
Related 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.
|
||||
|
||||
## Phase 2: State Consistency and Ordering
|
||||
|
||||
Related 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.
|
||||
|
||||
## Phase 3: Checkpointing Correctness Bundle
|
||||
|
||||
Related 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`
|
||||
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
|
||||
- `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.
|
||||
|
||||
## Phase 4: Memory and Lifecycle Hygiene
|
||||
|
||||
Related 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 Cases
|
||||
|
||||
Related 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`
|
||||
- `apps/server/src/os-jank.ts`
|
||||
- `apps/server/src/git/Layers/GitCore.ts`
|
||||
- `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 Cleanup
|
||||
|
||||
Related 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.
|
||||
|
||||
## Phase 7: Verification and Closeout
|
||||
|
||||
- Add backend tests for all behavioral fixes (integration-focused; external services may be layered/mocked, core business logic not mocked out).
|
||||
- Run lint and backend tests for all touched packages.
|
||||
- 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.
|
||||
@@ -1,477 +0,0 @@
|
||||
# PR #89 Remediation Checklist (Consolidated)
|
||||
|
||||
_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
|
||||
- `DONE`: Implemented and verified
|
||||
- `CLOSED_INVALID`: Stale/invalid review finding
|
||||
|
||||
Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
|
||||
|
||||
## Active Checklist
|
||||
|
||||
### Phase 1
|
||||
|
||||
- [x] `C002` A dispatch error in `processEvent` will terminate the `Effect.forever` loop, permanently halting event ingestion. Consider adding error recovery (e.g., `Effect.catchAll` with logging) around `processEvent` so failures don't kill the fiber.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `High`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:333`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cH, PRRT_kwDORLtfbc5wnWwF, PRRT_kwDORLtfbc5wyTaP, PRRT_kwDORLtfbc5wzliw, PRRT_kwDORLtfbc5w0_g3, PRRT_kwDORLtfbc5w1HGT (+5 duplicate thread(s))
|
||||
- Audit note: Ingestion worker loop can terminate on unhandled processEvent failure.
|
||||
|
||||
- [x] `C003` Consider attaching a no-op error listener before `socket.write` (e.g., `socket.on('error', () => {})`) to prevent an unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `High`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:75`
|
||||
- Threads: PRRT_kwDORLtfbc5v-cf4
|
||||
- Audit note: Upgrade reject writes then destroys socket without defensive error listener.
|
||||
|
||||
- [x] `C012` Forked revert dispatch risks read model inconsistency
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:542`
|
||||
- Threads: PRRT_kwDORLtfbc5whszW, PRRT_kwDORLtfbc5wyTaS, PRRT_kwDORLtfbc5wzli0, PRRT_kwDORLtfbc5w0_g4, PRRT_kwDORLtfbc5w1HGX (+4 duplicate thread(s))
|
||||
- Audit note: Revert completion dispatch remains forked; state consistency window remains.
|
||||
|
||||
- [ ] `C019` ProviderRuntimeIngestion processes events for wrong thread on race
|
||||
- Status: `TODO`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:178`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaL
|
||||
- Audit note: SessionId-only routing can misassociate events under races/rebinds.
|
||||
|
||||
- [x] `C020` On `message.completed`, the message ID is added to the set and `thread.message.assistant.complete` is dispatched. On `turn.completed`, the same set is iterated and `thread.message.assistant.complete` is dispatched again for each ID—including already-completed ones. Consider removing message IDs from the set after dispatching on `message.completed`, or filtering out already-completed IDs before the `turn.completed` loop.
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:266`
|
||||
- Threads: PRRT_kwDORLtfbc5w1GPr
|
||||
- Audit note: Duplicate complete dispatch exists; downstream impact often idempotent.
|
||||
|
||||
- [x] `C026` Consider adding `.catch(() => {})` after `Effect.runPromise(handleMessage(ws, raw))` to prevent unhandled rejections from crashing the server if `encodeResponse` or setup logic fails.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:545`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cE
|
||||
- Audit note: runPromise result still not caught; rejection can surface unhandled.
|
||||
|
||||
- [x] `C027` WS message handler can cause unhandled promise rejection
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/wsServer.ts:545`
|
||||
- Threads: PRRT_kwDORLtfbc5wyTaW, PRRT_kwDORLtfbc5wzli3 (+1 duplicate thread(s))
|
||||
- Audit note: Same unhandled rejection path remains in WS message handler.
|
||||
|
||||
- [x] `C042` Duplicated `resolveThreadWorkspaceCwd` across three files
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62`
|
||||
- Threads: PRRT_kwDORLtfbc5wzli2
|
||||
- Audit note: Duplication exists but one instance is variant logic, so impact is moderate.
|
||||
|
||||
- [x] `C043` Duplicated workspace CWD resolution logic across reactor modules
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:62`
|
||||
- Threads: PRRT_kwDORLtfbc5wnWwM, PRRT_kwDORLtfbc5w1C3-, PRRT_kwDORLtfbc5w1HGZ (+2 duplicate thread(s))
|
||||
- Audit note: Workspace CWD resolution duplication still present across modules.
|
||||
|
||||
- [x] `C044` Checkpoint reactor swallows diff errors silently for `turn.completed`
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/CheckpointReactor.ts:274`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaO
|
||||
- Audit note: Errors are swallowed to empty diff with warning; not fully silent but still lossy.
|
||||
|
||||
- [x] `C045` `truncateDetail` slices to `limit - 1` then appends `"..."` (3 chars), producing strings of length `limit + 2`. Consider slicing to `limit - 3` instead. <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: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:29`
|
||||
- Threads: PRRT_kwDORLtfbc5wzp4R
|
||||
- Audit note: truncateDetail still overshoots limit.
|
||||
|
||||
- [x] `C046` `latestMessageIdByTurnKey` is written to but never read, and `clearAssistantMessageIdsForTurn` doesn't clear its entries—only `clearTurnStateForSession` does. Consider removing this map entirely if unused, or clearing it alongside `turnMessageIdsByTurnKey` in `clearAssistantMessageIdsForTurn`. <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: `Low`
|
||||
- Area: `Runtime resilience and failure handling`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts:133`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIQ
|
||||
- Audit note: latestMessageIdByTurnKey still unused/unpruned in per-turn clear path.
|
||||
|
||||
- [x] `C053` Consider using `socket.end(response)` instead of `socket.write(response)` + `socket.destroy()` to ensure the HTTP error response is fully flushed before closing the connection.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:83`
|
||||
- Threads: PRRT_kwDORLtfbc5v-WPD
|
||||
- Audit note: Still uses write+destroy rather than end() for rejection response.
|
||||
|
||||
- [ ] `C054` When array chunks contain a multi-byte UTF-8 character split across boundaries, decoding each chunk separately produces replacement characters. Consider using `Buffer.concat()` on all chunks before calling `.toString("utf8")`. <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: `Low`
|
||||
- Area: `WebSocket robustness`
|
||||
- File: `apps/server/src/wsServer.ts:104`
|
||||
- Threads: PRRT_kwDORLtfbc5whtrR
|
||||
- Audit note: Array chunk UTF-8 decode remains vulnerable to split multibyte corruption.
|
||||
|
||||
- [x] `C059` Suggestion: don’t spread `params` into `body`; it can override `_tag` and mishandle non-object values. Keep `_tag` separate and nest `params` under a single key (e.g., `data`), or validate `params` is a plain object.
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- 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.
|
||||
|
||||
### Phase 2
|
||||
|
||||
- [x] `C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`. <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: `High`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:96`
|
||||
- Threads: PRRT_kwDORLtfbc5wzp4T
|
||||
- Audit note: Append/project/receipt are non-atomic; retry can duplicate events.
|
||||
|
||||
- [x] `C013` If `projectionPipeline.projectEvent` fails after `eventStore.append` succeeds, the event is persisted but `readModel` isn't updated, causing desync. Consider updating the in-memory `readModel` immediately after append (before the external projection), so local state stays consistent regardless of downstream failures.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:99`
|
||||
- Threads: PRRT_kwDORLtfbc5whtrM
|
||||
- Audit note: Persisted event can outpace in-memory projection on mid-flight failure.
|
||||
|
||||
- [x] `C015` The gap-filling fallback logic can retain messages from turns that are about to be deleted, causing foreign key violations. Consider removing the fallback logic entirely, or filtering `fallbackUserMessages` and `fallbackAssistantMessages` to only include messages whose `turnId` is in `retainedTurnIds`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:99`
|
||||
- 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>
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Event ordering and state consistency`
|
||||
- File: `apps/server/src/orchestration/Layers/ProjectionPipeline.ts:490`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvH8
|
||||
- Audit note: Pending turn-start map is in-memory only and not rebuilt on bootstrap.
|
||||
|
||||
### Phase 3
|
||||
|
||||
- [x] `C008` Inconsistent input normalization across CheckpointStore methods
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- 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))
|
||||
- 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>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts:71`
|
||||
- Threads: PRRT_kwDORLtfbc5wiLhQ
|
||||
- Audit note: Snapshot sequence can under-report due to extra projectors, but replay impact is lower now.
|
||||
|
||||
- [x] `C033` Three error classes defined but never instantiated anywhere
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Errors.ts:51`
|
||||
- Threads: PRRT_kwDORLtfbc5wlYgo
|
||||
- Audit note: Original claim overstated; some errors used, others appear unused.
|
||||
|
||||
- [x] `C034` Redundant `CheckpointInvariantError` in `CheckpointServiceError` union type
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Errors.ts:79`
|
||||
- Threads: PRRT_kwDORLtfbc5wj5fn
|
||||
- Audit note: CheckpointInvariantError remains redundantly included in service union.
|
||||
|
||||
- [x] `C035` Redundant error type in CheckpointServiceError union definition
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Checkpointing correctness`
|
||||
- File: `apps/server/src/checkpointing/Errors.ts:79`
|
||||
- Threads: PRRT_kwDORLtfbc5wlYgs, PRRT_kwDORLtfbc5wxsO6, PRRT_kwDORLtfbc5w1C4B (+2 duplicate thread(s))
|
||||
- Audit note: Same as C034.
|
||||
|
||||
### Phase 4
|
||||
|
||||
- [ ] `C018` Unbounded memory growth in turn start deduplication set
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Memory/resource growth`
|
||||
- File: `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts:84`
|
||||
- Threads: PRRT_kwDORLtfbc5whszQ, PRRT_kwDORLtfbc5wl2A8, PRRT_kwDORLtfbc5wyTaT, PRRT_kwDORLtfbc5wzliz, PRRT_kwDORLtfbc5w0_g-, PRRT_kwDORLtfbc5w1HGW (+5 duplicate thread(s))
|
||||
- Audit note: handledTurnStartKeys still grows without pruning.
|
||||
|
||||
### 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>
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/git/Layers/GitCore.ts:41`
|
||||
- Threads: PRRT_kwDORLtfbc5w1CxT
|
||||
- Audit note: Braced rename parsing still breaks paths like src/{old => new}/file.ts.
|
||||
|
||||
- [ ] `C010` `loadCustomKeybindingsConfig` fails when the config file doesn't exist, which is expected for new users. Consider catching `ENOENT` and returning an empty array instead. <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`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/keybindings.ts:418`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIJ
|
||||
- Audit note: ENOENT for missing keybindings config still not handled as empty/default.
|
||||
|
||||
- [ ] `C022` Fish shell outputs `$PATH` as space-separated, not colon-separated. Consider checking if the shell is fish and using `string join : $PATH` instead, or validating the result contains colons before assigning.
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/os-jank.ts:10`
|
||||
- Threads: PRRT_kwDORLtfbc5wkRZM
|
||||
- Audit note: fish PATH formatting risk still exists in os-jank path recovery.
|
||||
|
||||
- [ ] `C023` Using `-il` flags causes the shell to source profile scripts that may print banners or other text, polluting the captured `PATH`. Consider using `-lc` (login only, non-interactive) to reduce unwanted output.
|
||||
- Status: `TODO`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/os-jank.ts:10`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cM
|
||||
- Audit note: -ilc shell invocation can pollute captured PATH output.
|
||||
|
||||
- [x] `C029` `parseFileUrlHref` already decodes the path (line 46), but `safeDecode` is called again here, corrupting filenames containing `%` sequences. Consider skipping the decode when `fileUrlTarget` is non-null.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/web/src/markdown-links.ts:105`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsU
|
||||
- Audit note: file URL decoding still double-decodes in one path.
|
||||
|
||||
- [x] `C030` `EXTERNAL_SCHEME_PATTERN` matches `script.ts:10` as a scheme because `.ts:` looks like `scheme:`. Consider requiring `://` after the colon, or checking that what follows the colon is not just digits. <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`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/web/src/markdown-links.ts:111`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsK
|
||||
- Audit note: Scheme regex still misclassifies script.ts:10 as external scheme.
|
||||
|
||||
- [ ] `C038` Multi-byte UTF-8 characters split across chunks will be corrupted when decoding each chunk separately. Consider accumulating all chunks first, then decoding once, or use `TextDecoder` with `stream: true`. <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: `Low`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/git/Layers/CodexTextGeneration.ts:136`
|
||||
- Threads: PRRT_kwDORLtfbc5w1GPo
|
||||
- Audit note: Chunk-by-chunk UTF-8 decode can still corrupt split multibyte characters.
|
||||
|
||||
- [x] `C039` The `+` key can be parsed (via trailing `+` handling) but cannot be encoded because `shortcut.key.includes("+")` returns true for the literal `+` key. Consider checking `shortcut.key === "+"` separately and encoding it as `"space"` style (e.g., a special token), or adjusting the condition to allow the single `+` character. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/keybindings.ts:352`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIB
|
||||
- Audit note: Parser/encoder mismatch remains, but encoder path currently low-use.
|
||||
|
||||
- [x] `C040` `upsertKeybindingRule` has a race condition: concurrent calls read the same file state, then the last write overwrites earlier changes. Consider wrapping the read-modify-write sequence with `Effect.Semaphore` to serialize access. <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: `Low`
|
||||
- Area: `Edge-case parsing/platform behavior`
|
||||
- File: `apps/server/src/keybindings.ts:488`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIA
|
||||
- Audit note: upsertKeybindingRule read-modify-write remains race-prone.
|
||||
|
||||
### Phase 6
|
||||
|
||||
- [ ] `C028` Branch sync dispatches both server and stale local update
|
||||
- Status: `TODO`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Medium`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/components/BranchToolbar.tsx:102`
|
||||
- Threads: PRRT_kwDORLtfbc5v-XCu
|
||||
- Audit note: Optimistic local+server dual update is intentional but can temporarily diverge.
|
||||
|
||||
- [x] `C037` `Effect.callback` should return a cleanup function to close the server(s) on fiber interruption. Without it, the `Net.Server` handles keep the process alive and leak the port if the effect is cancelled. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/config.ts:41`
|
||||
- Threads: PRRT_kwDORLtfbc5wj4cO
|
||||
- Audit note: Callback cleanup missing, but practical exposure is low in one-shot startup path.
|
||||
|
||||
- [ ] `C047` `SqlSchema.findOneOption` can produce both SQL errors and decode errors, but `mapError` wraps all as `PersistenceSqlError`. Consider distinguishing `ParseError` from SQL errors and mapping decode failures to `PersistenceDecodeError` instead. <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: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/persistence/Layers/OrchestrationCommandReceipts.ts:75`
|
||||
- Threads: PRRT_kwDORLtfbc5wiaR-
|
||||
- Audit note: Decode and SQL errors still collapsed into one persistence error kind.
|
||||
|
||||
- [x] `C049` `JSON.stringify(cause)` returns `undefined` for `undefined`, functions, or symbols, violating the `string` return type. Consider coercing the result to a string (e.g., `String(JSON.stringify(cause))`) or adding a fallback.
|
||||
- Status: `DONE`
|
||||
- Verdict: `valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/provider/Layers/ProviderService.ts:59`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsI
|
||||
- Audit note: JSON.stringify(cause) may return undefined despite string expectations.
|
||||
|
||||
- [ ] `C050` The read-modify-write pattern (`getBySessionId` → merge → `upsert`) is susceptible to lost updates under concurrent writes. Consider wrapping in a transaction or adding optimistic concurrency control (e.g., version field) if concurrent session updates are expected. <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: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:94`
|
||||
- Threads: PRRT_kwDORLtfbc5wiLhY
|
||||
- Audit note: ProviderSessionDirectory upsert remains read-merge-write without concurrency control.
|
||||
|
||||
- [x] `C051` Using `??` for `providerThreadId` and `adapterKey` makes it impossible to clear these fields by passing `null`, since `null ?? existing` evaluates to `existing`. Consider using explicit `undefined` checks (like `resumeCursor` does) if clearing should be supported. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
|
||||
- Status: `DONE`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/provider/Layers/ProviderSessionDirectory.ts:119`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvH9
|
||||
- Audit note: Null-clearing issue is real for providerThreadId; adapterKey part overstated.
|
||||
|
||||
- [ ] `C052` Race condition: `processHandle` may be `null` when `data` callback fires, since it's assigned after `Bun.spawn` returns. Consider initializing `BunPtyProcess` first, then passing it to the callback to avoid losing initial output. <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: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/server/src/terminal/Layers/BunPTY.ts:97`
|
||||
- Threads: PRRT_kwDORLtfbc5w1CxE
|
||||
- Audit note: Data callback may race before processHandle assignment.
|
||||
|
||||
- [ ] `C056` When `onOpenChange` is provided without `open`, the internal `_open` state never updates because `setOpenProp` takes precedence. Consider calling `_setOpen` when `openProp === undefined`, regardless of whether `setOpenProp` exists.
|
||||
- Status: `TODO`
|
||||
- Verdict: `partially-valid`
|
||||
- Severity: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/components/ui/sidebar.tsx:114`
|
||||
- Threads: PRRT_kwDORLtfbc5wxvIq
|
||||
- Audit note: Bug pattern exists, but current callsites mostly avoid triggering it.
|
||||
|
||||
- [ ] `C057` The `resizable` object is recreated on every render, causing `SidebarRail`'s `useEffect` to repeatedly read localStorage and update the DOM. Consider memoizing the object with `useMemo`. <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: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/routes/_chat.$threadId.tsx:105`
|
||||
- Threads: PRRT_kwDORLtfbc5wyWz4
|
||||
- Audit note: Resizable object recreation still retriggers effect/storage reads.
|
||||
|
||||
- [ ] `C058` When `localStorage.getItem()` returns `null`, `Number(null)` evaluates to `0`, which passes `Number.isFinite(0)`. This causes the sidebar to clamp to `minWidth` on first load, overriding the `DIFF_INLINE_DEFAULT_WIDTH` CSS clamp. Consider checking for `null` or empty string before parsing, e.g. guard with `storedWidth === null || storedWidth === ''`. <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: `Low`
|
||||
- Area: `Other`
|
||||
- File: `apps/web/src/routes/_chat.$threadId.tsx:122`
|
||||
- Threads: PRRT_kwDORLtfbc5wnVsX
|
||||
- Audit note: Number(null) -> 0 path still forces min width on initial load.
|
||||
|
||||
- [ ] `C060` `defaultModel` should be `Schema.optional(Schema.NullOr(Schema.String))` to allow clearing the value. Currently there's no way to reset it to `null` since omitting means "no change" in patch semantics. <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: `Low`
|
||||
- Area: `Other`
|
||||
- File: `packages/contracts/src/orchestration.ts:253`
|
||||
- Threads: PRRT_kwDORLtfbc5whxJC
|
||||
- Audit note: Schema still cannot express null clear for defaultModel patch.
|
||||
|
||||
## Closed Invalid Items
|
||||
|
||||
- [x] `C014` Engine error handler catches all errors including non-invariant ones
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts:144`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaJ
|
||||
- Rationale: Broad catch is intentional for worker liveness; transactional dispatch path prevents the claimed non-invariant idempotency break in current design.
|
||||
|
||||
- [x] `C021` Shared mutable default metadata object causes stale eventId
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/server/src/orchestration/decider.ts:27`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaA
|
||||
- Rationale: Stale-eventId claim no longer applies; eventId is regenerated per event.
|
||||
|
||||
- [x] `C025` Duplicated checkpoint ref computation across two files
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/server/src/wsServer.ts:128`
|
||||
- Threads: PRRT_kwDORLtfbc5wvwag
|
||||
- Rationale: No longer duplicated; checkpoint ref helper now centralized.
|
||||
|
||||
- [x] `C031` Revert uses wrong turn count from positional inference
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Medium`
|
||||
- File: `apps/web/src/session-logic.ts:127`
|
||||
- Threads: PRRT_kwDORLtfbc5v9SCp
|
||||
- Rationale: Revert now uses explicit checkpointTurnCount first; positional fallback is non-primary.
|
||||
|
||||
- [x] `C036` Duplicate `checkpointRefForThreadTurn` function in two production files
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Low`
|
||||
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:284`
|
||||
- Threads: PRRT_kwDORLtfbc5wiqFX
|
||||
- Rationale: No longer duplicated; single production source via Refs.ts.
|
||||
|
||||
- [x] `C055` Duplicate `checkpointRefForThreadTurn` function across files
|
||||
- Status: `CLOSED_INVALID`
|
||||
- Severity: `Low`
|
||||
- File: `apps/server/src/wsServer.ts:128`
|
||||
- Threads: PRRT_kwDORLtfbc5wkPaG
|
||||
- Rationale: No longer duplicated; helper is centralized.
|
||||
@@ -1,201 +0,0 @@
|
||||
# Spec 1:1 Cutover Plan
|
||||
|
||||
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.
|
||||
- Mark each row with status labels: `required`, `implemented`, `to-replace`, `delete`.
|
||||
- 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.
|
||||
- Create `003_checkpoint_diff_blobs.ts` with uniqueness on `(thread_id, from_turn_count, to_turn_count)`.
|
||||
- Create `004_provider_session_runtime.ts` with PK and runtime lookup indexes.
|
||||
- Create `005_projections.ts` with all projection tables:
|
||||
- `projection_projects`
|
||||
- `projection_threads`
|
||||
- `projection_thread_messages`
|
||||
- `projection_thread_activities`
|
||||
- `projection_thread_sessions`
|
||||
- `projection_thread_turns`
|
||||
- `projection_checkpoints`
|
||||
- `projection_pending_approvals`
|
||||
- `projection_state`
|
||||
- Add all required indexes/constraints in `005_projections.ts`.
|
||||
- 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.
|
||||
- Normalize enum and null semantics to match contracts exactly.
|
||||
- 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.
|
||||
- Refactor read/replay path to decode payload and metadata from JSON and return `OrchestrationEvent` consistently.
|
||||
- Remove assumptions from old minimal schema (`aggregate_id`, missing metadata/actor).
|
||||
- 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`.
|
||||
- On domain rejection, persist rejected receipt with error payload.
|
||||
- On duplicate command, return prior result from receipt without re-appending event.
|
||||
- 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.
|
||||
- Define projector names used in `projection_state` and make them stable constants.
|
||||
- Add replay bootstrap from event store to bring projections up to latest sequence on startup.
|
||||
- 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`.
|
||||
- Implement `getTurnDiff` query backed by `checkpoint_diff_blobs` only.
|
||||
- Remove or bypass in-memory snapshot construction for RPC responses.
|
||||
- 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`.
|
||||
- Remove writes to legacy provider session tables.
|
||||
- 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.
|
||||
- Remove unused contracts/types linked to deprecated persistence model.
|
||||
- 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.
|
||||
- Add projector tests for transactional row updates + `projection_state` updates.
|
||||
- Add snapshot tests verifying projection-sourced output and `snapshotSequence` semantics.
|
||||
- Add turn diff tests verifying `checkpoint_diff_blobs` source of truth.
|
||||
- Add provider runtime tests for persist + restart + resume behavior.
|
||||
- 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.
|
||||
@@ -1,401 +0,0 @@
|
||||
# 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.
|
||||
- `delete`: current path actively conflicts with SPEC and should be removed.
|
||||
|
||||
## 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:
|
||||
- `sequence INTEGER PRIMARY KEY` (global monotonic)
|
||||
- `event_id TEXT UNIQUE NOT NULL`
|
||||
- `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')`
|
||||
- `stream_id TEXT NOT NULL`
|
||||
- `stream_version INTEGER NOT NULL`
|
||||
- `event_type TEXT NOT NULL`
|
||||
- `occurred_at TEXT NOT NULL`
|
||||
- `command_id TEXT NULL`
|
||||
- `causation_event_id TEXT NULL`
|
||||
- `correlation_id TEXT NULL`
|
||||
- `actor_kind TEXT NOT NULL CHECK IN ('client','server','provider')`
|
||||
- `payload_json TEXT NOT NULL`
|
||||
- `metadata_json TEXT NOT NULL`
|
||||
- Current writer path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts`
|
||||
- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts`
|
||||
- Owner module: `apps/server/src/persistence` (event store + migrations)
|
||||
- Status: `to-replace`
|
||||
- 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:
|
||||
- `command_id TEXT PRIMARY KEY`
|
||||
- `aggregate_kind TEXT NOT NULL CHECK IN ('project','thread')`
|
||||
- `aggregate_id TEXT NOT NULL`
|
||||
- `accepted_at TEXT NOT NULL`
|
||||
- `result_sequence INTEGER NOT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('accepted','rejected')`
|
||||
- `error TEXT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: `apps/server/src/orchestration` dispatch boundary + `apps/server/src/persistence`
|
||||
- Status: `to-replace`
|
||||
- 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:
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `from_turn_count INTEGER NOT NULL`
|
||||
- `to_turn_count INTEGER NOT NULL`
|
||||
- `diff TEXT NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `UNIQUE(thread_id, from_turn_count, to_turn_count)`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: `apps/server/src/persistence` + turn diff query service
|
||||
- Status: `to-replace`
|
||||
- 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:
|
||||
- `provider_session_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `provider_name TEXT NOT NULL`
|
||||
- `adapter_key TEXT NOT NULL`
|
||||
- `provider_thread_id TEXT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('starting','running','stopped','error')`
|
||||
- `last_seen_at TEXT NOT NULL`
|
||||
- `resume_cursor_json TEXT NULL`
|
||||
- `runtime_payload_json TEXT NULL`
|
||||
- Current writer path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`)
|
||||
- Current reader path: legacy provider session persistence (`apps/server/src/persistence/Layers/ProviderSessions.ts`)
|
||||
- Owner module: provider runtime manager + persistence runtime repository
|
||||
- Status: `to-replace`
|
||||
- Notes: existing `provider_sessions` schema is incompatible and too small.
|
||||
|
||||
## 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.
|
||||
- Current writer path: contracts defined in `packages/contracts/src/orchestration.ts`
|
||||
- Current reader path: used by persistence decode boundaries (partial)
|
||||
- Owner module: `packages/contracts`
|
||||
- Status: `implemented`
|
||||
- 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.
|
||||
- Current writer path: `packages/contracts/src/orchestration.ts`
|
||||
- Current reader path: `apps/server/src/persistence/Layers/OrchestrationEventStore.ts` decode path
|
||||
- Owner module: contracts + event store
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: `apps/server/src/orchestration/decider.ts` (metadata mostly empty)
|
||||
- Current reader path: projector/event consumers
|
||||
- Owner module: decider + provider ingestion + event store
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: event store append logic + DB constraints
|
||||
- Status: `to-replace`
|
||||
- Notes: no stream version assignment/checking today.
|
||||
|
||||
## 7.3 Required Projected Tables (Read Models)
|
||||
|
||||
### P1
|
||||
- Spec ref: `7.3.1 projection_projects`
|
||||
- Requirement: persisted project projection table.
|
||||
- SQL contract:
|
||||
- `project_id TEXT PRIMARY KEY`
|
||||
- `title TEXT NOT NULL`
|
||||
- `workspace_root TEXT NOT NULL`
|
||||
- `default_model TEXT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- `deleted_at TEXT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- 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:
|
||||
- `thread_id TEXT PRIMARY KEY`
|
||||
- `project_id TEXT NOT NULL`
|
||||
- `title TEXT NOT NULL`
|
||||
- `model TEXT NOT NULL`
|
||||
- `branch TEXT NULL`
|
||||
- `worktree_path TEXT NULL`
|
||||
- `latest_turn_id TEXT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- `deleted_at TEXT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and projector writes.
|
||||
|
||||
### P3
|
||||
- Spec ref: `7.3.3 projection_thread_messages`
|
||||
- Requirement: persisted thread message projection table.
|
||||
- SQL contract:
|
||||
- `message_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `role TEXT NOT NULL CHECK IN ('user','assistant','system')`
|
||||
- `text TEXT NOT NULL`
|
||||
- `is_streaming INTEGER/BOOLEAN NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and message projection writes.
|
||||
|
||||
### P4
|
||||
- Spec ref: `7.3.4 projection_thread_activities`
|
||||
- Requirement: persisted thread activity projection table.
|
||||
- SQL contract:
|
||||
- `activity_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `tone TEXT NOT NULL CHECK IN ('info','tool','approval','error')`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `summary TEXT NOT NULL`
|
||||
- `payload_json TEXT NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- Notes: no canonical activity projection persistence.
|
||||
|
||||
### P5
|
||||
- Spec ref: `7.3.5 projection_thread_sessions`
|
||||
- Requirement: persisted thread session projection table.
|
||||
- SQL contract:
|
||||
- `thread_id TEXT PRIMARY KEY`
|
||||
- `status TEXT NOT NULL CHECK IN ('idle','starting','running','ready','interrupted','stopped','error')`
|
||||
- `provider_name TEXT NULL`
|
||||
- `provider_session_id TEXT NULL`
|
||||
- `provider_thread_id TEXT NULL`
|
||||
- `active_turn_id TEXT NULL`
|
||||
- `last_error TEXT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- Current writer path: none (in-memory projector only)
|
||||
- Current reader path: none (snapshot not DB-projected)
|
||||
- Owner module: projector pipeline + snapshot query
|
||||
- Status: `to-replace`
|
||||
- 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:
|
||||
- `turn_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_count INTEGER NOT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('running','completed','interrupted','error')`
|
||||
- `user_message_id TEXT NULL`
|
||||
- `assistant_message_id TEXT NULL`
|
||||
- `started_at TEXT NOT NULL`
|
||||
- `completed_at TEXT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector pipeline + session/turn query helpers
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and projection logic.
|
||||
|
||||
### P7
|
||||
- Spec ref: `7.3.7 projection_checkpoints`
|
||||
- Requirement: persisted checkpoint summary projection table.
|
||||
- SQL contract:
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NOT NULL`
|
||||
- `checkpoint_turn_count INTEGER NOT NULL`
|
||||
- `checkpoint_ref TEXT NOT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('ready','missing','error')`
|
||||
- `files_json TEXT NOT NULL`
|
||||
- `assistant_message_id TEXT NULL`
|
||||
- `completed_at TEXT NOT NULL`
|
||||
- `UNIQUE(thread_id, checkpoint_turn_count)`
|
||||
- Current writer path: legacy `provider_checkpoints` writes in `apps/server/src/persistence/Layers/Checkpoints.ts`
|
||||
- Current reader path: legacy checkpoint repository
|
||||
- Owner module: projector pipeline + checkpoint query layer
|
||||
- Status: `to-replace`
|
||||
- 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:
|
||||
- `request_id TEXT PRIMARY KEY`
|
||||
- `thread_id TEXT NOT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `status TEXT NOT NULL CHECK IN ('pending','resolved')`
|
||||
- `decision TEXT NULL CHECK IN ('accept','acceptForSession','decline','cancel')`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `resolved_at TEXT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector pipeline + approval query layer
|
||||
- Status: `to-replace`
|
||||
- Notes: missing table and projection logic.
|
||||
|
||||
### P9
|
||||
- Spec ref: `7.3.9 projection_state`
|
||||
- Requirement: projector progress tracking table.
|
||||
- SQL contract:
|
||||
- `projector TEXT PRIMARY KEY`
|
||||
- `last_applied_sequence INTEGER NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector runner/checkpointing
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: none (in-memory projector has no SQL transaction)
|
||||
- Current reader path: none
|
||||
- Owner module: projector runner
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: none
|
||||
- Current reader path: none
|
||||
- Owner module: projector runner
|
||||
- Status: `required`
|
||||
- Notes: interpretation: exclude from first cutover unless debugging requires it.
|
||||
|
||||
## 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`.
|
||||
- Current writer path: in-memory model built in `apps/server/src/orchestration/projector.ts`
|
||||
- Current reader path: `apps/server/src/orchestration/Layers/OrchestrationEngine.ts#getReadModel`
|
||||
- Owner module: snapshot query service + ws RPC handler
|
||||
- Status: `delete`
|
||||
- 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.
|
||||
- Current writer path: none
|
||||
- Current reader path: in-memory thread/project arrays
|
||||
- Owner module: snapshot query service
|
||||
- Status: `to-replace`
|
||||
- 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`.
|
||||
- Current writer path: legacy checkpoint repo data model
|
||||
- Current reader path: in-memory checkpoints from orchestration events
|
||||
- Owner module: snapshot query service + checkpoint projector
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: none for diff blobs
|
||||
- Current reader path: `orchestration.getTurnDiff` schema exists, data backing incomplete
|
||||
- Owner module: ws RPC handler + diff query service
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: mixed provider/session handling paths
|
||||
- Current reader path: legacy provider session persistence lookups
|
||||
- Owner module: provider dispatch/session resolution
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: none
|
||||
- Current reader path: currently from in-memory event projection sequence
|
||||
- Owner module: snapshot query service
|
||||
- Status: `to-replace`
|
||||
- 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.
|
||||
- Current writer path: event stream via `OrchestrationEventStore.readFromSequence`
|
||||
- Current reader path: ws replay flow in `apps/server/src/wsServer.ts`
|
||||
- Owner module: ws RPC + event stream handoff layer
|
||||
- Status: `to-replace`
|
||||
- Notes: interpretation requires explicit consistency boundary (transaction, sequence fence, or equivalent).
|
||||
|
||||
## 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`.
|
||||
Vendored
+1
-2
@@ -4,6 +4,5 @@
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.oxc": "always"
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
"oxc.unusedDisableDirectives": "warn"
|
||||
}
|
||||
@@ -29,7 +29,7 @@ How we use it in this codebase:
|
||||
- Session startup/resume and turn lifecycle are brokered in `apps/server/src/codexAppServerManager.ts`.
|
||||
- Provider dispatch and thread event logging are coordinated in `apps/server/src/providerManager.ts`.
|
||||
- WebSocket server routes NativeApi methods in `apps/server/src/wsServer.ts`.
|
||||
- Web app consumes orchestration domain events via WebSocket push on channel `orchestration.domainEvent` (provider runtime activity is projected into orchestration events server-side).
|
||||
- Web app consumes provider event streams via WebSocket push on channel `providers.event`.
|
||||
|
||||
Docs:
|
||||
|
||||
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
# Keybindings
|
||||
|
||||
T3 Code reads keybindings from:
|
||||
|
||||
- `~/.t3/keybindings.json`
|
||||
|
||||
The file must be a JSON array of rules:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "key": "mod+g", "command": "terminal.toggle" },
|
||||
{ "key": "mod+shift+g", "command": "terminal.new", "when": "terminalFocus" }
|
||||
]
|
||||
```
|
||||
|
||||
See the full schema for more details: [`packages/contracts/src/keybindings.ts`](packages/contracts/src/keybindings.ts)
|
||||
|
||||
## Defaults
|
||||
|
||||
```json
|
||||
[
|
||||
{ "key": "mod+j", "command": "terminal.toggle" },
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
{ "key": "mod+o", "command": "editor.openFavorite" }
|
||||
]
|
||||
```
|
||||
|
||||
For most up to date defaults, see [`DEFAULT_KEYBINDINGS` in `apps/server/src/keybindings.ts`](apps/server/src/keybindings.ts)
|
||||
|
||||
## Configuration
|
||||
|
||||
### Rule Shape
|
||||
|
||||
Each entry supports:
|
||||
|
||||
- `key` (required): shortcut string, like `mod+j`, `ctrl+k`, `cmd+shift+d`
|
||||
- `command` (required): action ID
|
||||
- `when` (optional): boolean expression controlling when the shortcut is active
|
||||
|
||||
Invalid rules are ignored. Invalid config files are ignored. Warnings are logged by the server.
|
||||
|
||||
### Available Commands
|
||||
|
||||
- `terminal.toggle`: open/close terminal drawer
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
|
||||
|
||||
### Key Syntax
|
||||
|
||||
Supported modifiers:
|
||||
|
||||
- `mod` (`cmd` on macOS, `ctrl` on non-macOS)
|
||||
- `cmd` / `meta`
|
||||
- `ctrl` / `control`
|
||||
- `shift`
|
||||
- `alt` / `option`
|
||||
|
||||
Examples:
|
||||
|
||||
- `mod+j`
|
||||
- `mod+shift+d`
|
||||
- `ctrl+l`
|
||||
- `cmd+k`
|
||||
|
||||
### `when` Conditions
|
||||
|
||||
Currently available context keys:
|
||||
|
||||
- `terminalFocus`
|
||||
- `terminalOpen`
|
||||
|
||||
Supported operators:
|
||||
|
||||
- `!` (not)
|
||||
- `&&` (and)
|
||||
- `||` (or)
|
||||
- parentheses: `(` `)`
|
||||
|
||||
Examples:
|
||||
|
||||
- `"when": "terminalFocus"`
|
||||
- `"when": "terminalOpen && !terminalFocus"`
|
||||
- `"when": "terminalFocus || terminalOpen"`
|
||||
|
||||
Unknown condition keys evaluate to `false`.
|
||||
|
||||
### Precedence
|
||||
|
||||
- Rules are evaluated in array order.
|
||||
- For a key event, the last rule where both `key` matches and `when` evaluates to `true` wins.
|
||||
- That means precedence is across commands, not only within the same command.
|
||||
@@ -56,9 +56,6 @@ T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
```
|
||||
@@ -72,17 +69,6 @@ npx t3
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
@@ -106,12 +92,12 @@ T3 Code has a global runtime mode switch in the chat toolbar:
|
||||
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
|
||||
|
||||
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
|
||||
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
|
||||
- **Push events**: `{ type: "push", channel, data }` for streaming provider events
|
||||
|
||||
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
|
||||
|
||||
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
|
||||
- `providers.respondToRequest`, `providers.stopSession`
|
||||
- `providers.respondToRequest`, `providers.stopSession`, `providers.listSessions`
|
||||
- `shell.openInEditor`, `server.getConfig`
|
||||
|
||||
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
# Remote Access Setup
|
||||
|
||||
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
|
||||
|
||||
## CLI ↔ Env option map
|
||||
|
||||
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
|
||||
|
||||
| CLI flag | Env var | Notes |
|
||||
| ----------------------- | --------------------- | ---------------------------------- |
|
||||
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
|
||||
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
|
||||
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
|
||||
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
|
||||
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
|
||||
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
|
||||
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
|
||||
|
||||
> TIP: Use the `--help` flag to see all available options and their descriptions.
|
||||
|
||||
## Security First
|
||||
|
||||
- Always set `--auth-token` before exposing the server outside localhost.
|
||||
- Treat the token like a password.
|
||||
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
|
||||
|
||||
## 1) Build + run server for remote access
|
||||
|
||||
Remote access should use the built web app (not local Vite redirect mode).
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
```
|
||||
|
||||
Then open on your phone:
|
||||
|
||||
`http://<your-machine-ip>:3773`
|
||||
|
||||
Example:
|
||||
|
||||
`http://192.168.1.42:3773`
|
||||
|
||||
Notes:
|
||||
|
||||
- `--host 0.0.0.0` listens on all IPv4 interfaces.
|
||||
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
|
||||
- Ensure your OS firewall allows inbound TCP on the selected port.
|
||||
|
||||
## 2) Tailnet / Tailscale access
|
||||
|
||||
If you use Tailscale, you can bind directly to your Tailnet address.
|
||||
|
||||
```bash
|
||||
TAILNET_IP="$(tailscale ip -4)"
|
||||
TOKEN="$(openssl rand -hex 24)"
|
||||
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
|
||||
```
|
||||
|
||||
Open from any device in your tailnet:
|
||||
|
||||
`http://<tailnet-ip>:3773`
|
||||
|
||||
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
|
||||
@@ -1,582 +0,0 @@
|
||||
# Orchestration Interface Spec (Required State)
|
||||
|
||||
Status: Required target architecture (not a description of current behavior).
|
||||
|
||||
## 1. Identifier Schema (Branded)
|
||||
|
||||
All identifiers are branded and never plain `string` in schema definitions.
|
||||
|
||||
```ts
|
||||
const ThreadId = Schema.String.pipe(Schema.brand("ThreadId"));
|
||||
const ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
|
||||
const CommandId = Schema.String.pipe(Schema.brand("CommandId"));
|
||||
const EventId = Schema.String.pipe(Schema.brand("EventId"));
|
||||
const MessageId = Schema.String.pipe(Schema.brand("MessageId"));
|
||||
const TurnId = Schema.String.pipe(Schema.brand("TurnId"));
|
||||
|
||||
const ProviderSessionId = Schema.String.pipe(Schema.brand("ProviderSessionId"));
|
||||
const ProviderThreadId = Schema.String.pipe(Schema.brand("ProviderThreadId"));
|
||||
const ProviderTurnId = Schema.String.pipe(Schema.brand("ProviderTurnId"));
|
||||
const ProviderItemId = Schema.String.pipe(Schema.brand("ProviderItemId"));
|
||||
const ApprovalRequestId = Schema.String.pipe(Schema.brand("ApprovalRequestId"));
|
||||
|
||||
const CheckpointRef = Schema.String.pipe(Schema.brand("CheckpointRef"));
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `ThreadId` is app/orchestration thread identity.
|
||||
- `ProviderThreadId` is provider runtime thread identity.
|
||||
- They are never assigned to each other.
|
||||
- `ProviderSessionId` is internal server/provider routing identity; clients do not send it.
|
||||
- use e.g. `ThreadId.make(randomUUID())` to create new entity ids at the source (e.g. client create thread id and send to server, provider adapter creates the provider thread id from the codex app server etc)
|
||||
|
||||
## 2. Client Commands (Domain Commands)
|
||||
|
||||
All commands are sent through one RPC: `orchestration.dispatchCommand`.
|
||||
|
||||
Output for every command: `DispatchResultSchema = { sequence: number }`.
|
||||
|
||||
### 2.1 Client-Dispatchable Commands
|
||||
|
||||
1. `project.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel?: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
2. `project.meta.update`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- optional `{ title, workspaceRoot, defaultModel, scripts }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `project.delete`
|
||||
|
||||
- Input: `commandId`, `projectId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
4. `thread.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `threadId: ThreadId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
5. `thread.delete`
|
||||
|
||||
- Input: `commandId`, `threadId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
6. `thread.meta.update`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `{ title, model, branch, worktreePath }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
7. `thread.turn.start`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `message`:
|
||||
- `messageId: MessageId`
|
||||
- `role: "user"`
|
||||
- `text: string`
|
||||
- `attachments: ChatAttachment[]` (schema-shared)
|
||||
- `model?: string`
|
||||
- `effort?: string`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
8. `thread.turn.interrupt`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `turnId: TurnId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
9. `thread.approval.respond`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `requestId: ApprovalRequestId`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel"`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
10. `thread.checkpoint.revert`
|
||||
|
||||
- Input: `commandId`, `threadId`, `turnCount: number`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
11. `thread.session.stop`
|
||||
|
||||
- Input: `commandId`, `threadId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
### 2.2 Internal-Only Commands (Not Client Dispatchable)
|
||||
|
||||
1. `thread.session.set`
|
||||
|
||||
- Server-owned projection update for session lifecycle.
|
||||
|
||||
2. `thread.message.assistant.delta`
|
||||
|
||||
- Server-owned incremental assistant content append.
|
||||
|
||||
3. `thread.message.assistant.complete`
|
||||
|
||||
- Server-owned assistant message completion marker.
|
||||
|
||||
4. `thread.turn.diff.complete`
|
||||
|
||||
- Server-owned checkpoint diff summary write.
|
||||
|
||||
5. `thread.activity.append`
|
||||
|
||||
- Server-owned activity feed append.
|
||||
|
||||
## 3. Client RPC (Required)
|
||||
|
||||
These are the required client-facing RPC methods.
|
||||
|
||||
1. `orchestration.getSnapshot`
|
||||
|
||||
- Input: `{}`
|
||||
- Output: `OrchestrationReadModel`
|
||||
|
||||
2. `orchestration.dispatchCommand`
|
||||
|
||||
- Input: `ClientOrchestrationCommand` (`Schema.Union` of all client-dispatchable commands)
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `orchestration.getTurnDiff`
|
||||
|
||||
- Input:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- Output:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
|
||||
4. `orchestration.replayEvents` (optional operational/debug API)
|
||||
|
||||
- Input: `{ fromSequenceExclusive: number }`
|
||||
- Output: `OrchestrationEvent[]`
|
||||
|
||||
### 3.1 RPC To Remove
|
||||
|
||||
Remove from client boundary:
|
||||
|
||||
- `providers.startSession`
|
||||
- `providers.sendTurn`
|
||||
- `providers.interruptTurn`
|
||||
- `providers.respondToRequest`
|
||||
- `providers.stopSession`
|
||||
- `providers.listCheckpoints`
|
||||
- `providers.getCheckpointDiff`
|
||||
- `providers.revertToCheckpoint`
|
||||
|
||||
Rationale:
|
||||
|
||||
- Session/turn/checkpoint control belongs to orchestrator command path.
|
||||
- Snapshot already includes checkpoint summaries (`checkpoints`); only full textual diff needs explicit query RPC.
|
||||
|
||||
## 4. Server Orchestrator Command <-> Event Schemas
|
||||
|
||||
Each command deterministically yields one or more domain events that are persisted to the event store.
|
||||
|
||||
1. `project.create` -> `project.created`
|
||||
2. `project.meta.update` -> `project.meta-updated`
|
||||
3. `project.delete` -> `project.deleted`
|
||||
4. `thread.create` -> `thread.created`
|
||||
5. `thread.delete` -> `thread.deleted`
|
||||
6. `thread.meta.update` -> `thread.meta-updated`
|
||||
7. `thread.turn.start` ->
|
||||
|
||||
- `thread.message-sent` (user message append)
|
||||
- `thread.turn-start-requested`
|
||||
- then (async side effect success) `thread.session-set` + provider-driven message/turn events
|
||||
|
||||
8. `thread.turn.interrupt` -> `thread.turn-interrupt-requested`
|
||||
9. `thread.approval.respond` -> `thread.approval-response-requested`
|
||||
10. `thread.checkpoint.revert` -> `thread.checkpoint-revert-requested` then `thread.reverted`
|
||||
11. `thread.session.stop` -> `thread.session-stop-requested` then `thread.session-set`
|
||||
|
||||
Internal command/event path:
|
||||
|
||||
- `thread.session.set` -> `thread.session-set`
|
||||
- `thread.message.assistant.delta` -> `thread.message-sent` (assistant streaming)
|
||||
- `thread.message.assistant.complete` -> `thread.message-sent` (streaming false)
|
||||
- `thread.turn.diff.complete` -> `thread.turn-diff-completed`
|
||||
- `thread.activity.append` -> `thread.activity-appended`
|
||||
|
||||
## 5. Orchestration Events <-> Generic Provider Events <-> Raw Provider Events
|
||||
|
||||
Required mapping pipeline:
|
||||
|
||||
`Raw Provider Event (adapter-specific)`
|
||||
-> `GenericProviderRuntimeEvent` (provider-agnostic schema)
|
||||
-> `Internal Orchestration Command`
|
||||
-> `Orchestration Domain Event`
|
||||
|
||||
### 5.1 Mapping Table for Codex Adapter
|
||||
|
||||
1. Raw `thread/started`
|
||||
|
||||
- Generic: `thread.started`
|
||||
- Internal command: `thread.session.set` (attach `ProviderThreadId`, status `ready|running`)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
2. Raw `turn/started`
|
||||
|
||||
- Generic: `turn.started`
|
||||
- Internal command: `thread.session.set` (status `running`, active turn)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
3. Raw `item/agentMessage/delta`
|
||||
|
||||
- Generic: `message.delta`
|
||||
- Internal command: `thread.message.assistant.delta`
|
||||
- Domain event: `thread.message-sent` (assistant, streaming)
|
||||
|
||||
4. Raw `item/completed` (agent message)
|
||||
|
||||
- Generic: `message.completed`
|
||||
- Internal command: `thread.message.assistant.complete`
|
||||
- Domain event: `thread.message-sent` (assistant, completed)
|
||||
|
||||
5. Raw `turn/completed`
|
||||
|
||||
- Generic: `turn.completed`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (ready/error)
|
||||
- `thread.activity.append` (optional summary)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
6. Raw approval request
|
||||
|
||||
- Generic: `approval.requested`
|
||||
- Internal command: `thread.activity.append` (typed `requestId`, `requestKind`)
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
7. Raw approval decision ack
|
||||
|
||||
- Generic: `approval.resolved`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
8. Raw tool start/complete
|
||||
|
||||
- Generic: `tool.started` / `tool.completed`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
9. Checkpoint capture (server-produced)
|
||||
|
||||
- Generic: `checkpoint.captured`
|
||||
- Internal command: `thread.turn.diff.complete`
|
||||
- Domain event: `thread.turn-diff-completed`
|
||||
|
||||
10. Raw/runtime error
|
||||
|
||||
- Generic: `runtime.error`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (status `error`)
|
||||
- `thread.activity.append` (`tone=error`)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
## 6. Schema Section (Boundary + Reuse)
|
||||
|
||||
### 6.1 Shared Schemas (contracts package)
|
||||
|
||||
Expose to both web and server:
|
||||
|
||||
- `OrchestrationReadModelSchema`
|
||||
- `ClientOrchestrationCommandSchema`
|
||||
- `OrchestrationEventSchema`
|
||||
- `OrchestrationRpcSchemas` (`getSnapshot`, `dispatchCommand`, `getTurnDiff`, optional replay)
|
||||
- `GenericProviderRuntimeEventSchema` (used for diagnostics/ingestion tests)
|
||||
- Shared message/activity/checkpoint summary schemas used in snapshot
|
||||
|
||||
### 6.2 Server-Internal Schemas
|
||||
|
||||
Not exposed to web:
|
||||
|
||||
- `InternalOrchestrationCommandSchema`
|
||||
- Adapter raw-event schemas and provider-specific payload schemas
|
||||
- Provider session directory records and persistence-only row schemas
|
||||
- Git service cache/query schemas (non-orchestration read model)
|
||||
|
||||
### 6.3 Reuse Requirements
|
||||
|
||||
- Snapshot checkpoint summary schema is source of truth for checkpoint list UI.
|
||||
- `getTurnDiff` response reuses `ThreadId`/turn count brands and textual `diff` only.
|
||||
- Activity schemas are reused for approval/tool/runtime annotations; no separate UI-only structure.
|
||||
- Session schema must include both `threadId: ThreadId` and optional `providerThreadId: ProviderThreadId` (explicitly distinct).
|
||||
|
||||
## 7. Persistence Model (Required)
|
||||
|
||||
This section defines required persisted tables, the canonical persisted event envelope, and required projected/read tables.
|
||||
|
||||
### 7.1 Write-Side Persisted Tables
|
||||
|
||||
1. `orchestration_events` (append-only event store)
|
||||
|
||||
- `sequence: number` (global monotonic sequence, primary key)
|
||||
- `eventId: EventId` (unique)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `streamId: ProjectId | ThreadId` (aggregate stream id)
|
||||
- `streamVersion: number` (per-aggregate monotonic version)
|
||||
- `eventType: OrchestrationEventType`
|
||||
- `occurredAt: IsoDateTime`
|
||||
- `commandId: CommandId | null`
|
||||
- `causationEventId: EventId | null`
|
||||
- `correlationId: CommandId | null`
|
||||
- `actorKind: "client" | "server" | "provider"`
|
||||
- `payload: OrchestrationEventPayload` (type-validated by `eventType`)
|
||||
- `metadata: OrchestrationEventMetadata`
|
||||
|
||||
2. `orchestration_command_receipts` (idempotency + ack replay)
|
||||
|
||||
- `commandId: CommandId` (primary key)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `aggregateId: ProjectId | ThreadId`
|
||||
- `acceptedAt: IsoDateTime`
|
||||
- `resultSequence: number`
|
||||
- `status: "accepted" | "rejected"`
|
||||
- `error: string | null`
|
||||
|
||||
3. `checkpoint_diff_blobs` (large plaintext diffs; separate from summaries)
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- unique key: `(threadId, fromTurnCount, toTurnCount)`
|
||||
|
||||
4. `provider_session_runtime` (server-internal adapter resume state)
|
||||
|
||||
- `providerSessionId: ProviderSessionId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `providerName: string`
|
||||
- `adapterKey: string`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `status: "starting" | "running" | "stopped" | "error"`
|
||||
- `lastSeenAt: IsoDateTime`
|
||||
- `resumeCursor: JsonValue | null` (adapter-specific opaque state)
|
||||
- `runtimePayload: JsonValue | null` (adapter-specific opaque state)
|
||||
|
||||
### 7.2 Canonical Persisted Event Schema
|
||||
|
||||
`OrchestrationPersistedEventSchema` (full envelope):
|
||||
|
||||
```ts
|
||||
type OrchestrationPersistedEvent = {
|
||||
sequence: number;
|
||||
eventId: EventId;
|
||||
aggregateKind: "project" | "thread";
|
||||
streamId: ProjectId | ThreadId;
|
||||
streamVersion: number;
|
||||
eventType: OrchestrationEventType;
|
||||
occurredAt: IsoDateTime;
|
||||
commandId: CommandId | null;
|
||||
causationEventId: EventId | null;
|
||||
correlationId: CommandId | null;
|
||||
actorKind: "client" | "server" | "provider";
|
||||
payload: OrchestrationEventPayload;
|
||||
metadata: {
|
||||
providerSessionId?: ProviderSessionId;
|
||||
providerThreadId?: ProviderThreadId;
|
||||
providerTurnId?: ProviderTurnId;
|
||||
providerItemId?: ProviderItemId;
|
||||
adapterKey?: string;
|
||||
requestId?: ApprovalRequestId;
|
||||
ingestedAt?: IsoDateTime;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `payload` must be schema-discriminated by `eventType`.
|
||||
- provider identifiers only appear in `metadata` and provider-specific payload sub-shapes; they do not replace `ThreadId`.
|
||||
- `streamVersion` is concurrency guard for aggregate writes.
|
||||
|
||||
### 7.3 Required Projected Tables (Read Models)
|
||||
|
||||
1. `projection_projects`
|
||||
|
||||
- `projectId: ProjectId` (primary key)
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel: string | null`
|
||||
- `scripts: ProjectScript[]`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
2. `projection_threads`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `latestTurnId: TurnId | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
3. `projection_thread_messages`
|
||||
|
||||
- `messageId: MessageId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `role: "user" | "assistant" | "system"`
|
||||
- `text: string`
|
||||
- `isStreaming: boolean`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
4. `projection_thread_activities`
|
||||
|
||||
- `activityId: EventId` (primary key; derived from source event)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `tone: "info" | "tool" | "approval" | "error"`
|
||||
- `kind: string`
|
||||
- `summary: string`
|
||||
- `payload: JsonValue`
|
||||
- `createdAt: IsoDateTime`
|
||||
|
||||
5. `projection_thread_sessions`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `status: "idle" | "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"`
|
||||
- `providerName: string | null`
|
||||
- `providerSessionId: ProviderSessionId | null`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `activeTurnId: TurnId | null`
|
||||
- `lastError: string | null`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
6. `projection_thread_turns`
|
||||
|
||||
- `turnId: TurnId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnCount: number`
|
||||
- `status: "running" | "completed" | "interrupted" | "error"`
|
||||
- `userMessageId: MessageId | null`
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `startedAt: IsoDateTime`
|
||||
- `completedAt: IsoDateTime | null`
|
||||
|
||||
7. `projection_checkpoints`
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId`
|
||||
- `checkpointTurnCount: number`
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `status: "ready" | "missing" | "error"`
|
||||
- `files: JsonArray` (typed as file diff summary schema)
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `completedAt: IsoDateTime`
|
||||
- unique key: `(threadId, checkpointTurnCount)`
|
||||
|
||||
8. `projection_pending_approvals`
|
||||
|
||||
- `requestId: ApprovalRequestId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `status: "pending" | "resolved"`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel" | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `resolvedAt: IsoDateTime | null`
|
||||
|
||||
9. `projection_state`
|
||||
|
||||
- `projector: string` (primary key; e.g. `threads`, `messages`, `sessions`)
|
||||
- `lastAppliedSequence: number`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
Projection consistency rules:
|
||||
|
||||
- Every projector applies read-model row updates and `projection_state.lastAppliedSequence` in the same database transaction.
|
||||
- Optional debug field on projection rows: `lastEventSequence: number` (not required for correctness).
|
||||
|
||||
### 7.4 Snapshot and RPC Requirements
|
||||
|
||||
1. `orchestration.getSnapshot` is fully served from projection tables and returns `snapshotSequence: number`.
|
||||
2. Snapshot must include `projects[]` from `projection_projects`.
|
||||
3. Thread snapshot must include `checkpoints[]` from `projection_checkpoints`:
|
||||
|
||||
- `turnId: TurnId`
|
||||
- `completedAt: IsoDateTime`
|
||||
- `status`
|
||||
- `files[]` (`path`, `kind`, `additions`, `deletions`)
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `assistantMessageId?: MessageId`
|
||||
- `checkpointTurnCount: number`
|
||||
|
||||
4. Client does not require `listCheckpoints` RPC:
|
||||
|
||||
- checkpoint list comes from snapshot projections
|
||||
- full diff text comes from `orchestration.getTurnDiff` backed by `checkpoint_diff_blobs`
|
||||
|
||||
5. Provider session identity is not a client routing key:
|
||||
|
||||
- client acts on `ThreadId`
|
||||
- server resolves provider session internally via `projection_thread_sessions`
|
||||
|
||||
6. `snapshotSequence` is derived from `projection_state`:
|
||||
|
||||
- if snapshot depends on multiple projectors, use the minimum `lastAppliedSequence` across those projectors.
|
||||
|
||||
7. Event subscription handoff contract:
|
||||
|
||||
- client performs `getSnapshot` and reads `snapshotSequence`
|
||||
- client subscribes/replays with `fromSequenceExclusive = snapshotSequence`
|
||||
- server guarantees no gap between snapshot visibility and subsequent event stream from that sequence.
|
||||
|
||||
### 7.5 External Derived State (Non-Orchestration)
|
||||
|
||||
1. Current git/worktree state is not projected from orchestration events.
|
||||
2. If persisted, it belongs in a separate git cache/read model (for example `git_state_cache`) owned by a git service.
|
||||
3. Orchestration may embed git metadata only when captured as a domain fact (for example checkpoint metadata at turn completion).
|
||||
4. Any RPC for current git status should be outside orchestration RPC (for example `git.getThreadState`).
|
||||
|
||||
### 7.6 Existing Repository Placement
|
||||
|
||||
1. `ProjectsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_projects` plus orchestration command dispatch for writes.
|
||||
- Must not bypass command->event append path for mutations.
|
||||
|
||||
2. `CheckpointsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_checkpoints` plus `checkpoint_diff_blobs` (or git-service on-demand diff implementation).
|
||||
- Represents the same concept as prior `turn_diff_summary`; canonical naming is `checkpoint`.
|
||||
- Must not be an independent source of truth outside orchestration events.
|
||||
|
||||
3. `ProviderSessionsRepository`
|
||||
|
||||
- Fits as server-internal runtime persistence on top of `provider_session_runtime`, with domain-visible state projected into `projection_thread_sessions`.
|
||||
- Not part of client RPC/domain aggregate boundary.
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
## Small things
|
||||
|
||||
- [ ] Plan mode
|
||||
- [ ] Submitting new messages should scroll to bottom
|
||||
- [ ] 1 click copy in codeblocks
|
||||
- [x] Pasting/adding images to submit with prompts
|
||||
- [ ] Only show last 10 threads for a given project
|
||||
@@ -14,7 +12,7 @@
|
||||
- [x] "Response" bar should ONLY appear on work completed
|
||||
- [x] "Response" bar should ONLY appear above the FINAL message in a series
|
||||
- [x] Reduce noise of tool calls (combine "command run" and "command completed", make tool calls a "box" with limited # of calls shown at a time, etc)
|
||||
- [x] Insta focus input on new thread creation
|
||||
- [ ] Insta focus input on new thread creation
|
||||
- [ ] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [x] Making new thread should auto-focus input box
|
||||
- [x] Threads should be scrolled to bottom on open (they currently start near top and "scroll down" after rendering, it's jank)
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
dist-electron/
|
||||
.electron-runtime/
|
||||
@@ -8,22 +8,20 @@
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"start": "electron dist-electron/main.js",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron": "40.6.0"
|
||||
"electron": "33.4.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@types/node": "^22.10.2",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"wait-on": "^8.0.2"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 279 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 313 KiB |
@@ -1,10 +1,7 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
import waitOn from "wait-on";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
|
||||
@@ -17,54 +14,18 @@ await waitOn({
|
||||
],
|
||||
});
|
||||
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
try {
|
||||
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
}
|
||||
|
||||
killChildTree("TERM");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
process.once("SIGTERM", () => {
|
||||
void shutdown(143);
|
||||
});
|
||||
process.once("SIGHUP", () => {
|
||||
void shutdown(129);
|
||||
child.on("exit", (code) => {
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
@@ -1,144 +0,0 @@
|
||||
// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (replaceResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertResult = spawnSync("plutil", ["-insert", key, "-string", value, plistPath], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (insertResult.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
|
||||
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
|
||||
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
|
||||
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
|
||||
|
||||
const resourcesDir = join(appBundlePath, "Contents", "Resources");
|
||||
copyFileSync(iconPath, join(resourcesDir, "icon.icns"));
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function buildMacLauncher(electronBinaryPath) {
|
||||
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
const expectedMetadata = {
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
sourceAppBundlePath,
|
||||
sourceAppMtimeMs: statSync(sourceAppBundlePath).mtimeMs,
|
||||
iconMtimeMs: statSync(iconPath).mtimeMs,
|
||||
};
|
||||
|
||||
const currentMetadata = readJson(metadataPath);
|
||||
if (
|
||||
existsSync(targetBinaryPath) &&
|
||||
currentMetadata &&
|
||||
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
|
||||
) {
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
}
|
||||
|
||||
export function resolveElectronPath() {
|
||||
const require = createRequire(import.meta.url);
|
||||
const electronBinaryPath = require("electron");
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.kill(process.pid, signal);
|
||||
return;
|
||||
}
|
||||
process.exit(code ?? 0);
|
||||
});
|
||||
+14
-292
@@ -5,16 +5,7 @@ import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
dialog,
|
||||
ipcMain,
|
||||
Menu,
|
||||
type MenuItemConstructorOptions,
|
||||
protocol,
|
||||
shell,
|
||||
} from "electron";
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
@@ -25,13 +16,11 @@ const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
|
||||
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
|
||||
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
@@ -41,238 +30,6 @@ let backendWsUrl = "";
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
let desktopProtocolRegistered = false;
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
function resolveAppRoot(): string {
|
||||
if (!app.isPackaged) {
|
||||
return ROOT_DIR;
|
||||
}
|
||||
return app.getAppPath();
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
if (!app.isPackaged) {
|
||||
return resolveAppRoot();
|
||||
}
|
||||
return os.homedir();
|
||||
}
|
||||
|
||||
function resolveDesktopStaticDir(): string | null {
|
||||
const appRoot = resolveAppRoot();
|
||||
const candidates = [
|
||||
path.join(appRoot, "apps/server/dist/client"),
|
||||
path.join(appRoot, "apps/web/dist"),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(path.join(candidate, "index.html"))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
if (normalizedPath.includes("..")) {
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
|
||||
const resolvedPath = path.join(staticRoot, requestedPath);
|
||||
|
||||
if (path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = path.join(resolvedPath, "index.html");
|
||||
if (fs.existsSync(nestedIndex)) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function registerDesktopProtocol(): void {
|
||||
if (isDevelopment || desktopProtocolRegistered) return;
|
||||
|
||||
const staticRoot = resolveDesktopStaticDir();
|
||||
if (!staticRoot) {
|
||||
throw new Error(
|
||||
"Desktop static bundle missing. Build apps/server (with bundled client) first.",
|
||||
);
|
||||
}
|
||||
|
||||
const staticRootResolved = path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
|
||||
const fallbackIndex = path.join(staticRootResolved, "index.html");
|
||||
|
||||
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
|
||||
try {
|
||||
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url);
|
||||
|
||||
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
|
||||
if (isAssetRequest) {
|
||||
callback({ error: -6 });
|
||||
return;
|
||||
}
|
||||
callback({ path: fallbackIndex });
|
||||
return;
|
||||
}
|
||||
|
||||
callback({ path: resolvedCandidate });
|
||||
} catch {
|
||||
callback({ path: fallbackIndex });
|
||||
}
|
||||
});
|
||||
|
||||
desktopProtocolRegistered = true;
|
||||
}
|
||||
|
||||
function dispatchMenuAction(action: string): void {
|
||||
const existingWindow =
|
||||
BrowserWindow.getFocusedWindow() ?? mainWindow ?? BrowserWindow.getAllWindows()[0];
|
||||
const targetWindow = existingWindow ?? createWindow();
|
||||
if (!existingWindow) {
|
||||
mainWindow = targetWindow;
|
||||
}
|
||||
|
||||
const send = () => {
|
||||
if (targetWindow.isDestroyed()) return;
|
||||
targetWindow.webContents.send(MENU_ACTION_CHANNEL, action);
|
||||
if (!targetWindow.isVisible()) {
|
||||
targetWindow.show();
|
||||
}
|
||||
targetWindow.focus();
|
||||
};
|
||||
|
||||
if (targetWindow.webContents.isLoadingMainFrame()) {
|
||||
targetWindow.webContents.once("did-finish-load", send);
|
||||
return;
|
||||
}
|
||||
|
||||
send();
|
||||
}
|
||||
|
||||
function configureApplicationMenu(): void {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
template.push({
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services" },
|
||||
{ type: "separator" },
|
||||
{ role: "hide" },
|
||||
{ role: "hideOthers" },
|
||||
{ role: "unhide" },
|
||||
{ type: "separator" },
|
||||
{ role: "quit" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
template.push(
|
||||
{
|
||||
label: "File",
|
||||
submenu: [
|
||||
...(process.platform === "darwin"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => dispatchMenuAction("open-settings"),
|
||||
},
|
||||
{ type: "separator" as const },
|
||||
]),
|
||||
{ role: process.platform === "darwin" ? "close" : "quit" },
|
||||
],
|
||||
},
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
}
|
||||
|
||||
function resolveResourcePath(fileName: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, "../resources", fileName),
|
||||
path.join(process.resourcesPath, "resources", fileName),
|
||||
path.join(process.resourcesPath, fileName),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
return resolveResourcePath(`icon.${ext}`);
|
||||
}
|
||||
|
||||
function configureAppIdentity(): void {
|
||||
app.setName(APP_DISPLAY_NAME);
|
||||
app.setAboutPanelOptions({
|
||||
applicationName: APP_DISPLAY_NAME,
|
||||
});
|
||||
|
||||
if (process.platform === "win32") {
|
||||
app.setAppUserModelId(APP_USER_MODEL_ID);
|
||||
}
|
||||
|
||||
if (process.platform === "darwin" && app.dock) {
|
||||
const iconPath = resolveIconPath("png");
|
||||
if (iconPath) {
|
||||
app.dock.setIcon(iconPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -319,14 +76,13 @@ function scheduleBackendRestart(reason: string): void {
|
||||
function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!fs.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
if (!fs.existsSync(BACKEND_ENTRY)) {
|
||||
scheduleBackendRestart(`missing server entry at ${BACKEND_ENTRY}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [backendEntry], {
|
||||
cwd: resolveBackendCwd(),
|
||||
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
||||
cwd: ROOT_DIR,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
@@ -368,10 +124,10 @@ function stopBackend(): void {
|
||||
backendProcess = null;
|
||||
if (!child) return;
|
||||
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
if (!child.killed) {
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
if (!child.killed) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 2_000).unref();
|
||||
@@ -448,13 +204,6 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
if (process.platform === "darwin") return {}; // macOS uses .icns from app bundle
|
||||
const ext = process.platform === "win32" ? "ico" : "png";
|
||||
const iconPath = resolveIconPath(ext);
|
||||
return iconPath ? { icon: iconPath } : {};
|
||||
}
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
@@ -463,8 +212,6 @@ function createWindow(): BrowserWindow {
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
@@ -476,13 +223,6 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
|
||||
window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
});
|
||||
@@ -491,7 +231,10 @@ function createWindow(): BrowserWindow {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`);
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
}
|
||||
void window.loadFile(WEB_ENTRY);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -503,8 +246,6 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
@@ -522,9 +263,6 @@ app.on("before-quit", () => {
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
void bootstrap();
|
||||
|
||||
app.on("activate", () => {
|
||||
@@ -539,19 +277,3 @@ app.on("window-all-closed", () => {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
process.on("SIGINT", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
stopBackend();
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -1,28 +1,16 @@
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
listener(action);
|
||||
};
|
||||
|
||||
ipcRenderer.on(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
|
||||
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
|
||||
showContextMenu: (items: { id: string; label: string }[]) =>
|
||||
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
|
||||
});
|
||||
@@ -1,344 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Option, Schedule, Scope, Stream } from "effect";
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
function initializeGitWorkspace(cwd: string) {
|
||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
||||
runGit(cwd, ["add", "."]);
|
||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
}
|
||||
|
||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||
try {
|
||||
runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
|
||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||
}
|
||||
|
||||
function waitFor<A>(
|
||||
read: Effect.Effect<A, unknown>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<A, never>;
|
||||
function waitFor<A, B extends A>(
|
||||
read: Effect.Effect<A, unknown>,
|
||||
predicate: (value: A) => value is B,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<B, never>;
|
||||
function waitFor<A>(
|
||||
read: Effect.Effect<A, unknown>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
): Effect.Effect<A, never> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
|
||||
const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
|
||||
|
||||
return read.pipe(
|
||||
Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
|
||||
Effect.retry({
|
||||
schedule: retrySchedule,
|
||||
times: maxRetries,
|
||||
while: (error) => error === RETRY_SIGNAL,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
error === RETRY_SIGNAL ? new Error(`Timed out waiting for ${description}.`) : error,
|
||||
),
|
||||
Effect.orDie,
|
||||
);
|
||||
}
|
||||
|
||||
export interface OrchestrationIntegrationHarness {
|
||||
readonly rootDir: string;
|
||||
readonly workspaceDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly adapterHarness: TestProviderAdapterHarness;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
readonly checkpointStore: CheckpointStore["Service"];
|
||||
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
|
||||
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
|
||||
readonly waitForThread: (
|
||||
threadId: string,
|
||||
predicate: (thread: OrchestrationThread) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<OrchestrationThread, never>;
|
||||
readonly waitForDomainEvent: (
|
||||
predicate: (event: OrchestrationEvent) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
|
||||
readonly waitForPendingApproval: (
|
||||
requestId: string,
|
||||
predicate: (row: {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
}) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
const sleep = (ms: number) =>
|
||||
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
const adapterHarness = yield* makeTestProviderAdapterHarness;
|
||||
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const stateDir = path.join(rootDir, "state");
|
||||
const dbPath = path.join(stateDir, "state.sqlite");
|
||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
initializeGitWorkspace(workspaceDir);
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
);
|
||||
const reactor = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
);
|
||||
const snapshotQuery = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
);
|
||||
const providerService = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
);
|
||||
const checkpointStore = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
);
|
||||
const checkpointRepository = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
);
|
||||
const pendingApprovalRepository = yield* Effect.promise(() =>
|
||||
runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
);
|
||||
|
||||
const scope = yield* Effect.promise(() => Effect.runPromise(Scope.make("sequential")));
|
||||
yield* Effect.promise(() => runtime.runPromise(reactor.start.pipe(Scope.provide(scope))));
|
||||
yield* sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
),
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
);
|
||||
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
yield* Effect.promise(() => runtime.runPromise(providerService.stopAll()));
|
||||
yield* Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void)));
|
||||
yield* Effect.promise(() => runtime.dispose());
|
||||
yield* Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -1,368 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
import {
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "../src/provider/Errors.ts";
|
||||
import type {
|
||||
ProviderAdapterShape,
|
||||
ProviderThreadSnapshot,
|
||||
ProviderThreadTurnSnapshot,
|
||||
} from "../src/provider/Services/ProviderAdapter.ts";
|
||||
|
||||
export interface TestTurnResponse {
|
||||
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
interface SessionState {
|
||||
readonly session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
turnCount: number;
|
||||
readonly queuedResponses: Array<TestTurnResponse>;
|
||||
readonly rollbackCalls: Array<number>;
|
||||
}
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly queueTurnResponse: (
|
||||
sessionId: string,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly getRollbackCalls: (sessionId: string) => ReadonlyArray<number>;
|
||||
readonly getApprovalResponses: (sessionId: string) => ReadonlyArray<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>;
|
||||
}
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(sessionId: string): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
sessionId,
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(sessionId: string): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(sessionId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<string, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const approvalResponsesBySession = new Map<
|
||||
string,
|
||||
Array<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
|
||||
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: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
sessionCount += 1;
|
||||
const sessionId = ProviderSessionId.makeUnsafe(`test-session-${sessionCount}`);
|
||||
const threadId = ProviderThreadId.makeUnsafe(`test-thread-${sessionCount}`);
|
||||
const createdAt = nowIso();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: PROVIDER,
|
||||
status: "ready",
|
||||
threadId,
|
||||
cwd: input.cwd,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(sessionId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId,
|
||||
turns: [],
|
||||
},
|
||||
turnCount: 0,
|
||||
queuedResponses: queuedResponsesForNextSession.splice(0),
|
||||
rollbackCalls: [],
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.sessionId);
|
||||
if (!state) {
|
||||
return yield* missingSessionEffect(input.sessionId);
|
||||
}
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = ProviderTurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: `No queued turn response for session ${input.sessionId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
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: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
if (Object.hasOwn(rawEvent, "threadId")) {
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
}
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
}
|
||||
|
||||
const runtimeEvent = rawEvent as ProviderRuntimeEvent;
|
||||
if (runtimeEvent.type === "message.delta") {
|
||||
assistantDeltas.push(runtimeEvent.delta);
|
||||
}
|
||||
if (runtimeEvent.type === "turn.completed") {
|
||||
deferredTurnCompletedEvents.push(runtimeEvent);
|
||||
continue;
|
||||
}
|
||||
|
||||
yield* emit(runtimeEvent);
|
||||
}
|
||||
|
||||
if (response.mutateWorkspace && state.session.cwd) {
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
|
||||
}
|
||||
|
||||
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: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
status: "completed",
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
yield* emit(completedEvent);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
sessionId,
|
||||
_turnId,
|
||||
) => (sessions.has(sessionId) ? Effect.void : missingSessionEffect(sessionId));
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
sessions.has(sessionId)
|
||||
? Effect.sync(() => {
|
||||
const existing = approvalResponsesBySession.get(sessionId) ?? [];
|
||||
existing.push({
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
approvalResponsesBySession.set(sessionId, existing);
|
||||
})
|
||||
: missingSessionEffect(sessionId);
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (sessionId) =>
|
||||
Effect.sync(() => {
|
||||
sessions.delete(sessionId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (sessionId) =>
|
||||
Effect.succeed(sessions.has(sessionId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (sessionId) => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(sessionId);
|
||||
}
|
||||
return Effect.succeed(state.snapshot);
|
||||
};
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
sessionId,
|
||||
numTurns,
|
||||
) => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(sessionId);
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: 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: PROVIDER,
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
sessionId: string,
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
|
||||
Effect.sync(() => sessions.get(sessionId)).pipe(
|
||||
Effect.flatMap((state) =>
|
||||
state
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(sessionNotFound(sessionId)),
|
||||
),
|
||||
);
|
||||
|
||||
const queueTurnResponseForNextSession = (
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, never> =>
|
||||
Effect.sync(() => {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
const getRollbackCalls = (sessionId: string): ReadonlyArray<number> => {
|
||||
const state = sessions.get(sessionId);
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return [...state.rollbackCalls];
|
||||
};
|
||||
|
||||
const getApprovalResponses = (
|
||||
sessionId: string,
|
||||
): ReadonlyArray<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}> => {
|
||||
const responses = approvalResponsesBySession.get(sessionId);
|
||||
if (!responses) {
|
||||
return [];
|
||||
}
|
||||
return [...responses];
|
||||
};
|
||||
|
||||
return {
|
||||
adapter,
|
||||
queueTurnResponse,
|
||||
queueTurnResponseForNextSession,
|
||||
getRollbackCalls,
|
||||
getApprovalResponses,
|
||||
} satisfies TestProviderAdapterHarness;
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = ProviderSessionId.makeUnsafe("fixture-session");
|
||||
const THREAD_ID = ProviderThreadId.makeUnsafe("fixture-thread");
|
||||
const TURN_ID = ProviderTurnId.makeUnsafe("fixture-turn");
|
||||
const REQUEST_ID = ApprovalRequestId.makeUnsafe("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<ProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const codexTurnTextFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Done.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
{
|
||||
type: "approval.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
decision: "accept",
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
@@ -1,742 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Option } from "effect";
|
||||
|
||||
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
|
||||
import {
|
||||
gitRefExists,
|
||||
gitShowFileAtRef,
|
||||
makeOrchestrationIntegrationHarness,
|
||||
type OrchestrationIntegrationHarness,
|
||||
} from "./OrchestrationEngineHarness.integration.ts";
|
||||
import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts";
|
||||
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_SESSION_ID = asProviderSessionId("fixture-session");
|
||||
const FIXTURE_THREAD_ID = asProviderThreadId("fixture-thread");
|
||||
const FIXTURE_TURN_ID = asProviderTurnId("fixture-turn");
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
const sleep = (ms: number) =>
|
||||
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
|
||||
function waitForSync<A>(
|
||||
read: () => A,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 3000,
|
||||
): Effect.Effect<A, never> {
|
||||
return Effect.gen(function* () {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
while (true) {
|
||||
const value = read();
|
||||
if (predicate(value)) {
|
||||
return value;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
return yield* Effect.die(new Error(`Timed out waiting for ${description}.`));
|
||||
}
|
||||
yield* sleep(10);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function runtimeBase(eventId: string, createdAt: string) {
|
||||
return {
|
||||
eventId: asEventId(eventId),
|
||||
provider: "codex" as const,
|
||||
sessionId: FIXTURE_SESSION_ID,
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
function withHarness<A, E>(use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness,
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
}
|
||||
|
||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = nowIso();
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: harness.workspaceDir,
|
||||
createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
const startTurn = (input: {
|
||||
readonly harness: OrchestrationIntegrationHarness;
|
||||
readonly commandId: string;
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe(input.commandId),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId(input.messageId),
|
||||
role: "user",
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
const turnResponse: TestTurnResponse = {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-single-1", "2026-02-24T10:00:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Single turn response.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-single-3", "2026-02-24T10:00:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession(turnResponse);
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-single",
|
||||
messageId: "msg-user-single",
|
||||
text: "Say hello",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.streaming === false,
|
||||
) &&
|
||||
entry.checkpoints.length === 1,
|
||||
);
|
||||
assert.equal(thread.checkpoints[0]?.status, "ready");
|
||||
assert.equal(thread.checkpoints[0]?.checkpointTurnCount, 1);
|
||||
|
||||
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
|
||||
threadId: THREAD_ID,
|
||||
});
|
||||
assert.equal(checkpointRows.length, 1);
|
||||
assert.equal(checkpointRows[0]?.checkpointTurnCount, 1);
|
||||
assert.equal(checkpointRows[0]?.status, "ready");
|
||||
assert.deepEqual(checkpointRows[0]?.files, []);
|
||||
|
||||
yield* harness.waitForDomainEvent((event) => event.type === "thread.turn-diff-completed");
|
||||
|
||||
const ref0 = checkpointRefForThreadTurn(THREAD_ID, 0);
|
||||
const ref1 = checkpointRefForThreadTurn(THREAD_ID, 1);
|
||||
assert.equal(gitRefExists(harness.workspaceDir, ref0), true);
|
||||
assert.equal(gitRefExists(harness.workspaceDir, ref1), true);
|
||||
assert.equal(gitShowFileAtRef(harness.workspaceDir, ref0, "README.md"), "v1\n");
|
||||
assert.equal(gitShowFileAtRef(harness.workspaceDir, ref1, "README.md"), "v1\n");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-multi-3", "2026-02-24T10:01:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-multi-4", "2026-02-24T10:01:00.300Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-5", "2026-02-24T10:01:00.400Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-multi-1",
|
||||
messageId: "msg-user-multi-1",
|
||||
text: "Make first edit",
|
||||
});
|
||||
|
||||
const firstTurnThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.checkpoints.length === 1 && entry.session?.providerSessionId !== null,
|
||||
);
|
||||
const sessionId = firstTurnThread.session?.providerSessionId;
|
||||
assert.equal(sessionId !== null, true);
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-8", "2026-02-24T10:02:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-multi-2",
|
||||
messageId: "msg-user-multi-2",
|
||||
text: "Make second edit",
|
||||
});
|
||||
|
||||
const secondTurnThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 2),
|
||||
);
|
||||
const secondCheckpoint = secondTurnThread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === 2,
|
||||
);
|
||||
assert.equal(
|
||||
secondCheckpoint?.files.some((file) => file.path === "README.md"),
|
||||
true,
|
||||
);
|
||||
|
||||
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
|
||||
threadId: THREAD_ID,
|
||||
});
|
||||
assert.deepEqual(
|
||||
checkpointRows.map((row) => row.checkpointTurnCount),
|
||||
[1, 2],
|
||||
);
|
||||
|
||||
const incrementalDiff = yield* harness.checkpointStore.diffCheckpoints({
|
||||
cwd: harness.workspaceDir,
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
});
|
||||
assert.equal(incrementalDiff.includes("README.md"), true);
|
||||
|
||||
const fullDiff = yield* harness.checkpointStore.diffCheckpoints({
|
||||
cwd: harness.workspaceDir,
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
});
|
||||
assert.equal(fullDiff.includes("README.md"), true);
|
||||
|
||||
assert.equal(
|
||||
gitShowFileAtRef(
|
||||
harness.workspaceDir,
|
||||
checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||
"README.md",
|
||||
),
|
||||
"v2\n",
|
||||
);
|
||||
assert.equal(
|
||||
gitShowFileAtRef(
|
||||
harness.workspaceDir,
|
||||
checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
"README.md",
|
||||
),
|
||||
"v3\n",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("tracks approval requests and resolves pending approvals on user response", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Approve command execution",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-approval-3", "2026-02-24T10:03:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-approval",
|
||||
messageId: "msg-user-approval",
|
||||
text: "Run command needing approval",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "approval.requested"),
|
||||
);
|
||||
assert.equal(
|
||||
thread.activities.some((activity) => activity.kind === "approval.requested"),
|
||||
true,
|
||||
);
|
||||
|
||||
const pendingRow = yield* harness.waitForPendingApproval(
|
||||
"req-approval-1",
|
||||
(row) => row.status === "pending" && row.decision === null,
|
||||
);
|
||||
assert.equal(pendingRow.status, "pending");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const resolvedRow = yield* harness.waitForPendingApproval(
|
||||
"req-approval-1",
|
||||
(row) => row.status === "resolved" && row.decision === "accept",
|
||||
);
|
||||
assert.equal(resolvedRow.status, "resolved");
|
||||
assert.equal(resolvedRow.decision, "accept");
|
||||
|
||||
const providerSessionId = thread.session?.providerSessionId ?? "test-session-1";
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness.getApprovalResponses(providerSessionId),
|
||||
(responses) => responses.length === 1,
|
||||
"provider approval response",
|
||||
);
|
||||
assert.equal(approvalResponses.length, 1);
|
||||
assert.equal(approvalResponses[0]?.requestId, "req-approval-1");
|
||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("records failed turn runtime state and checkpoint status as error", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Partial output before failure.\n",
|
||||
},
|
||||
{
|
||||
type: "runtime.error",
|
||||
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
message: "Sandbox command failed.",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "failed",
|
||||
errorMessage: "Sandbox command failed.",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-failure",
|
||||
messageId: "msg-user-failure",
|
||||
text: "Run risky command",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.lastError === "Sandbox command failed." &&
|
||||
entry.activities.some((activity) => activity.kind === "runtime.error") &&
|
||||
entry.checkpoints.length === 1,
|
||||
);
|
||||
assert.equal(thread.session?.status, "error");
|
||||
assert.equal(thread.checkpoints[0]?.status, "error");
|
||||
|
||||
const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({
|
||||
threadId: THREAD_ID,
|
||||
checkpointTurnCount: 1,
|
||||
});
|
||||
assert.equal(Option.isSome(checkpointRow), true);
|
||||
if (Option.isSome(checkpointRow)) {
|
||||
assert.equal(checkpointRow.value.status, "error");
|
||||
}
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
|
||||
true,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("reverts to an earlier checkpoint and trims checkpoint projections + git refs", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
}),
|
||||
});
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-revert-1",
|
||||
messageId: "msg-user-revert-1",
|
||||
text: "First edit",
|
||||
});
|
||||
|
||||
const firstTurnThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.session?.providerSessionId !== null && entry.checkpoints.length === 1,
|
||||
);
|
||||
const sessionId = firstTurnThread.session?.providerSessionId;
|
||||
assert.equal(sessionId !== null, true);
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
}),
|
||||
});
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-revert-2",
|
||||
messageId: "msg-user-revert-2",
|
||||
text: "Second edit",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.activities.some((activity) => activity.turnId === "turn-2"),
|
||||
8000,
|
||||
);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted");
|
||||
const revertedThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
|
||||
);
|
||||
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
|
||||
assert.deepEqual(
|
||||
revertedThread.messages.map((message) => ({ role: message.role, text: message.text })),
|
||||
[
|
||||
{ role: "user", text: "First edit" },
|
||||
{ role: "assistant", text: "Updated README to v2.\n" },
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
revertedThread.activities.some((activity) => activity.turnId === "turn-2"),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
revertedThread.activities.some(
|
||||
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.started",
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
revertedThread.activities.some(
|
||||
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed",
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n");
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness.getRollbackCalls(sessionId), [1]);
|
||||
|
||||
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
|
||||
threadId: THREAD_ID,
|
||||
});
|
||||
assert.equal(checkpointRows.length, 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live(
|
||||
"appends checkpoint.revert.failed activity when revert is requested without an active session",
|
||||
() =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 0,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity) =>
|
||||
activity.kind === "checkpoint.revert.failed" &&
|
||||
typeof activity.payload === "object" &&
|
||||
activity.payload !== null,
|
||||
),
|
||||
);
|
||||
const failureActivity = thread.activities.find(
|
||||
(activity) => activity.kind === "checkpoint.revert.failed",
|
||||
);
|
||||
assert.equal(failureActivity !== undefined, true);
|
||||
assert.equal(
|
||||
String(
|
||||
(failureActivity?.payload as { readonly detail?: string } | undefined)?.detail,
|
||||
).includes("No active provider session"),
|
||||
true,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,287 +0,0 @@
|
||||
import type { ProviderRuntimeEvent, ProviderSessionId } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.ts";
|
||||
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
|
||||
import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
type TestTurnResponse,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import {
|
||||
codexTurnApprovalFixture,
|
||||
codexTurnToolFixture,
|
||||
codexTurnTextFixture,
|
||||
} from "./fixtures/providerRuntime.ts";
|
||||
|
||||
const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const cwd = yield* fs.makeTempDirectory();
|
||||
yield* fs.writeFileString(pathService.join(cwd, "README.md"), "v1\n");
|
||||
return cwd;
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
interface IntegrationFixture {
|
||||
readonly cwd: string;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
}
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness;
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(harness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
|
||||
return {
|
||||
cwd,
|
||||
harness,
|
||||
layer,
|
||||
} satisfies IntegrationFixture;
|
||||
});
|
||||
|
||||
const collectEventsDuring = <A, E, R>(
|
||||
stream: Stream.Stream<ProviderRuntimeEvent>,
|
||||
count: number,
|
||||
action: Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
yield* Stream.runForEach(stream, (event) => Queue.offer(queue, event).pipe(Effect.asVoid)).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* action;
|
||||
|
||||
return yield* Effect.forEach(
|
||||
Array.from({ length: count }, () => undefined),
|
||||
() => Queue.take(queue),
|
||||
{ discard: false },
|
||||
);
|
||||
});
|
||||
|
||||
const runTurn = (input: {
|
||||
readonly provider: ProviderServiceShape;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly userText: string;
|
||||
readonly response: TestTurnResponse;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.sessionId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
input.provider.sendTurn({
|
||||
sessionId: input.sessionId,
|
||||
input: input.userText,
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
userText: "hello",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
observedEvents.map((event) => event.type),
|
||||
codexTurnTextFixture.map((event) => event.type),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
userText: "make a small change",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
observedEvents.map((event) => event.type),
|
||||
codexTurnToolFixture.map((event) => event.type),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
firstTurnEvents.map((event) => event.type),
|
||||
codexTurnToolFixture.map((event) => event.type),
|
||||
);
|
||||
|
||||
const secondTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
secondTurnEvents.map((event) => event.type),
|
||||
codexTurnApprovalFixture.map((event) => event.type),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
sessionId: session.sessionId,
|
||||
numTurns: 1,
|
||||
});
|
||||
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.sessionId);
|
||||
assert.deepEqual(rollbackCalls, [1]);
|
||||
|
||||
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
|
||||
assert.equal(readme, "v3\n");
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -11,31 +11,22 @@
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.mjs",
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "4.0.0-beta.10",
|
||||
"@effect/sql-sqlite-bun": "4.0.0-beta.10",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "4.0.0-beta.10",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/vitest": "4.0.0-beta.10",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@
|
||||
* Copies the built web app into dist/client/ so the published npm package
|
||||
* includes the web UI. This runs as a post-build step.
|
||||
*/
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const webDist = path.resolve(__dirname, "../../web/dist");
|
||||
const target = path.resolve(__dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
@@ -1,68 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
|
||||
|
||||
describe("parseTurnDiffFilesFromUnifiedDiff", () => {
|
||||
it("returns empty list for empty diff", () => {
|
||||
expect(parseTurnDiffFilesFromUnifiedDiff("")).toEqual([]);
|
||||
});
|
||||
|
||||
it("parses per-file additions and deletions", () => {
|
||||
const diff = [
|
||||
"diff --git a/a.txt b/a.txt",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/a.txt",
|
||||
"+++ b/a.txt",
|
||||
"@@ -1,2 +1,3 @@",
|
||||
" one",
|
||||
"-two",
|
||||
"+two updated",
|
||||
"+three",
|
||||
"diff --git a/src/b.ts b/src/b.ts",
|
||||
"index 3333333..4444444 100644",
|
||||
"--- a/src/b.ts",
|
||||
"+++ b/src/b.ts",
|
||||
"@@ -3,2 +3,0 @@",
|
||||
"-old",
|
||||
"-stale",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
|
||||
{ path: "a.txt", additions: 2, deletions: 1 },
|
||||
{ path: "src/b.ts", additions: 0, deletions: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses rename-only diffs with zero line changes", () => {
|
||||
const diff = [
|
||||
"diff --git a/src/old.ts b/src/new.ts",
|
||||
"similarity index 100%",
|
||||
"rename from src/old.ts",
|
||||
"rename to src/new.ts",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
|
||||
{ path: "src/new.ts", additions: 0, deletions: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes CRLF input before parsing", () => {
|
||||
const diff = [
|
||||
"diff --git a/a.txt b/a.txt",
|
||||
"index 1111111..2222222 100644",
|
||||
"--- a/a.txt",
|
||||
"+++ b/a.txt",
|
||||
"@@ -1 +1,2 @@",
|
||||
"-one",
|
||||
"+one updated",
|
||||
"+two",
|
||||
"",
|
||||
].join("\r\n");
|
||||
|
||||
expect(parseTurnDiffFilesFromUnifiedDiff(diff)).toEqual([
|
||||
{ path: "a.txt", additions: 2, deletions: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,27 +0,0 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs";
|
||||
|
||||
export interface TurnDiffFileSummary {
|
||||
readonly path: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}
|
||||
|
||||
export function parseTurnDiffFilesFromUnifiedDiff(
|
||||
diff: string,
|
||||
): ReadonlyArray<TurnDiffFileSummary> {
|
||||
const normalized = diff.replace(/\r\n/g, "\n").trim();
|
||||
if (normalized.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parsedPatches = parsePatchFiles(normalized);
|
||||
const files = parsedPatches.flatMap((patch) =>
|
||||
patch.files.map((file) => ({
|
||||
path: file.name,
|
||||
additions: file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0),
|
||||
deletions: file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0),
|
||||
})),
|
||||
);
|
||||
|
||||
return files.toSorted((left, right) => left.path.localeCompare(right.path));
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import { GitCommandError } from "../git/Errors.ts";
|
||||
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
*/
|
||||
export class CheckpointUnavailableError extends Schema.TaggedErrorClass<CheckpointUnavailableError>()(
|
||||
"CheckpointUnavailableError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
turnCount: Schema.Number,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointInvariantError - Inconsistent provider/filesystem/catalog state.
|
||||
*/
|
||||
export class CheckpointInvariantError extends Schema.TaggedErrorClass<CheckpointInvariantError>()(
|
||||
"CheckpointInvariantError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Checkpoint invariant violation in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type CheckpointStoreError =
|
||||
| GitCommandError
|
||||
| CheckpointInvariantError
|
||||
| CheckpointUnavailableError;
|
||||
|
||||
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
|
||||
@@ -1,186 +0,0 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
|
||||
|
||||
function makeSnapshot(input: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string | null;
|
||||
readonly checkpointTurnCount: number;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
id: input.projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
latestTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
session: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("CheckpointDiffQueryLive", () => {
|
||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
||||
const diffCheckpointsCalls: Array<{
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
}> = [];
|
||||
|
||||
const snapshot = makeSnapshot({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: ({ checkpointRef }) =>
|
||||
Effect.sync(() => {
|
||||
hasCheckpointRefCalls.push(checkpointRef);
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(snapshot),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
|
||||
expect(diffCheckpointsCalls).toEqual([
|
||||
{
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
diff: "diff patch",
|
||||
});
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: () => Effect.succeed(""),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
} satisfies OrchestrationReadModel),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
),
|
||||
).rejects.toThrow("Thread 'thread-missing' not found.");
|
||||
});
|
||||
});
|
||||
@@ -1,169 +0,0 @@
|
||||
import {
|
||||
OrchestrationGetTurnDiffResult,
|
||||
type OrchestrationGetFullThreadDiffInput,
|
||||
type OrchestrationGetFullThreadDiffResult,
|
||||
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
|
||||
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import {
|
||||
CheckpointDiffQuery,
|
||||
type CheckpointDiffQueryShape,
|
||||
} from "../Services/CheckpointDiffQuery.ts";
|
||||
|
||||
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff: "",
|
||||
};
|
||||
if (!isTurnDiffResult(emptyDiff)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: "Computed turn diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
return emptyDiff;
|
||||
}
|
||||
|
||||
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
|
||||
if (!thread) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: `Thread '${input.threadId}' not found.`,
|
||||
});
|
||||
}
|
||||
|
||||
const maxTurnCount = thread.checkpoints.reduce(
|
||||
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
if (input.toTurnCount > maxTurnCount) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${maxTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const workspaceCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: snapshot.projects,
|
||||
});
|
||||
if (!workspaceCwd) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: `Workspace path missing for thread '${input.threadId}' when computing turn diff.`,
|
||||
});
|
||||
}
|
||||
|
||||
const fromCheckpointRef =
|
||||
input.fromTurnCount === 0
|
||||
? checkpointRefForThreadTurn(input.threadId, 0)
|
||||
: thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!fromCheckpointRef) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.fromTurnCount,
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.fromTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const toCheckpointRef = thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
|
||||
)?.checkpointRef;
|
||||
if (!toCheckpointRef) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const [fromExists, toExists] = yield* Effect.all(
|
||||
[
|
||||
checkpointStore.hasCheckpointRef({
|
||||
cwd: workspaceCwd,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
}),
|
||||
checkpointStore.hasCheckpointRef({
|
||||
cwd: workspaceCwd,
|
||||
checkpointRef: toCheckpointRef,
|
||||
}),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!fromExists) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.fromTurnCount,
|
||||
detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!toExists) {
|
||||
return yield* new CheckpointUnavailableError({
|
||||
threadId: input.threadId,
|
||||
turnCount: input.toTurnCount,
|
||||
detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const diff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: workspaceCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
});
|
||||
|
||||
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: input.fromTurnCount,
|
||||
toTurnCount: input.toTurnCount,
|
||||
diff,
|
||||
};
|
||||
if (!isTurnDiffResult(turnDiff)) {
|
||||
return yield* new CheckpointInvariantError({
|
||||
operation,
|
||||
detail: "Computed turn diff result does not satisfy contract schema.",
|
||||
});
|
||||
}
|
||||
|
||||
return turnDiff;
|
||||
});
|
||||
|
||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
) =>
|
||||
getTurnDiff({
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
||||
|
||||
return {
|
||||
getTurnDiff,
|
||||
getFullThreadDiff,
|
||||
} satisfies CheckpointDiffQueryShape;
|
||||
});
|
||||
|
||||
export const CheckpointDiffQueryLive = Layer.effect(CheckpointDiffQuery, make);
|
||||
@@ -1,282 +0,0 @@
|
||||
/**
|
||||
* CheckpointStoreLive - Filesystem checkpoint store adapter layer.
|
||||
*
|
||||
* Implements hidden Git-ref checkpoint capture/restore directly with
|
||||
* Effect-native child process execution (`effect/unstable/process`).
|
||||
*
|
||||
* This layer owns filesystem/Git interactions only; it does not persist
|
||||
* checkpoint metadata and does not coordinate provider rollback semantics.
|
||||
*
|
||||
* @module CheckpointStoreLive
|
||||
*/
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { GitCommandError } from "../../git/Errors.ts";
|
||||
import { GitServiceLive } from "../../git/Layers/GitService.ts";
|
||||
import { GitService } from "../../git/Services/GitService.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const git = yield* GitService;
|
||||
|
||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.hasHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "HEAD"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const resolveCheckpointCommit = (
|
||||
cwd: string,
|
||||
checkpointRef: CheckpointRef,
|
||||
): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveCheckpointCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.isGitRepository",
|
||||
cwd,
|
||||
args: ["rev-parse", "--is-inside-work-tree"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||
(tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
env: commitEnv,
|
||||
});
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
|
||||
const writeTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
env: commitEnv,
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
env: commitEnv,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
});
|
||||
}),
|
||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
Effect.fail(
|
||||
new CheckpointInvariantError({
|
||||
operation: "CheckpointStore.captureCheckpoint",
|
||||
detail: "Failed to capture checkpoint.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||
Effect.map((commit) => commit !== null),
|
||||
);
|
||||
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.restoreCheckpoint";
|
||||
|
||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||
|
||||
if (!commitOid && input.fallbackToHead === true) {
|
||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||
}
|
||||
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.diffCheckpoints";
|
||||
|
||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||
const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
|
||||
|
||||
if (!fromCommitOid && input.fallbackFromToHead === true) {
|
||||
const headCommit = yield* resolveHeadCommit(input.cwd);
|
||||
if (headCommit) {
|
||||
fromCommitOid = headCommit;
|
||||
}
|
||||
}
|
||||
|
||||
if (!fromCommitOid || !toCommitOid) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git diff",
|
||||
cwd: input.cwd,
|
||||
detail: "Checkpoint ref is unavailable for diff operation.",
|
||||
});
|
||||
}
|
||||
|
||||
const result = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
});
|
||||
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
isGitRepository,
|
||||
captureCheckpoint,
|
||||
hasCheckpointRef,
|
||||
restoreCheckpoint,
|
||||
diffCheckpoints,
|
||||
deleteCheckpointRefs,
|
||||
} satisfies CheckpointStoreShape;
|
||||
});
|
||||
|
||||
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
|
||||
Layer.provideMerge(GitServiceLive),
|
||||
);
|
||||
@@ -1,49 +0,0 @@
|
||||
/**
|
||||
* CheckpointDiffQuery - Query interface for computed checkpoint diffs.
|
||||
*
|
||||
* Provides read-only diff operations across checkpoint snapshots used by
|
||||
* orchestration APIs.
|
||||
*
|
||||
* @module CheckpointDiffQuery
|
||||
*/
|
||||
import type {
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
OrchestrationGetFullThreadDiffResult,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointServiceError } from "../Errors.ts";
|
||||
|
||||
/**
|
||||
* CheckpointDiffQueryShape - Service API for checkpoint diff queries.
|
||||
*/
|
||||
export interface CheckpointDiffQueryShape {
|
||||
/**
|
||||
* Read the patch diff for a single turn checkpoint transition.
|
||||
*
|
||||
* Verifies checkpoint availability in both projection state and filesystem.
|
||||
*/
|
||||
readonly getTurnDiff: (
|
||||
input: OrchestrationGetTurnDiffInput,
|
||||
) => Effect.Effect<OrchestrationGetTurnDiffResult, CheckpointServiceError>;
|
||||
|
||||
/**
|
||||
* Read the full patch diff across a thread range of checkpoints.
|
||||
*
|
||||
* Delegates to turn diff with `fromTurnCount = 0`.
|
||||
*/
|
||||
readonly getFullThreadDiff: (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
||||
*/
|
||||
export class CheckpointDiffQuery extends ServiceMap.Service<
|
||||
CheckpointDiffQuery,
|
||||
CheckpointDiffQueryShape
|
||||
>()("checkpointing/CheckpointDiffQuery") {}
|
||||
@@ -1,100 +0,0 @@
|
||||
/**
|
||||
* CheckpointStore - Repository interface for filesystem-backed workspace checkpoints.
|
||||
*
|
||||
* Owns hidden Git-ref checkpoint capture/restore and diff computation for a
|
||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||
* and does not coordinate provider conversation rollback.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||
* domain errors for checkpoint storage operations.
|
||||
*
|
||||
* @module CheckpointStore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointStoreError } from "../Errors.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
export interface CaptureCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
}
|
||||
|
||||
export interface RestoreCheckpointInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRef: CheckpointRef;
|
||||
readonly fallbackToHead?: boolean;
|
||||
}
|
||||
|
||||
export interface DiffCheckpointsInput {
|
||||
readonly cwd: string;
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteCheckpointRefsInput {
|
||||
readonly cwd: string;
|
||||
readonly checkpointRefs: ReadonlyArray<CheckpointRef>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointStoreShape - Service API for checkpoint capture/restore and diff access.
|
||||
*/
|
||||
export interface CheckpointStoreShape {
|
||||
/**
|
||||
* Check whether cwd is inside a Git worktree.
|
||||
*/
|
||||
readonly isGitRepository: (cwd: string) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Capture a checkpoint commit and store it at the provided checkpoint ref.
|
||||
*
|
||||
* Uses an isolated temporary Git index and writes a hidden ref.
|
||||
*/
|
||||
readonly captureCheckpoint: (
|
||||
input: CaptureCheckpointInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Check whether a checkpoint ref exists.
|
||||
*/
|
||||
readonly hasCheckpointRef: (
|
||||
input: Omit<RestoreCheckpointInput, "fallbackToHead">,
|
||||
) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Restore workspace/staging state to a checkpoint.
|
||||
*
|
||||
* Optionally falls back to current `HEAD` when the checkpoint ref is missing.
|
||||
*/
|
||||
readonly restoreCheckpoint: (
|
||||
input: RestoreCheckpointInput,
|
||||
) => Effect.Effect<boolean, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Compute patch diff between two checkpoint refs.
|
||||
*
|
||||
* Can optionally treat missing "from" ref as `HEAD`.
|
||||
*/
|
||||
readonly diffCheckpoints: (
|
||||
input: DiffCheckpointsInput,
|
||||
) => Effect.Effect<string, CheckpointStoreError>;
|
||||
|
||||
/**
|
||||
* Delete the provided checkpoint refs.
|
||||
*
|
||||
* Best-effort delete: missing refs are tolerated.
|
||||
*/
|
||||
readonly deleteCheckpointRefs: (
|
||||
input: DeleteCheckpointRefsInput,
|
||||
) => Effect.Effect<void, CheckpointStoreError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
||||
*/
|
||||
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
"checkpointing/CheckpointStore",
|
||||
) {}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { Encoding } from "effect";
|
||||
import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
|
||||
return CheckpointRef.makeUnsafe(
|
||||
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveThreadWorkspaceCwd(input: {
|
||||
readonly thread: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly worktreePath: string | null;
|
||||
};
|
||||
readonly projects: ReadonlyArray<{
|
||||
readonly id: ProjectId;
|
||||
readonly workspaceRoot: string;
|
||||
}>;
|
||||
}): string | undefined {
|
||||
const worktreeCwd = input.thread.worktreePath ?? undefined;
|
||||
if (worktreeCwd) {
|
||||
return worktreeCwd;
|
||||
}
|
||||
|
||||
return input.projects.find((project) => project.id === input.thread.projectId)?.workspaceRoot;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
@@ -8,8 +7,6 @@ import {
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
@@ -46,36 +43,6 @@ function createSendTurnHarness() {
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
||||
"requireSession",
|
||||
)
|
||||
.mockReturnValue(context);
|
||||
const sendRequest = vi.spyOn(
|
||||
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
|
||||
"sendRequest",
|
||||
);
|
||||
const updateSession = vi
|
||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -146,47 +113,13 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push({
|
||||
method: event.method,
|
||||
kind: event.kind,
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
||||
throw new Error("cwd missing");
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
provider: "codex",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]).toEqual({
|
||||
method: "session/startFailed",
|
||||
kind: "error",
|
||||
message: "cwd missing",
|
||||
});
|
||||
} finally {
|
||||
processCwd.mockRestore();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
it("sends text and image user input items to turn/start", async () => {
|
||||
const { manager, context, requireSession, sendRequest, updateSession } =
|
||||
createSendTurnHarness();
|
||||
|
||||
const result = await manager.sendTurn({
|
||||
sessionId: asSessionId("sess_1"),
|
||||
sessionId: "sess_1",
|
||||
input: "Inspect this image",
|
||||
attachments: [
|
||||
{
|
||||
@@ -204,9 +137,6 @@ describe("sendTurn", () => {
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turnId: "turn_1",
|
||||
resumeCursor: {
|
||||
threadId: "thread_1",
|
||||
},
|
||||
});
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
@@ -228,9 +158,6 @@ describe("sendTurn", () => {
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "running",
|
||||
activeTurnId: "turn_1",
|
||||
resumeCursor: {
|
||||
threadId: "thread_1",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -238,7 +165,7 @@ describe("sendTurn", () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
sessionId: asSessionId("sess_1"),
|
||||
sessionId: "sess_1",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
@@ -266,96 +193,8 @@ describe("sendTurn", () => {
|
||||
|
||||
await expect(
|
||||
manager.sendTurn({
|
||||
sessionId: asSessionId("sess_1"),
|
||||
sessionId: "sess_1",
|
||||
}),
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread checkpoint control", () => {
|
||||
it("reads thread turns from thread/read", async () => {
|
||||
const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asSessionId("sess_1"));
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads thread turns from flat thread/read responses", async () => {
|
||||
const { manager, context, sendRequest } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asSessionId("sess_1"));
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rolls back turns via thread/rollback and resets session running state", async () => {
|
||||
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.rollbackThread(asSessionId("sess_1"), 2);
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
||||
threadId: "thread_1",
|
||||
numTurns: 2,
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,22 +3,16 @@ import { randomUUID } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import readline from "node:readline";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderItemId,
|
||||
import type {
|
||||
ProviderApprovalDecision,
|
||||
ProviderEvent,
|
||||
ProviderRequestKind,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
normalizeModelSlug,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -30,13 +24,13 @@ interface PendingRequest {
|
||||
}
|
||||
|
||||
interface PendingApprovalRequest {
|
||||
requestId: ApprovalRequestId;
|
||||
requestId: string;
|
||||
jsonRpcId: string | number;
|
||||
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
|
||||
requestKind: ProviderRequestKind;
|
||||
threadId?: ProviderThreadId;
|
||||
turnId?: ProviderTurnId;
|
||||
itemId?: ProviderItemId;
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
itemId?: string;
|
||||
}
|
||||
|
||||
interface CodexSessionContext {
|
||||
@@ -44,7 +38,7 @@ interface CodexSessionContext {
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
output: readline.Interface;
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
pendingApprovals: Map<string, PendingApprovalRequest>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
@@ -71,16 +65,6 @@ interface JsonRpcNotification {
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export interface CodexThreadTurnSnapshot {
|
||||
id: ProviderTurnId;
|
||||
items: unknown[];
|
||||
}
|
||||
|
||||
export interface CodexThreadSnapshot {
|
||||
threadId: ProviderThreadId;
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -149,53 +133,45 @@ export interface CodexAppServerManagerEvents {
|
||||
}
|
||||
|
||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
|
||||
private readonly sessions = new Map<string, CodexSessionContext>();
|
||||
|
||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
|
||||
const sessionId = randomUUID();
|
||||
const now = new Date().toISOString();
|
||||
let context: CodexSessionContext | undefined;
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: input.cwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd: input.cwd,
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
const context: CodexSessionContext = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
try {
|
||||
const resolvedCwd = input.cwd ?? process.cwd();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: resolvedCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
||||
const codexHomePath = input.codexHomePath;
|
||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
||||
cwd: resolvedCwd,
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
context = {
|
||||
session,
|
||||
child,
|
||||
output,
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
this.sessions.set(sessionId, context);
|
||||
this.attachProcessListeners(context);
|
||||
|
||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||
|
||||
await this.sendRequest(context, "initialize", {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
@@ -221,16 +197,15 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
...sessionOverrides,
|
||||
experimentalRawEvents: false,
|
||||
};
|
||||
const resumeThreadId = readResumeThreadId(input);
|
||||
|
||||
let threadOpenMethod: "thread/start" | "thread/resume" = "thread/start";
|
||||
let threadOpenResponse: unknown;
|
||||
if (resumeThreadId) {
|
||||
if (input.resumeThreadId) {
|
||||
try {
|
||||
threadOpenMethod = "thread/resume";
|
||||
threadOpenResponse = await this.sendRequest(context, "thread/resume", {
|
||||
...sessionOverrides,
|
||||
threadId: resumeThreadId,
|
||||
threadId: input.resumeThreadId,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isRecoverableThreadResumeError(error)) {
|
||||
@@ -241,7 +216,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.emitLifecycleEvent(
|
||||
context,
|
||||
"session/threadResumeFallback",
|
||||
`Could not resume thread ${resumeThreadId}; started a new thread instead.`,
|
||||
`Could not resume thread ${input.resumeThreadId}; started a new thread instead.`,
|
||||
);
|
||||
threadOpenResponse = await this.sendRequest(context, "thread/start", threadStartParams);
|
||||
}
|
||||
@@ -251,41 +226,27 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
const threadOpenRecord = this.readObject(threadOpenResponse);
|
||||
const threadIdRaw =
|
||||
const threadId =
|
||||
this.readString(this.readObject(threadOpenRecord, "thread"), "id") ??
|
||||
this.readString(threadOpenRecord, "threadId");
|
||||
if (!threadIdRaw) {
|
||||
if (!threadId) {
|
||||
throw new Error(`${threadOpenMethod} response did not include a thread id.`);
|
||||
}
|
||||
const threadId = ProviderThreadId.makeUnsafe(threadIdRaw);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
threadId,
|
||||
resumeCursor: { threadId },
|
||||
});
|
||||
this.emitLifecycleEvent(context, "session/ready", `Connected to thread ${threadId}`);
|
||||
return { ...context.session };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Failed to start Codex session.";
|
||||
if (context) {
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "session/startFailed",
|
||||
message,
|
||||
});
|
||||
}
|
||||
this.updateSession(context, {
|
||||
status: "error",
|
||||
lastError: message,
|
||||
});
|
||||
this.emitErrorEvent(context, "session/startFailed", message);
|
||||
this.stopSession(sessionId);
|
||||
throw new Error(message, { cause: error });
|
||||
}
|
||||
}
|
||||
@@ -319,7 +280,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
const turnStartParams: {
|
||||
threadId: ProviderThreadId;
|
||||
threadId: string;
|
||||
input: Array<
|
||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
||||
>;
|
||||
@@ -340,26 +301,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const response = await this.sendRequest(context, "turn/start", turnStartParams);
|
||||
|
||||
const turn = this.readObject(this.readObject(response), "turn");
|
||||
const turnIdRaw = this.readString(turn, "id");
|
||||
if (!turnIdRaw) {
|
||||
const turnId = this.readString(turn, "id");
|
||||
if (!turnId) {
|
||||
throw new Error("turn/start response did not include a turn id.");
|
||||
}
|
||||
const turnId = ProviderTurnId.makeUnsafe(turnIdRaw);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
resumeCursor: context.session.resumeCursor ?? { threadId: context.session.threadId },
|
||||
});
|
||||
|
||||
return {
|
||||
threadId: context.session.threadId,
|
||||
turnId,
|
||||
resumeCursor: context.session.resumeCursor ?? { threadId: context.session.threadId },
|
||||
};
|
||||
}
|
||||
|
||||
async interruptTurn(sessionId: ProviderSessionId, turnId?: ProviderTurnId): Promise<void> {
|
||||
async interruptTurn(sessionId: string, turnId?: string): Promise<void> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const effectiveTurnId = turnId ?? context.session.activeTurnId;
|
||||
|
||||
@@ -373,47 +331,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
async readThread(sessionId: ProviderSessionId): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/read", {
|
||||
threadId,
|
||||
includeTurns: true,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/read", response);
|
||||
}
|
||||
|
||||
async rollbackThread(
|
||||
sessionId: ProviderSessionId,
|
||||
numTurns: number,
|
||||
): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
throw new Error("numTurns must be an integer >= 1.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/rollback", {
|
||||
threadId,
|
||||
numTurns,
|
||||
});
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/rollback", response);
|
||||
}
|
||||
|
||||
async respondToRequest(
|
||||
sessionId: ProviderSessionId,
|
||||
requestId: ApprovalRequestId,
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
decision: ProviderApprovalDecision,
|
||||
): Promise<void> {
|
||||
const context = this.requireSession(sessionId);
|
||||
@@ -431,7 +351,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
@@ -450,7 +370,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
stopSession(sessionId: ProviderSessionId): void {
|
||||
stopSession(sessionId: string): void {
|
||||
const context = this.sessions.get(sessionId);
|
||||
if (!context) {
|
||||
return;
|
||||
@@ -485,7 +405,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}));
|
||||
}
|
||||
|
||||
hasSession(sessionId: ProviderSessionId): boolean {
|
||||
hasSession(sessionId: string): boolean {
|
||||
return this.sessions.has(sessionId);
|
||||
}
|
||||
|
||||
@@ -495,7 +415,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
}
|
||||
|
||||
private requireSession(sessionId: ProviderSessionId): CodexSessionContext {
|
||||
private requireSession(sessionId: string): CodexSessionContext {
|
||||
const context = this.sessions.get(sessionId);
|
||||
if (!context) {
|
||||
throw new Error(`Unknown session: ${sessionId}`);
|
||||
@@ -606,7 +526,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
: undefined;
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: randomUUID(),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
@@ -620,9 +540,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
if (notification.method === "thread/started") {
|
||||
const threadId = toProviderThreadId(
|
||||
this.readString(this.readObject(notification.params)?.thread, "id"),
|
||||
);
|
||||
const threadId = this.readString(this.readObject(notification.params)?.thread, "id");
|
||||
if (threadId) {
|
||||
this.updateSession(context, { threadId });
|
||||
}
|
||||
@@ -630,9 +548,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "turn/started") {
|
||||
const turnId = toProviderTurnId(
|
||||
this.readString(this.readObject(notification.params)?.turn, "id"),
|
||||
);
|
||||
const turnId = this.readString(this.readObject(notification.params)?.turn, "id");
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
@@ -666,9 +582,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
||||
const route = this.readRouteFields(request.params);
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
let requestId: string | undefined;
|
||||
if (requestKind) {
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
requestId = randomUUID();
|
||||
const pendingRequest: PendingApprovalRequest = {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -685,7 +601,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: randomUUID(),
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
@@ -780,7 +696,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: randomUUID(),
|
||||
kind: "session",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
@@ -792,7 +708,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId: context.session.sessionId,
|
||||
@@ -826,35 +742,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
|
||||
const responseRecord = this.readObject(response);
|
||||
const thread = this.readObject(responseRecord, "thread");
|
||||
const threadIdRaw =
|
||||
this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
|
||||
if (!threadIdRaw) {
|
||||
throw new Error(`${method} response did not include a thread id.`);
|
||||
}
|
||||
const threadId = ProviderThreadId.makeUnsafe(threadIdRaw);
|
||||
|
||||
const turnsRaw =
|
||||
this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
|
||||
const turnId = ProviderTurnId.makeUnsafe(turnIdRaw);
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
items,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
threadId,
|
||||
turns,
|
||||
};
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
@@ -888,26 +775,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
private readRouteFields(params: unknown): {
|
||||
threadId?: ProviderThreadId;
|
||||
turnId?: ProviderTurnId;
|
||||
itemId?: ProviderItemId;
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
itemId?: string;
|
||||
} {
|
||||
const route: {
|
||||
threadId?: ProviderThreadId;
|
||||
turnId?: ProviderTurnId;
|
||||
itemId?: ProviderItemId;
|
||||
threadId?: string;
|
||||
turnId?: string;
|
||||
itemId?: string;
|
||||
} = {};
|
||||
|
||||
const threadId = toProviderThreadId(
|
||||
const threadId =
|
||||
this.readString(params, "threadId") ??
|
||||
this.readString(this.readObject(params, "thread"), "id"),
|
||||
);
|
||||
const turnId = toProviderTurnId(
|
||||
this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id"),
|
||||
);
|
||||
const itemId = toProviderItemId(
|
||||
this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id"),
|
||||
);
|
||||
this.readString(this.readObject(params, "thread"), "id");
|
||||
const turnId =
|
||||
this.readString(params, "turnId") ?? this.readString(this.readObject(params, "turn"), "id");
|
||||
const itemId =
|
||||
this.readString(params, "itemId") ?? this.readString(this.readObject(params, "item"), "id");
|
||||
|
||||
if (threadId) {
|
||||
route.threadId = threadId;
|
||||
@@ -939,16 +823,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return target as Record<string, unknown>;
|
||||
}
|
||||
|
||||
private readArray(value: unknown, key?: string): unknown[] | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
? value
|
||||
: value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)[key]
|
||||
: undefined;
|
||||
return Array.isArray(target) ? target : undefined;
|
||||
}
|
||||
|
||||
private readString(value: unknown, key: string): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
@@ -967,35 +841,3 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return typeof candidate === "boolean" ? candidate : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function brandIfNonEmpty<T extends string>(
|
||||
value: string | undefined,
|
||||
maker: (value: string) => T,
|
||||
): T | undefined {
|
||||
const normalized = value?.trim();
|
||||
return normalized?.length ? maker(normalized) : undefined;
|
||||
}
|
||||
|
||||
function toProviderThreadId(value: string | undefined): ProviderThreadId | undefined {
|
||||
return brandIfNonEmpty(value, ProviderThreadId.makeUnsafe);
|
||||
}
|
||||
|
||||
function readResumeThreadId(input: ProviderSessionStartInput): ProviderThreadId | undefined {
|
||||
if (
|
||||
!input.resumeCursor ||
|
||||
typeof input.resumeCursor !== "object" ||
|
||||
Array.isArray(input.resumeCursor)
|
||||
) {
|
||||
return input.resumeThreadId;
|
||||
}
|
||||
const rawThreadId = (input.resumeCursor as Record<string, unknown>).threadId;
|
||||
return typeof rawThreadId === "string" ? toProviderThreadId(rawThreadId) : input.resumeThreadId;
|
||||
}
|
||||
|
||||
function toProviderTurnId(value: string | undefined): ProviderTurnId | undefined {
|
||||
return brandIfNonEmpty(value, ProviderTurnId.makeUnsafe);
|
||||
}
|
||||
|
||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||
return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
CommitMessageGenerationInput,
|
||||
CommitMessageGenerationResult,
|
||||
PrContentGenerationInput,
|
||||
PrContentGenerationResult,
|
||||
TextGenerationService,
|
||||
} from "./coreServices";
|
||||
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
|
||||
|
||||
type ProcessRunner = (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>;
|
||||
|
||||
const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
|
||||
const COMMIT_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
subject: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["subject", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
const PR_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["title", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
throw new Error("Codex returned a non-object commit message payload.");
|
||||
}
|
||||
const record = raw as Record<string, unknown>;
|
||||
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
|
||||
const body = typeof record.body === "string" ? record.body : "";
|
||||
if (subject.length === 0) {
|
||||
throw new Error("Codex returned an empty commit subject.");
|
||||
}
|
||||
return { subject, body };
|
||||
}
|
||||
|
||||
function parsePrOutput(raw: unknown): { title: string; body: string } {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
throw new Error("Codex returned a non-object PR payload.");
|
||||
}
|
||||
const record = raw as Record<string, unknown>;
|
||||
const title = typeof record.title === "string" ? record.title.trim() : "";
|
||||
const body = typeof record.body === "string" ? record.body.trim() : "";
|
||||
if (title.length === 0 || body.length === 0) {
|
||||
throw new Error("Codex returned an invalid PR title/body payload.");
|
||||
}
|
||||
return { title, body };
|
||||
}
|
||||
|
||||
function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
async function writeTempFile(prefix: string, content: string): Promise<string> {
|
||||
const filePath = path.join(os.tmpdir(), `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
|
||||
await fs.writeFile(filePath, content, "utf8");
|
||||
return filePath;
|
||||
}
|
||||
|
||||
async function safeUnlink(filePath: string): Promise<void> {
|
||||
try {
|
||||
await fs.unlink(filePath);
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||
if (withoutTrailingPeriod.length === 0) {
|
||||
return "Update project files";
|
||||
}
|
||||
|
||||
if (withoutTrailingPeriod.length <= 72) {
|
||||
return withoutTrailingPeriod;
|
||||
}
|
||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||
}
|
||||
|
||||
function sanitizePrTitle(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
if (singleLine.length > 0) {
|
||||
return singleLine;
|
||||
}
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
async function runCodexJson<T>({
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
parse,
|
||||
run,
|
||||
}: {
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: object;
|
||||
parse: (raw: unknown) => T;
|
||||
run: ProcessRunner;
|
||||
}): Promise<T> {
|
||||
const schemaPath = await writeTempFile("codex-schema", JSON.stringify(outputSchemaJson));
|
||||
let outputPath: string | null = null;
|
||||
|
||||
try {
|
||||
outputPath = await writeTempFile("codex-output", "");
|
||||
await run(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
timeoutMs: 180_000,
|
||||
stdin: prompt,
|
||||
},
|
||||
);
|
||||
|
||||
const rawOutput = (await fs.readFile(outputPath, "utf8")).trim();
|
||||
if (rawOutput.length === 0) {
|
||||
throw new Error("Codex returned an empty response.");
|
||||
}
|
||||
|
||||
let parsedJson: unknown;
|
||||
try {
|
||||
parsedJson = JSON.parse(rawOutput);
|
||||
} catch {
|
||||
throw new Error("Codex returned invalid JSON output.");
|
||||
}
|
||||
|
||||
return parse(parsedJson);
|
||||
} finally {
|
||||
await Promise.all([safeUnlink(schemaPath), ...(outputPath ? [safeUnlink(outputPath)] : [])]);
|
||||
}
|
||||
}
|
||||
|
||||
interface CodexTextGeneratorDeps {
|
||||
runProcess?: ProcessRunner;
|
||||
}
|
||||
|
||||
export class CodexTextGenerator implements TextGenerationService {
|
||||
private readonly run: ProcessRunner;
|
||||
|
||||
constructor(deps: CodexTextGeneratorDeps = {}) {
|
||||
this.run = deps.runProcess ?? runProcess;
|
||||
}
|
||||
|
||||
async generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult> {
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
"Return a JSON object with keys: subject, body.",
|
||||
"Rules:",
|
||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||
"- body can be empty string or short bullet points",
|
||||
"- capture the primary user-visible or developer-visible change",
|
||||
"",
|
||||
`Branch: ${input.branch ?? "(detached)"}`,
|
||||
"",
|
||||
"Staged files:",
|
||||
limitSection(input.stagedSummary, 6_000),
|
||||
"",
|
||||
"Staged patch:",
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
const generated = await runCodexJson({
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parseCommitOutput(raw),
|
||||
run: this.run,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
async generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult> {
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
"",
|
||||
"Commits:",
|
||||
limitSection(input.commitSummary, 12_000),
|
||||
"",
|
||||
"Diff stat:",
|
||||
limitSection(input.diffSummary, 12_000),
|
||||
"",
|
||||
"Diff patch:",
|
||||
limitSection(input.diffPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
const generated = await runCodexJson({
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parsePrOutput(raw),
|
||||
run: this.run,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* ServerConfig and NetService - Runtime configuration services.
|
||||
*
|
||||
* Defines process-level server configuration and networking helpers used by
|
||||
* startup and runtime layers.
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import * as Net from "node:net";
|
||||
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
export type RuntimeMode = "web" | "desktop";
|
||||
|
||||
/**
|
||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||
*/
|
||||
export interface ServerConfigShape {
|
||||
readonly mode: RuntimeMode;
|
||||
readonly port: number;
|
||||
readonly host: string | undefined;
|
||||
readonly cwd: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly stateDir: string;
|
||||
readonly staticDir: string | undefined;
|
||||
readonly devUrl: URL | undefined;
|
||||
readonly noBrowser: boolean;
|
||||
readonly authToken: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServerConfig - Service tag for server runtime configuration.
|
||||
*/
|
||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||
"server/ServerConfig",
|
||||
) {}
|
||||
|
||||
// Helpers
|
||||
|
||||
export class NetError extends Data.TaggedError("NetError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
/**
|
||||
* NetServiceShape - Networking helper operations used during startup.
|
||||
*/
|
||||
export interface NetServiceShape {
|
||||
/**
|
||||
* Resolve an available listening port, preferring the provided port first.
|
||||
*
|
||||
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
|
||||
*/
|
||||
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* NetService - Service tag for startup networking helpers.
|
||||
*/
|
||||
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
|
||||
"server/NetService",
|
||||
) {
|
||||
static readonly layer = Layer.succeed(NetService, {
|
||||
findAvailablePort: (preferred) =>
|
||||
Effect.callback<number, NetError>((resume) => {
|
||||
let fallbackServer: Net.Server | null = null;
|
||||
const server = Net.createServer();
|
||||
server.listen(preferred, () => {
|
||||
server.close(() => resume(Effect.succeed(preferred)));
|
||||
});
|
||||
server.on("error", () => {
|
||||
const fallback = Net.createServer();
|
||||
fallback.listen(0, () => {
|
||||
const addr = fallback.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
fallback.close(() => {
|
||||
resume(
|
||||
port > 0
|
||||
? Effect.succeed(port)
|
||||
: Effect.fail(new NetError({ message: "Could not find an available port." })),
|
||||
);
|
||||
});
|
||||
});
|
||||
fallback.on("error", (cause) => {
|
||||
resume(
|
||||
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
|
||||
);
|
||||
});
|
||||
fallbackServer = fallback;
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
server.close();
|
||||
fallbackServer?.close();
|
||||
});
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveStaticDir = Effect.fn(function* () {
|
||||
const { join, resolve } = yield* Path.Path;
|
||||
const { stat } = yield* FileSystem.FileSystem;
|
||||
const bundledClient = resolve(join(import.meta.dirname, "client"));
|
||||
const bundledStat = yield* stat(join(bundledClient, "index.html")).pipe(
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
);
|
||||
if (bundledStat) {
|
||||
return bundledClient;
|
||||
}
|
||||
|
||||
const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
|
||||
const monorepoStat = yield* stat(join(monorepoClient, "index.html")).pipe(
|
||||
Effect.orElseSucceed(() => undefined),
|
||||
);
|
||||
if (monorepoStat) {
|
||||
return monorepoClient;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
subject: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationInput {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult>;
|
||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
if (result) {
|
||||
process.env.PATH = result;
|
||||
}
|
||||
} catch {
|
||||
// Silently ignore — keep default PATH
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
GitCoreService,
|
||||
checkoutGitBranch,
|
||||
createGitBranch,
|
||||
createGitWorktree,
|
||||
initGitRepo,
|
||||
listGitBranches,
|
||||
pullGitBranch,
|
||||
removeGitWorktree,
|
||||
runTerminalCommand,
|
||||
} from "./git";
|
||||
|
||||
// ── Helpers ──
|
||||
|
||||
/** Run a raw git command for test setup (not under test). */
|
||||
async function git(cwd: string, command: string): Promise<string> {
|
||||
const result = await runTerminalCommand({
|
||||
command: `git ${command}`,
|
||||
cwd,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
throw new Error(`git ${command} failed: ${result.stderr}`);
|
||||
}
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
/** Create a disposable temp directory that cleans up automatically. */
|
||||
async function makeTmpDir() {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "git-test-"));
|
||||
return {
|
||||
path: dir,
|
||||
[Symbol.asyncDispose]: async () => {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Create a repo with an initial commit so branches work. */
|
||||
async function initRepoWithCommit(cwd: string): Promise<void> {
|
||||
await initGitRepo({ cwd });
|
||||
await git(cwd, "config user.email '[email protected]'");
|
||||
await git(cwd, "config user.name 'Test'");
|
||||
await writeFile(path.join(cwd, "README.md"), "# test\n");
|
||||
await git(cwd, "add .");
|
||||
await git(cwd, "commit -m 'initial commit'");
|
||||
}
|
||||
|
||||
async function commitWithDate(
|
||||
cwd: string,
|
||||
fileName: string,
|
||||
fileContents: string,
|
||||
dateIsoString: string,
|
||||
message: string,
|
||||
): Promise<void> {
|
||||
await writeFile(path.join(cwd, fileName), fileContents);
|
||||
await git(cwd, `add ${fileName}`);
|
||||
const commitResult = await runTerminalCommand({
|
||||
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
|
||||
cwd,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (commitResult.code !== 0) {
|
||||
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tests ──
|
||||
|
||||
describe("git integration", () => {
|
||||
describe("runTerminalCommand", () => {
|
||||
it("caps captured output when maxOutputBytes is exceeded", async () => {
|
||||
const result = await runTerminalCommand({
|
||||
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
|
||||
cwd: process.cwd(),
|
||||
timeoutMs: 10_000,
|
||||
maxOutputBytes: 128,
|
||||
});
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
expect(result.stdout.length).toBeLessThanOrEqual(128);
|
||||
expect(result.stderr).toContain("output truncated");
|
||||
});
|
||||
});
|
||||
|
||||
// ── initGitRepo ──
|
||||
|
||||
describe("initGitRepo", () => {
|
||||
it("creates a valid git repo", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initGitRepo({ cwd: tmp.path });
|
||||
expect(existsSync(path.join(tmp.path, ".git"))).toBe(true);
|
||||
});
|
||||
|
||||
it("listGitBranches reports isRepo: true after init + commit", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.isRepo).toBe(true);
|
||||
expect(result.branches.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
|
||||
describe("listGitBranches", () => {
|
||||
it("returns isRepo: false for non-git directory", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.isRepo).toBe(false);
|
||||
expect(result.branches).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns the current branch with current: true", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
const current = result.branches.find((b) => b.current);
|
||||
expect(current).toBeDefined();
|
||||
expect(current!.current).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps current branch first and sorts the remaining branches by recency", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"older.txt",
|
||||
"older branch change\n",
|
||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
||||
"older branch change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"newer.txt",
|
||||
"newer branch change\n",
|
||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
||||
"newer branch change",
|
||||
);
|
||||
|
||||
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches[0]!.name).toBe("older-branch");
|
||||
expect(result.branches[1]!.name).toBe("newer-branch");
|
||||
});
|
||||
|
||||
it("keeps default branch right after current branch", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await using remote = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
await git(remote.path, "init --bare");
|
||||
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(tmp.path, `push -u origin ${defaultBranch}`);
|
||||
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
|
||||
|
||||
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"current.txt",
|
||||
"current change\n",
|
||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
||||
"current change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"newer.txt",
|
||||
"newer change\n",
|
||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
||||
"newer change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches[0]!.name).toBe("current-branch");
|
||||
expect(result.branches[1]!.name).toBe(defaultBranch);
|
||||
expect(result.branches[2]!.name).toBe("newer-branch");
|
||||
});
|
||||
|
||||
it("lists multiple branches after creating them", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "feature-a" });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "feature-b" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
const names = result.branches.map((b) => b.name);
|
||||
expect(names).toContain("feature-a");
|
||||
expect(names).toContain("feature-b");
|
||||
});
|
||||
|
||||
it("isDefault is false when no remote exists", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
|
||||
describe("checkoutGitBranch", () => {
|
||||
it("checks out an existing branch", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "feature" });
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "feature" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
const current = result.branches.find((b) => b.current);
|
||||
expect(current!.name).toBe("feature");
|
||||
});
|
||||
|
||||
it("throws when branch does not exist", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "nonexistent" })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("throws when checkout would overwrite uncommitted changes", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "other" });
|
||||
|
||||
// Create a conflicting change: modify README on current branch
|
||||
await writeFile(path.join(tmp.path, "README.md"), "modified\n");
|
||||
await git(tmp.path, "add README.md");
|
||||
|
||||
// First, checkout other branch cleanly
|
||||
await git(tmp.path, "stash");
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "other" });
|
||||
await writeFile(path.join(tmp.path, "README.md"), "other content\n");
|
||||
await git(tmp.path, "add .");
|
||||
await git(tmp.path, "commit -m 'other change'");
|
||||
|
||||
// Go back to default branch
|
||||
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => !b.current,
|
||||
)!.name;
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
|
||||
|
||||
// Make uncommitted changes to the same file
|
||||
await writeFile(path.join(tmp.path, "README.md"), "conflicting local\n");
|
||||
|
||||
// Checkout should fail due to uncommitted changes
|
||||
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "other" })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ── createGitBranch ──
|
||||
|
||||
describe("createGitBranch", () => {
|
||||
it("creates a new branch visible in listGitBranches", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "new-feature" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches.some((b) => b.name === "new-feature")).toBe(true);
|
||||
});
|
||||
|
||||
it("throws when branch already exists", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "dupe" });
|
||||
await expect(createGitBranch({ cwd: tmp.path, branch: "dupe" })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ── createGitWorktree + removeGitWorktree ──
|
||||
|
||||
describe("createGitWorktree", () => {
|
||||
it("creates a worktree with a new branch from the base branch", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const wtPath = path.join(tmp.path, "worktree-out");
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
const result = await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "wt-branch",
|
||||
path: wtPath,
|
||||
});
|
||||
|
||||
expect(result.worktree.path).toBe(wtPath);
|
||||
expect(result.worktree.branch).toBe("wt-branch");
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
expect(existsSync(path.join(wtPath, "README.md"))).toBe(true);
|
||||
|
||||
// Clean up worktree before tmp dir disposal
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
|
||||
});
|
||||
|
||||
it("worktree has the new branch checked out", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const wtPath = path.join(tmp.path, "wt-check-dir");
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "wt-check",
|
||||
path: wtPath,
|
||||
});
|
||||
|
||||
// Verify the worktree is on the new branch
|
||||
const branchOutput = await git(wtPath, "branch --show-current");
|
||||
expect(branchOutput).toBe("wt-check");
|
||||
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
|
||||
});
|
||||
|
||||
it("throws when new branch name already exists", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "existing" });
|
||||
|
||||
const wtPath = path.join(tmp.path, "wt-conflict");
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
await expect(
|
||||
createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "existing",
|
||||
path: wtPath,
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("listGitBranches from worktree cwd reports worktree branch as current", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const wtPath = path.join(tmp.path, "wt-list-dir");
|
||||
const mainBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: mainBranch,
|
||||
newBranch: "wt-list",
|
||||
path: wtPath,
|
||||
});
|
||||
|
||||
// listGitBranches from the worktree should show wt-list as current
|
||||
const wtBranches = await listGitBranches({ cwd: wtPath });
|
||||
expect(wtBranches.isRepo).toBe(true);
|
||||
const wtCurrent = wtBranches.branches.find((b) => b.current);
|
||||
expect(wtCurrent!.name).toBe("wt-list");
|
||||
|
||||
// Main repo should still show the original branch as current
|
||||
const mainBranches = await listGitBranches({ cwd: tmp.path });
|
||||
const mainCurrent = mainBranches.branches.find((b) => b.current);
|
||||
expect(mainCurrent!.name).toBe(mainBranch);
|
||||
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
|
||||
});
|
||||
|
||||
it("removeGitWorktree cleans up the worktree", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const wtPath = path.join(tmp.path, "wt-remove-dir");
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "wt-remove",
|
||||
path: wtPath,
|
||||
});
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
|
||||
expect(existsSync(wtPath)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Full flow: local branch checkout ──
|
||||
|
||||
describe("full flow: local branch checkout", () => {
|
||||
it("init → commit → create branch → checkout → verify current", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "feature-login" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "feature-login" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
const current = result.branches.find((b) => b.current);
|
||||
expect(current!.name).toBe("feature-login");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Full flow: worktree creation from base branch ──
|
||||
|
||||
describe("full flow: worktree creation", () => {
|
||||
it("creates worktree with new branch from current branch", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
const wtPath = path.join(tmp.path, "my-worktree");
|
||||
const result = await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "feature-wt",
|
||||
path: wtPath,
|
||||
});
|
||||
|
||||
// Worktree exists
|
||||
expect(existsSync(result.worktree.path)).toBe(true);
|
||||
|
||||
// Main repo still on original branch
|
||||
const mainBranches = await listGitBranches({ cwd: tmp.path });
|
||||
const mainCurrent = mainBranches.branches.find((b) => b.current);
|
||||
expect(mainCurrent!.name).toBe(currentBranch);
|
||||
|
||||
// Worktree is on the new branch
|
||||
const wtBranch = await git(wtPath, "branch --show-current");
|
||||
expect(wtBranch).toBe("feature-wt");
|
||||
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath });
|
||||
});
|
||||
});
|
||||
|
||||
// ── Full flow: thread switching simulation ──
|
||||
|
||||
describe("full flow: thread switching (checkout toggling)", () => {
|
||||
it("checkout a → checkout b → checkout a → current matches", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "branch-a" });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "branch-b" });
|
||||
|
||||
// Simulate switching to thread A's branch
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
|
||||
let branches = await listGitBranches({ cwd: tmp.path });
|
||||
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
|
||||
|
||||
// Simulate switching to thread B's branch
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-b" });
|
||||
branches = await listGitBranches({ cwd: tmp.path });
|
||||
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-b");
|
||||
|
||||
// Switch back to thread A
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "branch-a" });
|
||||
branches = await listGitBranches({ cwd: tmp.path });
|
||||
expect(branches.branches.find((b) => b.current)!.name).toBe("branch-a");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Full flow: checkout conflict ──
|
||||
|
||||
describe("full flow: checkout conflict", () => {
|
||||
it("uncommitted changes prevent checkout to a diverged branch", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "diverged" });
|
||||
|
||||
// Make diverged branch have different file content
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "diverged" });
|
||||
await writeFile(path.join(tmp.path, "README.md"), "diverged content\n");
|
||||
await git(tmp.path, "add .");
|
||||
await git(tmp.path, "commit -m 'diverge'");
|
||||
|
||||
// Actually, let's just get back to the initial branch explicitly
|
||||
const allBranches = await listGitBranches({ cwd: tmp.path });
|
||||
const initialBranch = allBranches.branches.find((b) => b.name !== "diverged")!.name;
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
|
||||
|
||||
// Make local uncommitted changes to the same file
|
||||
await writeFile(path.join(tmp.path, "README.md"), "local uncommitted\n");
|
||||
|
||||
// Attempt checkout should fail
|
||||
await expect(checkoutGitBranch({ cwd: tmp.path, branch: "diverged" })).rejects.toThrow();
|
||||
|
||||
// Current branch should still be the initial one
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GitCoreService", () => {
|
||||
it("supports branch lifecycle operations through the service API", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
const core = new GitCoreService();
|
||||
|
||||
await core.initRepo({ cwd: tmp.path });
|
||||
await git(tmp.path, "config user.email '[email protected]'");
|
||||
await git(tmp.path, "config user.name 'Test'");
|
||||
await writeFile(path.join(tmp.path, "README.md"), "# test\n");
|
||||
await git(tmp.path, "add .");
|
||||
await git(tmp.path, "commit -m 'initial commit'");
|
||||
|
||||
await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" });
|
||||
await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" });
|
||||
const branches = await core.listBranches({ cwd: tmp.path });
|
||||
|
||||
expect(branches.isRepo).toBe(true);
|
||||
expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api");
|
||||
});
|
||||
|
||||
it("reports status details and dirty state", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
|
||||
const clean = await core.status({ cwd: tmp.path });
|
||||
expect(clean.hasWorkingTreeChanges).toBe(false);
|
||||
expect(clean.branch).toBeTruthy();
|
||||
|
||||
await writeFile(path.join(tmp.path, "README.md"), "updated\n");
|
||||
const dirty = await core.statusDetails(tmp.path);
|
||||
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
||||
});
|
||||
|
||||
it("prepares commit context by auto-staging and creates commit", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
|
||||
await writeFile(path.join(tmp.path, "README.md"), "new content\n");
|
||||
const context = await core.prepareCommitContext(tmp.path);
|
||||
expect(context).not.toBeNull();
|
||||
expect(context!.stagedSummary.length).toBeGreaterThan(0);
|
||||
expect(context!.stagedPatch.length).toBeGreaterThan(0);
|
||||
|
||||
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
|
||||
expect(created.commitSha.length).toBeGreaterThan(0);
|
||||
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
|
||||
});
|
||||
|
||||
it("pushes with upstream setup and then skips when up to date", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await using remote = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await git(remote.path, "init --bare");
|
||||
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
|
||||
|
||||
await writeFile(path.join(tmp.path, "feature.txt"), "push me\n");
|
||||
const core = new GitCoreService();
|
||||
const context = await core.prepareCommitContext(tmp.path);
|
||||
expect(context).not.toBeNull();
|
||||
await core.commit(tmp.path, "Add feature file", "");
|
||||
|
||||
const pushed = await core.pushCurrentBranch(tmp.path, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(true);
|
||||
expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe(
|
||||
"origin/feature/core-push",
|
||||
);
|
||||
|
||||
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
||||
expect(skipped.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
|
||||
it("pulls behind branch and then reports up-to-date", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await using clone = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const initialBranch = (await listGitBranches({ cwd: source.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
await git(source.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(source.path, `push -u origin ${initialBranch}`);
|
||||
|
||||
await git(clone.path, `clone ${JSON.stringify(remote.path)} .`);
|
||||
await git(clone.path, "config user.email '[email protected]'");
|
||||
await git(clone.path, "config user.name 'Test'");
|
||||
await writeFile(path.join(clone.path, "CHANGELOG.md"), "remote change\n");
|
||||
await git(clone.path, "add CHANGELOG.md");
|
||||
await git(clone.path, "commit -m 'remote update'");
|
||||
await git(clone.path, `push origin ${initialBranch}`);
|
||||
|
||||
const core = new GitCoreService();
|
||||
const pulled = await core.pullCurrentBranch(source.path);
|
||||
expect(pulled.status).toBe("pulled");
|
||||
expect((await core.statusDetails(source.path)).behindCount).toBe(0);
|
||||
|
||||
const skipped = await core.pullCurrentBranch(source.path);
|
||||
expect(skipped.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
|
||||
it("top-level pullGitBranch rejects when no upstream exists", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await expect(pullGitBranch({ cwd: tmp.path })).rejects.toThrow("no upstream");
|
||||
});
|
||||
|
||||
it("lists branches when recency lookup fails", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
const recencySpy = vi
|
||||
.spyOn(core as any, "readBranchRecency")
|
||||
.mockRejectedValueOnce(new Error("timeout"));
|
||||
|
||||
const result = await core.listBranches({ cwd: tmp.path });
|
||||
|
||||
expect(result.isRepo).toBe(true);
|
||||
expect(result.branches.length).toBeGreaterThan(0);
|
||||
expect(result.branches[0]?.current).toBe(true);
|
||||
recencySpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,641 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
gitPullInputSchema,
|
||||
gitPullResultSchema,
|
||||
gitStatusInputSchema,
|
||||
gitStatusResultSchema,
|
||||
type GitCheckoutInput,
|
||||
type GitCreateBranchInput,
|
||||
type GitCreateWorktreeInput,
|
||||
type GitCreateWorktreeResult,
|
||||
type GitInitInput,
|
||||
type GitListBranchesInput,
|
||||
type GitListBranchesResult,
|
||||
type GitPullInput,
|
||||
type GitPullResult,
|
||||
type GitRemoveWorktreeInput,
|
||||
type GitStatusInput,
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ProcessRunResult, runProcess } from "./processRunner";
|
||||
|
||||
export interface TerminalCommandInput {
|
||||
command: string;
|
||||
cwd: string;
|
||||
timeoutMs?: number;
|
||||
maxOutputBytes?: number;
|
||||
}
|
||||
|
||||
export type TerminalCommandResult = ProcessRunResult;
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface GitPushResult {
|
||||
status: "pushed" | "skipped_up_to_date";
|
||||
branch: string;
|
||||
upstreamBranch?: string | undefined;
|
||||
setUpstream?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface GitRangeContext {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
interface RunGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||
function runGit(
|
||||
args: readonly string[],
|
||||
cwd: string,
|
||||
timeoutMs = 30_000,
|
||||
): Promise<ProcessRunResult> {
|
||||
return runProcess("git", args, {
|
||||
cwd,
|
||||
timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
}
|
||||
|
||||
function trimStdout(value: string): string {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function parseBranchAb(value: string): { ahead: number; behind: number } {
|
||||
const match = value.match(/^\+(\d+)\s+-(\d+)$/);
|
||||
if (!match) return { ahead: 0, behind: 0 };
|
||||
return {
|
||||
ahead: Number(match[1] ?? "0"),
|
||||
behind: Number(match[2] ?? "0"),
|
||||
};
|
||||
}
|
||||
|
||||
function parseNumstatEntries(
|
||||
stdout: string,
|
||||
): Array<{ path: string; insertions: number; deletions: number }> {
|
||||
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
|
||||
const rawPath =
|
||||
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
|
||||
if (rawPath.length === 0) continue;
|
||||
const added = Number.parseInt(addedRaw ?? "0", 10);
|
||||
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
|
||||
const renameArrowIndex = rawPath.indexOf(" => ");
|
||||
const normalizedPath =
|
||||
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
|
||||
entries.push({
|
||||
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
|
||||
insertions: Number.isFinite(added) ? added : 0,
|
||||
deletions: Number.isFinite(deleted) ? deleted : 0,
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function parsePorcelainPath(line: string): string | null {
|
||||
if (line.startsWith("? ") || line.startsWith("! ")) {
|
||||
const simple = line.slice(2).trim();
|
||||
return simple.length > 0 ? simple : null;
|
||||
}
|
||||
|
||||
if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const tabIndex = line.indexOf("\t");
|
||||
if (tabIndex >= 0) {
|
||||
const fromTab = line.slice(tabIndex + 1);
|
||||
const [path] = fromTab.split("\t");
|
||||
return path?.trim().length ? path.trim() : null;
|
||||
}
|
||||
|
||||
const parts = line.trim().split(/\s+/g);
|
||||
const path = parts.at(-1) ?? "";
|
||||
return path.length > 0 ? path : null;
|
||||
}
|
||||
|
||||
function commandLabel(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function normalizeGitSpawnError(cwd: string, error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error("Failed to run git command.");
|
||||
}
|
||||
if (!fs.existsSync(cwd)) {
|
||||
return new Error(`Working directory does not exist: ${cwd}`);
|
||||
}
|
||||
if (error.message.includes("Command not found: git")) {
|
||||
return new Error("Git is required but not available on PATH.");
|
||||
}
|
||||
return new Error(`Failed to run git command: ${error.message}`);
|
||||
}
|
||||
|
||||
function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return new Error("Current folder is not a git repository.");
|
||||
}
|
||||
if (result.timedOut) {
|
||||
return new Error(`${commandLabel(args)} timed out.`);
|
||||
}
|
||||
const detail =
|
||||
stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`;
|
||||
return new Error(`${commandLabel(args)} failed: ${detail}`);
|
||||
}
|
||||
|
||||
async function runGitOrThrow(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: RunGitOptions = {},
|
||||
): Promise<TerminalCommandResult> {
|
||||
let result: TerminalCommandResult;
|
||||
try {
|
||||
result = await runGit(args, cwd, options.timeoutMs);
|
||||
} catch (error) {
|
||||
throw normalizeGitSpawnError(cwd, error);
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw normalizeGitExecutionError(args, result);
|
||||
}
|
||||
if (!options.allowNonZeroExit && result.code !== 0) {
|
||||
throw normalizeGitExecutionError(args, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function executeGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Promise<TerminalCommandResult> {
|
||||
const result = await runGitOrThrow(cwd, args, {
|
||||
timeoutMs: options.timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
|
||||
if (options.allowNonZeroExit || result.code === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.length > 0) {
|
||||
throw new Error(stderr);
|
||||
}
|
||||
if (options.fallbackErrorMessage) {
|
||||
throw new Error(options.fallbackErrorMessage);
|
||||
}
|
||||
throw normalizeGitExecutionError(args, result);
|
||||
}
|
||||
|
||||
export class GitCoreService {
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.statusDetails(input.cwd);
|
||||
return gitStatusResultSchema.parse({
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr: null,
|
||||
});
|
||||
}
|
||||
|
||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = await Promise.all([
|
||||
this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]),
|
||||
this.gitStdout(cwd, ["diff", "--numstat"]),
|
||||
this.gitStdout(cwd, ["diff", "--cached", "--numstat"]),
|
||||
]);
|
||||
|
||||
let branch: string | null = null;
|
||||
let upstreamRef: string | null = null;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
let hasWorkingTreeChanges = false;
|
||||
const changedFilesWithoutNumstat = new Set<string>();
|
||||
|
||||
for (const line of statusStdout.split(/\r?\n/g)) {
|
||||
if (line.startsWith("# branch.head ")) {
|
||||
const value = line.slice("# branch.head ".length).trim();
|
||||
branch = value.startsWith("(") ? null : value;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("# branch.upstream ")) {
|
||||
const value = line.slice("# branch.upstream ".length).trim();
|
||||
upstreamRef = value.length > 0 ? value : null;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("# branch.ab ")) {
|
||||
const value = line.slice("# branch.ab ".length).trim();
|
||||
const parsed = parseBranchAb(value);
|
||||
aheadCount = parsed.ahead;
|
||||
behindCount = parsed.behind;
|
||||
continue;
|
||||
}
|
||||
if (line.trim().length > 0 && !line.startsWith("#")) {
|
||||
hasWorkingTreeChanges = true;
|
||||
const pathValue = parsePorcelainPath(line);
|
||||
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
|
||||
}
|
||||
}
|
||||
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
||||
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
||||
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
||||
for (const entry of [...stagedEntries, ...unstagedEntries]) {
|
||||
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
|
||||
existing.insertions += entry.insertions;
|
||||
existing.deletions += entry.deletions;
|
||||
fileStatMap.set(entry.path, existing);
|
||||
}
|
||||
|
||||
let insertions = 0;
|
||||
let deletions = 0;
|
||||
const files = Array.from(fileStatMap.entries())
|
||||
.map(([path, stat]) => {
|
||||
insertions += stat.insertions;
|
||||
deletions += stat.deletions;
|
||||
return { path, insertions: stat.insertions, deletions: stat.deletions };
|
||||
})
|
||||
.toSorted((a, b) => a.path.localeCompare(b.path));
|
||||
|
||||
for (const filePath of changedFilesWithoutNumstat) {
|
||||
if (fileStatMap.has(filePath)) continue;
|
||||
files.push({ path: filePath, insertions: 0, deletions: 0 });
|
||||
}
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
|
||||
return {
|
||||
branch,
|
||||
upstreamRef,
|
||||
hasWorkingTreeChanges,
|
||||
workingTree: {
|
||||
files,
|
||||
insertions,
|
||||
deletions,
|
||||
},
|
||||
hasUpstream: upstreamRef !== null,
|
||||
aheadCount,
|
||||
behindCount,
|
||||
};
|
||||
}
|
||||
|
||||
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
|
||||
await this.git(cwd, ["add", "-A"]);
|
||||
|
||||
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
|
||||
if (trimStdout(stagedSummary).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
|
||||
|
||||
return {
|
||||
stagedSummary,
|
||||
stagedPatch,
|
||||
};
|
||||
}
|
||||
|
||||
async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> {
|
||||
const args = ["commit", "-m", subject];
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length > 0) {
|
||||
args.push("-m", trimmedBody);
|
||||
}
|
||||
await this.git(cwd, args);
|
||||
const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"]));
|
||||
return { commitSha };
|
||||
}
|
||||
|
||||
async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise<GitPushResult> {
|
||||
const details = await this.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
throw new Error("Cannot push from detached HEAD.");
|
||||
}
|
||||
|
||||
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
|
||||
return {
|
||||
status: "skipped_up_to_date",
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!details.hasUpstream) {
|
||||
await this.git(cwd, ["push", "-u", "origin", branch]);
|
||||
return {
|
||||
status: "pushed",
|
||||
branch,
|
||||
upstreamBranch: `origin/${branch}`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}
|
||||
|
||||
await this.git(cwd, ["push"]);
|
||||
return {
|
||||
status: "pushed",
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
setUpstream: false,
|
||||
};
|
||||
}
|
||||
|
||||
async pullCurrentBranch(cwd: string): Promise<GitPullResult> {
|
||||
const details = await this.statusDetails(cwd);
|
||||
const branch = details.branch;
|
||||
if (!branch) {
|
||||
throw new Error("Cannot pull from detached HEAD.");
|
||||
}
|
||||
if (!details.hasUpstream) {
|
||||
throw new Error("Current branch has no upstream configured. Push with upstream first.");
|
||||
}
|
||||
const beforeSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
|
||||
await executeGit(cwd, ["pull", "--ff-only"], {
|
||||
timeoutMs: 30_000,
|
||||
fallbackErrorMessage: "git pull failed",
|
||||
});
|
||||
const afterSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"], true));
|
||||
const refreshed = await this.statusDetails(cwd);
|
||||
return gitPullResultSchema.parse({
|
||||
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
|
||||
branch,
|
||||
...(refreshed.upstreamRef ? { upstreamBranch: refreshed.upstreamRef } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
|
||||
const range = `${baseBranch}..HEAD`;
|
||||
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
|
||||
this.gitStdout(cwd, ["log", "--oneline", range]),
|
||||
this.gitStdout(cwd, ["diff", "--stat", range]),
|
||||
this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]),
|
||||
]);
|
||||
|
||||
return {
|
||||
commitSummary,
|
||||
diffSummary,
|
||||
diffPatch,
|
||||
};
|
||||
}
|
||||
|
||||
async readConfigValue(cwd: string, key: string): Promise<string | null> {
|
||||
const stdout = await this.gitStdout(cwd, ["config", "--get", key], true);
|
||||
const value = trimStdout(stdout);
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
|
||||
const branchRecency = await executeGit(
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
|
||||
const branchLastCommit = new Map<string, number>();
|
||||
if (branchRecency.code !== 0) {
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
for (const line of branchRecency.stdout.split("\n")) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [name, lastCommitRaw] = line.split("\t");
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
|
||||
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
|
||||
}
|
||||
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
||||
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
|
||||
() => new Map<string, number>(),
|
||||
);
|
||||
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
|
||||
if (result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false };
|
||||
}
|
||||
throw new Error(stderr || "git branch failed");
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
|
||||
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
executeGit(input.cwd, ["worktree", "list", "--porcelain"], {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
branchRecencyPromise,
|
||||
]);
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
const worktreeMap = new Map<string, string>();
|
||||
if (worktreeList.code === 0) {
|
||||
let currentPath: string | null = null;
|
||||
for (const line of worktreeList.stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
|
||||
} else if (line === "") {
|
||||
currentPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const branches = result.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const name = line.replace(/^[*+]\s+/, "");
|
||||
return {
|
||||
name,
|
||||
current: line.startsWith("* "),
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return { branches, isRepo: true };
|
||||
}
|
||||
|
||||
async createWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
|
||||
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const worktreePath =
|
||||
input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
|
||||
|
||||
await executeGit(
|
||||
input.cwd,
|
||||
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
|
||||
{ fallbackErrorMessage: "git worktree add failed" },
|
||||
);
|
||||
|
||||
return {
|
||||
worktree: {
|
||||
path: worktreePath,
|
||||
branch: input.newBranch,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["worktree", "remove", input.path], {
|
||||
timeoutMs: 15_000,
|
||||
fallbackErrorMessage: "git worktree remove failed",
|
||||
});
|
||||
}
|
||||
|
||||
async createBranch(input: GitCreateBranchInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
});
|
||||
}
|
||||
|
||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["checkout", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
}
|
||||
|
||||
async initRepo(input: GitInitInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["init"], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git init failed",
|
||||
});
|
||||
}
|
||||
|
||||
async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
|
||||
await executeGit(cwd, args, { allowNonZeroExit });
|
||||
}
|
||||
|
||||
async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
|
||||
const result = await executeGit(cwd, args, { allowNonZeroExit });
|
||||
return result.stdout;
|
||||
}
|
||||
}
|
||||
|
||||
const defaultGitCoreService = new GitCoreService();
|
||||
|
||||
export async function runTerminalCommand(
|
||||
input: TerminalCommandInput,
|
||||
): Promise<TerminalCommandResult> {
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
const shellPath =
|
||||
process.platform === "win32"
|
||||
? (process.env.ComSpec ?? "cmd.exe")
|
||||
: (process.env.SHELL ?? "/bin/sh");
|
||||
|
||||
const args =
|
||||
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
|
||||
|
||||
const result = await runProcess(shellPath, args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? 30_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: maxOutputBytes,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
|
||||
if (!result.stdoutTruncated && !result.stderrTruncated) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return {
|
||||
...result,
|
||||
stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
||||
return defaultGitCoreService.listBranches(input);
|
||||
}
|
||||
|
||||
export async function pullGitBranch(raw: GitPullInput): Promise<GitPullResult> {
|
||||
const input = gitPullInputSchema.parse(raw);
|
||||
return defaultGitCoreService.pullCurrentBranch(input.cwd);
|
||||
}
|
||||
|
||||
export async function createGitWorktree(
|
||||
input: GitCreateWorktreeInput,
|
||||
): Promise<GitCreateWorktreeResult> {
|
||||
return defaultGitCoreService.createWorktree(input);
|
||||
}
|
||||
|
||||
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
|
||||
await defaultGitCoreService.removeWorktree(input);
|
||||
}
|
||||
|
||||
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
|
||||
await defaultGitCoreService.createBranch(input);
|
||||
}
|
||||
|
||||
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
|
||||
await defaultGitCoreService.checkoutBranch(input);
|
||||
}
|
||||
|
||||
export async function initGitRepo(input: GitInitInput): Promise<void> {
|
||||
await defaultGitCoreService.initRepo(input);
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
/**
|
||||
* GitCommandError - Git command execution failed.
|
||||
*/
|
||||
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHubCliError - GitHub CLI execution or authentication failed.
|
||||
*/
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGenerationError - Commit or PR text generation failed.
|
||||
*/
|
||||
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
|
||||
"TextGenerationError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Text generation failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManagerError - Stacked Git workflow orchestration failed.
|
||||
*/
|
||||
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Git manager failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
|
||||
*/
|
||||
export type GitManagerServiceError =
|
||||
| GitManagerError
|
||||
| GitCommandError
|
||||
| GitHubCliError
|
||||
| TextGenerationError;
|
||||
@@ -1,205 +0,0 @@
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
function makeFakeCodexBinary(dir: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = path.join(dir, "bin");
|
||||
const codexPath = path.join(binDir, "codex");
|
||||
yield* fs.makeDirectory(binDir, { recursive: true });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
codexPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'output_path=""',
|
||||
"while [ $# -gt 0 ]; do",
|
||||
' if [ "$1" = "--output-last-message" ]; then',
|
||||
" shift",
|
||||
' output_path="$1"',
|
||||
" fi",
|
||||
" shift",
|
||||
"done",
|
||||
"cat >/dev/null",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
|
||||
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||
"fi",
|
||||
'if [ -n "$output_path" ]; then',
|
||||
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
|
||||
"fi",
|
||||
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(codexPath, 0o755);
|
||||
return binDir;
|
||||
});
|
||||
}
|
||||
|
||||
function withFakeCodexEnv<A, E, R>(
|
||||
input: {
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
},
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
const binDir = yield* makeFakeCodexBinary(tempDir);
|
||||
const previousPath = process.env.PATH;
|
||||
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
|
||||
|
||||
if (input.exitCode !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
}
|
||||
|
||||
if (input.stderr !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
};
|
||||
}),
|
||||
() => effect,
|
||||
(previous) =>
|
||||
Effect.sync(() => {
|
||||
process.env.PATH = previous.previousPath;
|
||||
|
||||
if (previous.previousOutput === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
|
||||
}
|
||||
|
||||
if (previous.previousExitCode === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
|
||||
}
|
||||
|
||||
if (previous.previousStderr === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDERR;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const CodexTextGenerationTestLayer = Layer.provideMerge(
|
||||
CodexTextGenerationLive,
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
subject:
|
||||
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
|
||||
body: "\n- added migration\n- updated tests\n",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
});
|
||||
|
||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||
expect(generated.subject.endsWith(".")).toBe(false);
|
||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates PR content and trims markdown body", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: " Improve orchestration flow\nwith ignored suffix",
|
||||
body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd: process.cwd(),
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/codex-effect",
|
||||
commitSummary: "feat: improve orchestration flow",
|
||||
diffSummary: "2 files changed",
|
||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Improve orchestration flow");
|
||||
expect(generated.body.startsWith("## Summary")).toBe(true);
|
||||
expect(generated.body.endsWith("\n\n")).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({ subject: "ignored", body: "" }),
|
||||
exitCode: 1,
|
||||
stderr: "codex execution failed",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const result = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-error",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,393 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type CommitMessageGenerationResult,
|
||||
type PrContentGenerationResult,
|
||||
type TextGenerationShape,
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
|
||||
const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
|
||||
const COMMIT_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
subject: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["subject", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
const PR_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["title", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
function normalizeCodexError(
|
||||
operation: string,
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (error instanceof TextGenerationError) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
error.message.includes("Command not found: codex") ||
|
||||
lower.includes("spawn codex") ||
|
||||
lower.includes("enoent")
|
||||
) {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex CLI (`codex`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: `${fallback}: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail: fallback,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
throw new Error("Codex returned a non-object commit message payload.");
|
||||
}
|
||||
const record = raw as Record<string, unknown>;
|
||||
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
|
||||
const body = typeof record.body === "string" ? record.body : "";
|
||||
if (subject.length === 0) {
|
||||
throw new Error("Codex returned an empty commit subject.");
|
||||
}
|
||||
return { subject, body };
|
||||
}
|
||||
|
||||
function parsePrOutput(raw: unknown): { title: string; body: string } {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
throw new Error("Codex returned a non-object PR payload.");
|
||||
}
|
||||
const record = raw as Record<string, unknown>;
|
||||
const title = typeof record.title === "string" ? record.title.trim() : "";
|
||||
const body = typeof record.body === "string" ? record.body.trim() : "";
|
||||
if (title.length === 0 || body.length === 0) {
|
||||
throw new Error("Codex returned an invalid PR title/body payload.");
|
||||
}
|
||||
return { title, body };
|
||||
}
|
||||
|
||||
function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||
if (withoutTrailingPeriod.length === 0) {
|
||||
return "Update project files";
|
||||
}
|
||||
|
||||
if (withoutTrailingPeriod.length <= 72) {
|
||||
return withoutTrailingPeriod;
|
||||
}
|
||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||
}
|
||||
|
||||
function sanitizePrTitle(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
if (singleLine.length > 0) {
|
||||
return singleLine;
|
||||
}
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const readStreamAsString = (
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, unknown>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
let text = "";
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.sync(() => {
|
||||
text += Buffer.from(chunk).toString("utf8");
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
return text;
|
||||
});
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
|
||||
const writeTempFile = (
|
||||
operation: string,
|
||||
prefix: string,
|
||||
content: string,
|
||||
): Effect.Effect<string, TextGenerationError> => {
|
||||
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
|
||||
return fileSystem.writeFileString(filePath, content).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: `Failed to write temp file at ${filePath}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.as(filePath),
|
||||
);
|
||||
};
|
||||
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const runCodexJson = <T>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
parse,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: object;
|
||||
parse: (raw: unknown) => T;
|
||||
}): Effect.Effect<T, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(outputSchemaJson),
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const trimmed = rawOutput.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned an empty response.",
|
||||
});
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(trimmed) as unknown,
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid JSON output.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* Effect.try({
|
||||
try: () => parse(parsedJson),
|
||||
catch: (cause) =>
|
||||
normalizeCodexError(operation, cause, "Codex returned invalid structured output"),
|
||||
});
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
"Return a JSON object with keys: subject, body.",
|
||||
"Rules:",
|
||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||
"- body can be empty string or short bullet points",
|
||||
"- capture the primary user-visible or developer-visible change",
|
||||
"",
|
||||
`Branch: ${input.branch ?? "(detached)"}`,
|
||||
"",
|
||||
"Staged files:",
|
||||
limitSection(input.stagedSummary, 6_000),
|
||||
"",
|
||||
"Staged patch:",
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
return runCodexJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parseCommitOutput(raw),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
({
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
}) satisfies CommitMessageGenerationResult,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
"",
|
||||
"Commits:",
|
||||
limitSection(input.commitSummary, 12_000),
|
||||
"",
|
||||
"Diff stat:",
|
||||
limitSection(input.diffSummary, 12_000),
|
||||
"",
|
||||
"Diff patch:",
|
||||
limitSection(input.diffPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
return runCodexJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parsePrOutput(raw),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
({
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
}) satisfies PrContentGenerationResult,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,759 +0,0 @@
|
||||
import { Cache, Data, Duration, Effect, Exit, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
|
||||
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
cwd: string;
|
||||
upstreamRef: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
}
|
||||
|
||||
function parseBranchAb(value: string): { ahead: number; behind: number } {
|
||||
const match = value.match(/^\+(\d+)\s+-(\d+)$/);
|
||||
if (!match) return { ahead: 0, behind: 0 };
|
||||
return {
|
||||
ahead: Number(match[1] ?? "0"),
|
||||
behind: Number(match[2] ?? "0"),
|
||||
};
|
||||
}
|
||||
|
||||
function parseNumstatEntries(
|
||||
stdout: string,
|
||||
): Array<{ path: string; insertions: number; deletions: number }> {
|
||||
const entries: Array<{ path: string; insertions: number; deletions: number }> = [];
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
const [addedRaw, deletedRaw, ...pathParts] = line.split("\t");
|
||||
const rawPath =
|
||||
pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim();
|
||||
if (rawPath.length === 0) continue;
|
||||
const added = Number.parseInt(addedRaw ?? "0", 10);
|
||||
const deleted = Number.parseInt(deletedRaw ?? "0", 10);
|
||||
const renameArrowIndex = rawPath.indexOf(" => ");
|
||||
const normalizedPath =
|
||||
renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath;
|
||||
entries.push({
|
||||
path: normalizedPath.length > 0 ? normalizedPath : rawPath,
|
||||
insertions: Number.isFinite(added) ? added : 0,
|
||||
deletions: Number.isFinite(deleted) ? deleted : 0,
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function parsePorcelainPath(line: string): string | null {
|
||||
if (line.startsWith("? ") || line.startsWith("! ")) {
|
||||
const simple = line.slice(2).trim();
|
||||
return simple.length > 0 ? simple : null;
|
||||
}
|
||||
|
||||
if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const tabIndex = line.indexOf("\t");
|
||||
if (tabIndex >= 0) {
|
||||
const fromTab = line.slice(tabIndex + 1);
|
||||
const [filePath] = fromTab.split("\t");
|
||||
return filePath?.trim().length ? filePath.trim() : null;
|
||||
}
|
||||
|
||||
const parts = line.trim().split(/\s+/g);
|
||||
const filePath = parts.at(-1) ?? "";
|
||||
return filePath.length > 0 ? filePath : null;
|
||||
}
|
||||
|
||||
function commandLabel(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function createGitCommandError(
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
detail: string,
|
||||
cause?: unknown,
|
||||
): GitCommandError {
|
||||
return new GitCommandError({
|
||||
operation,
|
||||
command: commandLabel(args),
|
||||
cwd,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const makeGitCore = Effect.gen(function* () {
|
||||
const git = yield* GitService;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const executeGit = (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation,
|
||||
cwd,
|
||||
args,
|
||||
allowNonZeroExit: true,
|
||||
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((result) => {
|
||||
if (options.allowNonZeroExit || result.code === 0) {
|
||||
return Effect.succeed(result);
|
||||
}
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.length > 0) {
|
||||
return Effect.fail(createGitCommandError(operation, cwd, args, stderr));
|
||||
}
|
||||
if (options.fallbackErrorMessage) {
|
||||
return Effect.fail(
|
||||
createGitCommandError(operation, cwd, args, options.fallbackErrorMessage),
|
||||
);
|
||||
}
|
||||
return Effect.fail(
|
||||
createGitCommandError(
|
||||
operation,
|
||||
cwd,
|
||||
args,
|
||||
`${commandLabel(args)} failed: code=${result.code ?? "null"}`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const runGit = (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Effect.Effect<void, GitCommandError> =>
|
||||
executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid);
|
||||
|
||||
const runGitStdout = (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Effect.Effect<string, GitCommandError> =>
|
||||
executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(
|
||||
Effect.map((result) => result.stdout),
|
||||
);
|
||||
|
||||
const resolveCurrentUpstream = (
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null,
|
||||
GitCommandError
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const upstreamRef = yield* runGitStdout(
|
||||
"GitCore.resolveCurrentUpstream",
|
||||
cwd,
|
||||
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
|
||||
true,
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const separatorIndex = upstreamRef.indexOf("/");
|
||||
if (separatorIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
const remoteName = upstreamRef.slice(0, separatorIndex);
|
||||
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
|
||||
if (remoteName.length === 0 || upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
});
|
||||
|
||||
const fetchUpstreamRef = (
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
return runGit(
|
||||
"GitCore.fetchUpstreamRef",
|
||||
cwd,
|
||||
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
true,
|
||||
);
|
||||
};
|
||||
|
||||
const fetchUpstreamRefForStatus = (
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
return executeGit(
|
||||
"GitCore.fetchUpstreamRefForStatus",
|
||||
cwd,
|
||||
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith({
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
lookup: (cacheKey: StatusUpstreamRefreshCacheKey) =>
|
||||
Effect.gen(function* () {
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
});
|
||||
return true as const;
|
||||
}),
|
||||
// Keep successful refreshes warm; drop failures immediately so next request can retry.
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
|
||||
});
|
||||
|
||||
const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect<void, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
if (!upstream) return;
|
||||
yield* Cache.get(
|
||||
statusUpstreamRefreshCache,
|
||||
new StatusUpstreamRefreshCacheKey({
|
||||
cwd,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect<void, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
if (!upstream) return;
|
||||
yield* fetchUpstreamRef(cwd, upstream);
|
||||
});
|
||||
|
||||
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
|
||||
Effect.gen(function* () {
|
||||
const branchRecency = yield* executeGit(
|
||||
"GitCore.readBranchRecency",
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
|
||||
const branchLastCommit = new Map<string, number>();
|
||||
if (branchRecency.code !== 0) {
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
for (const line of branchRecency.stdout.split("\n")) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [name, lastCommitRaw] = line.split("\t");
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
|
||||
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
|
||||
}
|
||||
|
||||
return branchLastCommit;
|
||||
});
|
||||
|
||||
const statusDetails: GitCoreShape["statusDetails"] = (cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
|
||||
[
|
||||
runGitStdout("GitCore.statusDetails.status", cwd, [
|
||||
"status",
|
||||
"--porcelain=2",
|
||||
"--branch",
|
||||
]),
|
||||
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
|
||||
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
|
||||
"diff",
|
||||
"--cached",
|
||||
"--numstat",
|
||||
]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
let branch: string | null = null;
|
||||
let upstreamRef: string | null = null;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
let hasWorkingTreeChanges = false;
|
||||
const changedFilesWithoutNumstat = new Set<string>();
|
||||
|
||||
for (const line of statusStdout.split(/\r?\n/g)) {
|
||||
if (line.startsWith("# branch.head ")) {
|
||||
const value = line.slice("# branch.head ".length).trim();
|
||||
branch = value.startsWith("(") ? null : value;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("# branch.upstream ")) {
|
||||
const value = line.slice("# branch.upstream ".length).trim();
|
||||
upstreamRef = value.length > 0 ? value : null;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("# branch.ab ")) {
|
||||
const value = line.slice("# branch.ab ".length).trim();
|
||||
const parsed = parseBranchAb(value);
|
||||
aheadCount = parsed.ahead;
|
||||
behindCount = parsed.behind;
|
||||
continue;
|
||||
}
|
||||
if (line.trim().length > 0 && !line.startsWith("#")) {
|
||||
hasWorkingTreeChanges = true;
|
||||
const pathValue = parsePorcelainPath(line);
|
||||
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
|
||||
}
|
||||
}
|
||||
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
|
||||
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
|
||||
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
|
||||
for (const entry of [...stagedEntries, ...unstagedEntries]) {
|
||||
const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 };
|
||||
existing.insertions += entry.insertions;
|
||||
existing.deletions += entry.deletions;
|
||||
fileStatMap.set(entry.path, existing);
|
||||
}
|
||||
|
||||
let insertions = 0;
|
||||
let deletions = 0;
|
||||
const files = Array.from(fileStatMap.entries())
|
||||
.map(([filePath, stat]) => {
|
||||
insertions += stat.insertions;
|
||||
deletions += stat.deletions;
|
||||
return { path: filePath, insertions: stat.insertions, deletions: stat.deletions };
|
||||
})
|
||||
.toSorted((a, b) => a.path.localeCompare(b.path));
|
||||
|
||||
for (const filePath of changedFilesWithoutNumstat) {
|
||||
if (fileStatMap.has(filePath)) continue;
|
||||
files.push({ path: filePath, insertions: 0, deletions: 0 });
|
||||
}
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
|
||||
return {
|
||||
branch,
|
||||
upstreamRef,
|
||||
hasWorkingTreeChanges,
|
||||
workingTree: {
|
||||
files,
|
||||
insertions,
|
||||
deletions,
|
||||
},
|
||||
hasUpstream: upstreamRef !== null,
|
||||
aheadCount,
|
||||
behindCount,
|
||||
};
|
||||
});
|
||||
|
||||
const status: GitCoreShape["status"] = (input) =>
|
||||
statusDetails(input.cwd).pipe(
|
||||
Effect.map((details) => ({
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr: null,
|
||||
})),
|
||||
);
|
||||
|
||||
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
|
||||
|
||||
const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
|
||||
"diff",
|
||||
"--cached",
|
||||
"--name-status",
|
||||
]).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
if (stagedSummary.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [
|
||||
"diff",
|
||||
"--cached",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
]);
|
||||
|
||||
return {
|
||||
stagedSummary,
|
||||
stagedPatch,
|
||||
};
|
||||
});
|
||||
|
||||
const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["commit", "-m", subject];
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length > 0) {
|
||||
args.push("-m", trimmedBody);
|
||||
}
|
||||
yield* runGit("GitCore.commit.commit", cwd, args);
|
||||
const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
|
||||
"rev-parse",
|
||||
"HEAD",
|
||||
]).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
return { commitSha };
|
||||
});
|
||||
|
||||
const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.pushCurrentBranch",
|
||||
cwd,
|
||||
["push"],
|
||||
"Cannot push from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
|
||||
return {
|
||||
status: "skipped_up_to_date" as const,
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!details.hasUpstream) {
|
||||
yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [
|
||||
"push",
|
||||
"-u",
|
||||
"origin",
|
||||
branch,
|
||||
]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch,
|
||||
upstreamBranch: `origin/${branch}`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}
|
||||
|
||||
yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]);
|
||||
return {
|
||||
status: "pushed" as const,
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
setUpstream: false,
|
||||
};
|
||||
});
|
||||
|
||||
const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* statusDetails(cwd);
|
||||
const branch = details.branch;
|
||||
if (!branch) {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.pullCurrentBranch",
|
||||
cwd,
|
||||
["pull", "--ff-only"],
|
||||
"Cannot pull from detached HEAD.",
|
||||
);
|
||||
}
|
||||
if (!details.hasUpstream) {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.pullCurrentBranch",
|
||||
cwd,
|
||||
["pull", "--ff-only"],
|
||||
"Current branch has no upstream configured. Push with upstream first.",
|
||||
);
|
||||
}
|
||||
const beforeSha = yield* runGitStdout(
|
||||
"GitCore.pullCurrentBranch.beforeSha",
|
||||
cwd,
|
||||
["rev-parse", "HEAD"],
|
||||
true,
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], {
|
||||
timeoutMs: 30_000,
|
||||
fallbackErrorMessage: "git pull failed",
|
||||
});
|
||||
const afterSha = yield* runGitStdout(
|
||||
"GitCore.pullCurrentBranch.afterSha",
|
||||
cwd,
|
||||
["rev-parse", "HEAD"],
|
||||
true,
|
||||
).pipe(Effect.map((stdout) => stdout.trim()));
|
||||
|
||||
const refreshed = yield* statusDetails(cwd);
|
||||
return {
|
||||
status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled",
|
||||
branch,
|
||||
upstreamBranch: refreshed.upstreamRef,
|
||||
};
|
||||
});
|
||||
|
||||
const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) =>
|
||||
Effect.gen(function* () {
|
||||
const range = `${baseBranch}..HEAD`;
|
||||
const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(
|
||||
[
|
||||
runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]),
|
||||
runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]),
|
||||
runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
range,
|
||||
]),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
commitSummary,
|
||||
diffSummary,
|
||||
diffPatch,
|
||||
};
|
||||
});
|
||||
|
||||
const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) =>
|
||||
runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe(
|
||||
Effect.map((stdout) => stdout.trim()),
|
||||
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
|
||||
);
|
||||
|
||||
const listBranches: GitCoreShape["listBranches"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
);
|
||||
const result = yield* executeGit(
|
||||
"GitCore.listBranches.branchNoColor",
|
||||
input.cwd,
|
||||
["branch", "--no-color"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false };
|
||||
}
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.listBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color"],
|
||||
stderr || "git branch failed",
|
||||
);
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
input.cwd,
|
||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
executeGit(
|
||||
"GitCore.listBranches.worktreeList",
|
||||
input.cwd,
|
||||
["worktree", "list", "--porcelain"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
const worktreeMap = new Map<string, string>();
|
||||
if (worktreeList.code === 0) {
|
||||
let currentPath: string | null = null;
|
||||
for (const line of worktreeList.stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
const exists = yield* fileSystem.stat(candidatePath).pipe(
|
||||
Effect.map(() => true),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
currentPath = exists ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
|
||||
} else if (line === "") {
|
||||
currentPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const branches = result.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const name = line.replace(/^[*+]\s+/, "");
|
||||
return {
|
||||
name,
|
||||
current: line.startsWith("* "),
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return { branches, isRepo: true };
|
||||
});
|
||||
|
||||
const createWorktree: GitCoreShape["createWorktree"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const homeDir = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
|
||||
const worktreePath =
|
||||
input.path ?? path.join(homeDir, ".t3", "worktrees", repoName, sanitizedBranch);
|
||||
|
||||
yield* executeGit(
|
||||
"GitCore.createWorktree",
|
||||
input.cwd,
|
||||
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
|
||||
{
|
||||
fallbackErrorMessage: "git worktree add failed",
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
worktree: {
|
||||
path: worktreePath,
|
||||
branch: input.newBranch,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const removeWorktree: GitCoreShape["removeWorktree"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["worktree", "remove"];
|
||||
if (input.force) {
|
||||
args.push("--force");
|
||||
}
|
||||
args.push(input.path);
|
||||
yield* executeGit("GitCore.removeWorktree", input.cwd, args, {
|
||||
timeoutMs: 15_000,
|
||||
fallbackErrorMessage: "git worktree remove failed",
|
||||
}).pipe(
|
||||
Effect.mapError((error) =>
|
||||
createGitCommandError(
|
||||
"GitCore.removeWorktree",
|
||||
input.cwd,
|
||||
args,
|
||||
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const createBranch: GitCoreShape["createBranch"] = (input) =>
|
||||
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* Effect.sync(() => {
|
||||
void Effect.runPromise(
|
||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const initRepo: GitCoreShape["initRepo"] = (input) =>
|
||||
executeGit("GitCore.initRepo", input.cwd, ["init"], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git init failed",
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
return {
|
||||
status,
|
||||
statusDetails,
|
||||
prepareCommitContext,
|
||||
commit,
|
||||
pushCurrentBranch,
|
||||
pullCurrentBranch,
|
||||
readRangeContext,
|
||||
readConfigValue,
|
||||
listBranches,
|
||||
createWorktree,
|
||||
removeWorktree,
|
||||
createBranch,
|
||||
checkoutBranch,
|
||||
initRepo,
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
export const GitCoreLive = Layer.effect(GitCore, makeGitCore);
|
||||
@@ -1,178 +0,0 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "../Errors.ts";
|
||||
import { GitHubCli, type GitHubCliShape } from "../Services/GitHubCli.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("Command not found: gh")) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: `GitHub CLI command failed: ${error.message}`,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
operation,
|
||||
detail: "GitHub CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
function parseOpenPullRequests(raw: string): ReadonlyArray<{
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
}> {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) return [];
|
||||
|
||||
const parsed: unknown = JSON.parse(trimmed);
|
||||
if (!Array.isArray(parsed)) {
|
||||
throw new Error("GitHub CLI returned non-array JSON.");
|
||||
}
|
||||
|
||||
const result: Array<{
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
}> = [];
|
||||
for (const entry of parsed) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
if (
|
||||
typeof number !== "number" ||
|
||||
!Number.isInteger(number) ||
|
||||
number <= 0 ||
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
result.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const makeGitHubCli = Effect.sync(() => {
|
||||
const execute: GitHubCliShape["execute"] = (input) =>
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("gh", input.args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
}),
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
});
|
||||
|
||||
const service = {
|
||||
execute,
|
||||
listOpenPullRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headBranch,
|
||||
"--state",
|
||||
"open",
|
||||
"--limit",
|
||||
String(input.limit ?? 1),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.try({
|
||||
try: () => parseOpenPullRequests(raw),
|
||||
catch: (error: unknown) =>
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
detail:
|
||||
error instanceof Error
|
||||
? `GitHub CLI returned invalid PR list JSON: ${error.message}`
|
||||
: "GitHub CLI returned invalid PR list JSON.",
|
||||
...(error !== undefined ? { cause: error } : {}),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
createPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"create",
|
||||
"--base",
|
||||
input.baseBranch,
|
||||
"--head",
|
||||
input.headBranch,
|
||||
"--title",
|
||||
input.title,
|
||||
"--body-file",
|
||||
input.bodyFile,
|
||||
],
|
||||
}).pipe(Effect.asVoid),
|
||||
getDefaultBranch: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
|
||||
}).pipe(
|
||||
Effect.map((value) => {
|
||||
const trimmed = value.stdout.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}),
|
||||
),
|
||||
} satisfies GitHubCliShape;
|
||||
|
||||
return service;
|
||||
});
|
||||
|
||||
export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);
|
||||
@@ -1,660 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { GitHubCliError, TextGenerationError } from "../Errors.ts";
|
||||
import { type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
GitHubCli,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
import { GitCoreLive } from "./GitCore.ts";
|
||||
import { makeGitManager } from "./GitManager.ts";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
createdPrUrl?: string;
|
||||
defaultBranch?: string;
|
||||
failWith?: Error;
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}) => Effect.Effect<{ subject: string; body: string }, unknown>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}) => Effect.Effect<{ title: string; body: string }, unknown>;
|
||||
}
|
||||
|
||||
function makeTempDir(
|
||||
prefix: string,
|
||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
|
||||
});
|
||||
}
|
||||
|
||||
function runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Effect.Effect<
|
||||
{ readonly code: number; readonly stdout: string; readonly stderr: string },
|
||||
unknown,
|
||||
GitService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
return yield* gitService.execute({
|
||||
operation: "GitManager.test.runGit",
|
||||
cwd,
|
||||
args,
|
||||
allowNonZeroExit,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function initRepo(
|
||||
cwd: string,
|
||||
): Effect.Effect<void, unknown, FileSystem.FileSystem | Scope.Scope | GitService> {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
yield* fs.writeFileString(path.join(cwd, "README.md"), "hello\n");
|
||||
yield* runGit(cwd, ["add", "README.md"]);
|
||||
yield* runGit(cwd, ["commit", "-m", "Initial commit"]);
|
||||
});
|
||||
}
|
||||
|
||||
function createBareRemote(): Effect.Effect<
|
||||
string,
|
||||
unknown,
|
||||
FileSystem.FileSystem | Scope.Scope | GitService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const remoteDir = yield* makeTempDir("t3code-git-remote-");
|
||||
yield* runGit(remoteDir, ["init", "--bare"]);
|
||||
return remoteDir;
|
||||
});
|
||||
}
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: () =>
|
||||
Effect.succeed({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
}),
|
||||
generatePrContent: () =>
|
||||
Effect.succeed({
|
||||
title: "Add stacked git actions",
|
||||
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
|
||||
return {
|
||||
generateCommitMessage: (input) =>
|
||||
implementation.generateCommitMessage(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "fake text generation failed",
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
generatePrContent: (input) =>
|
||||
implementation.generatePrContent(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "fake text generation failed",
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
const normalizeGhError = (error: Error): GitHubCliError => {
|
||||
if (error.message.includes("Command not found: gh")) {
|
||||
return new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
};
|
||||
|
||||
function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
service: GitHubCliShape;
|
||||
ghCalls: string[];
|
||||
} {
|
||||
const prListQueue = [...(scenario.prListSequence ?? [])];
|
||||
const ghCalls: string[] = [];
|
||||
|
||||
const execute: GitHubCliShape["execute"] = (input) => {
|
||||
const args = [...input.args];
|
||||
ghCalls.push(args.join(" "));
|
||||
|
||||
if (scenario.failWith) {
|
||||
return Effect.fail(normalizeGhError(scenario.failWith));
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "list") {
|
||||
const stdout = (prListQueue.shift() ?? "[]") + "\n";
|
||||
return Effect.succeed({
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "create") {
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "view") {
|
||||
return Effect.succeed({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (args[0] === "repo" && args[1] === "view") {
|
||||
return Effect.succeed({
|
||||
stdout: `${scenario.defaultBranch ?? "main"}\n`,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
service: {
|
||||
execute,
|
||||
listOpenPullRequests: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
input.headBranch,
|
||||
"--state",
|
||||
"open",
|
||||
"--limit",
|
||||
String(input.limit ?? 1),
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName",
|
||||
],
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(result) => JSON.parse(result.stdout) as ReadonlyArray<GitHubPullRequestSummary>,
|
||||
),
|
||||
),
|
||||
createPullRequest: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"create",
|
||||
"--base",
|
||||
input.baseBranch,
|
||||
"--head",
|
||||
input.headBranch,
|
||||
"--title",
|
||||
input.title,
|
||||
"--body-file",
|
||||
input.bodyFile,
|
||||
],
|
||||
}).pipe(Effect.asVoid),
|
||||
getDefaultBranch: (input) =>
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],
|
||||
}).pipe(
|
||||
Effect.map((result) => {
|
||||
const value = result.stdout.trim();
|
||||
return value.length > 0 ? value : null;
|
||||
}),
|
||||
),
|
||||
},
|
||||
ghCalls,
|
||||
};
|
||||
}
|
||||
|
||||
function runStackedAction(
|
||||
manager: GitManagerShape,
|
||||
input: {
|
||||
cwd: string;
|
||||
action: "commit" | "commit_push" | "commit_push_pr";
|
||||
commitMessage?: string;
|
||||
},
|
||||
) {
|
||||
return manager.runStackedAction(input);
|
||||
}
|
||||
|
||||
function makeManager(input?: {
|
||||
ghScenario?: FakeGhScenario;
|
||||
textGeneration?: Partial<FakeGitTextGeneration>;
|
||||
}) {
|
||||
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
||||
const textGeneration = createTextGeneration(input?.textGeneration);
|
||||
|
||||
const gitCoreLayer = GitCoreLive.pipe(
|
||||
Layer.provideMerge(GitServiceLive),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const managerLayer = Layer.mergeAll(
|
||||
Layer.succeed(GitHubCli, gitHubCli),
|
||||
Layer.succeed(TextGeneration, textGeneration),
|
||||
gitCoreLayer,
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
return makeGitManager.pipe(
|
||||
Effect.provide(managerLayer),
|
||||
Effect.map((manager) => ({ manager, ghCalls })),
|
||||
);
|
||||
}
|
||||
|
||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
it.effect("status includes open PR metadata when branch already has an open PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.openPr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new Error("Command not found: gh"),
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.openPr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates a commit when working tree is dirty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("Implement stacked git actions");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses custom commit message when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: () =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
expect(
|
||||
yield* runGit(repoDir, ["log", "-1", "--pretty=%s"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("feat: custom summary line");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["log", "-1", "--pretty=%b"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toContain("- details from user");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips commit when there are no uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("commits and pushes with upstream auto-setup when needed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("origin/feature/stacked-flow");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips push when branch is already up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_up_to_date");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns existing PR metadata for commit/push/pr action", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 42,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/existing-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("opened_existing");
|
||||
expect(result.pr.number).toBe(42);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates PR when one does not already exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
|
||||
yield* runGit(repoDir, ["add", "changes.txt"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
|
||||
yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 88,
|
||||
title: "Add stacked git actions",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/88",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature-create-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||
).toBe(true);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects push/pr actions from detached HEAD", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "--detach", "HEAD"]);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||
);
|
||||
expect(errorMessage).toContain("detached HEAD");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces missing gh binary errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new Error("Command not found: gh"),
|
||||
},
|
||||
});
|
||||
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||
);
|
||||
expect(errorMessage).toContain("GitHub CLI (`gh`) is required");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces gh auth errors with guidance", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new Error("authentication failed"),
|
||||
},
|
||||
});
|
||||
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => (error instanceof Error ? error.message : String(error))),
|
||||
);
|
||||
expect(errorMessage).toContain("gh auth login");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,318 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
interface OpenPrInfo {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||
return new GitManagerError({
|
||||
operation,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function limitContext(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitMessage(generated: {
|
||||
subject: string;
|
||||
body: string;
|
||||
}): {
|
||||
subject: string;
|
||||
body: string;
|
||||
} {
|
||||
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
||||
const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
|
||||
return {
|
||||
subject: safeSubject,
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
|
||||
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
||||
if (normalized.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [firstLine, ...rest] = normalized.split("\n");
|
||||
const subject = firstLine?.trim() ?? "";
|
||||
if (subject.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
subject,
|
||||
body: rest.join("\n").trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function extractBranchFromRef(ref: string): string {
|
||||
const normalized = ref.trim();
|
||||
|
||||
if (normalized.startsWith("refs/remotes/")) {
|
||||
const withoutPrefix = normalized.slice("refs/remotes/".length);
|
||||
const firstSlash = withoutPrefix.indexOf("/");
|
||||
if (firstSlash === -1) {
|
||||
return withoutPrefix.trim();
|
||||
}
|
||||
return withoutPrefix.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
const firstSlash = normalized.indexOf("/");
|
||||
if (firstSlash === -1) {
|
||||
return normalized;
|
||||
}
|
||||
return normalized.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
};
|
||||
}
|
||||
|
||||
export const makeGitManager = Effect.gen(function* () {
|
||||
const gitCore = yield* GitCore;
|
||||
const gitHubCli = yield* GitHubCli;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||
|
||||
const findOpenPr = (cwd: string, branch: string) =>
|
||||
gitHubCli
|
||||
.listOpenPullRequests({
|
||||
cwd,
|
||||
headBranch: branch,
|
||||
limit: 1,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((prs) => {
|
||||
const [first] = prs;
|
||||
if (!first) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
number: first.number,
|
||||
title: first.title,
|
||||
url: first.url,
|
||||
baseRefName: first.baseRefName,
|
||||
headRefName: first.headRefName,
|
||||
} satisfies OpenPrInfo;
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||
if (configured) return configured;
|
||||
|
||||
if (upstreamRef) {
|
||||
const upstreamBranch = extractBranchFromRef(upstreamRef);
|
||||
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
|
||||
return upstreamBranch;
|
||||
}
|
||||
}
|
||||
|
||||
const defaultFromGh = yield* gitHubCli
|
||||
.getDefaultBranch({ cwd })
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (defaultFromGh) {
|
||||
return defaultFromGh;
|
||||
}
|
||||
|
||||
return "main";
|
||||
});
|
||||
|
||||
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(cwd);
|
||||
if (!context) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
let generated = parseCustomCommitMessage(commitMessage ?? "");
|
||||
if (!generated) {
|
||||
generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd,
|
||||
branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
}).pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
subject: generated.subject,
|
||||
};
|
||||
});
|
||||
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
return yield* gitManagerError("runPrStep", "Cannot create a pull request from detached HEAD.");
|
||||
}
|
||||
if (!details.hasUpstream) {
|
||||
return yield* gitManagerError(
|
||||
"runPrStep",
|
||||
"Current branch has not been pushed. Push before creating a PR.",
|
||||
);
|
||||
}
|
||||
|
||||
const existing = yield* findOpenPr(cwd, branch);
|
||||
if (existing) {
|
||||
return {
|
||||
status: "opened_existing" as const,
|
||||
url: existing.url,
|
||||
number: existing.number,
|
||||
baseBranch: existing.baseRefName,
|
||||
headBranch: existing.headRefName,
|
||||
title: existing.title,
|
||||
};
|
||||
}
|
||||
|
||||
const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef);
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch);
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd,
|
||||
baseBranch,
|
||||
headBranch: branch,
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
});
|
||||
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
||||
yield* fileSystem
|
||||
.writeFileString(bodyFile, generated.body)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
gitManagerError(
|
||||
"runPrStep",
|
||||
"Failed to write pull request body temp file.",
|
||||
cause,
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* gitHubCli
|
||||
.createPullRequest({
|
||||
cwd,
|
||||
baseBranch,
|
||||
headBranch: branch,
|
||||
title: generated.title,
|
||||
bodyFile,
|
||||
})
|
||||
.pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));
|
||||
|
||||
const created = yield* findOpenPr(cwd, branch);
|
||||
if (!created) {
|
||||
return {
|
||||
status: "created" as const,
|
||||
baseBranch,
|
||||
headBranch: branch,
|
||||
title: generated.title,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: "created" as const,
|
||||
url: created.url,
|
||||
number: created.number,
|
||||
baseBranch: created.baseRefName,
|
||||
headBranch: created.headRefName,
|
||||
title: created.title,
|
||||
};
|
||||
});
|
||||
|
||||
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||
const details = yield* gitCore.statusDetails(input.cwd);
|
||||
|
||||
const openPr =
|
||||
details.branch && details.hasUpstream
|
||||
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
: null;
|
||||
|
||||
return {
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr,
|
||||
};
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(function* (input) {
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
||||
if (wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot create a pull request from detached HEAD.");
|
||||
}
|
||||
|
||||
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
||||
|
||||
const push = wantsPush
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
action: input.action,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status,
|
||||
runStackedAction,
|
||||
} satisfies GitManagerShape;
|
||||
});
|
||||
|
||||
export const GitManagerLive = Layer.effect(GitManager, makeGitManager);
|
||||
@@ -1,59 +0,0 @@
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import { GitServiceLive } from "./GitService.ts";
|
||||
import { GitService } from "../Services/GitService.ts";
|
||||
|
||||
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||
|
||||
layer("GitServiceLive", (it) => {
|
||||
it.effect("runGit executes successful git commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
const result = yield* gitService.execute({
|
||||
operation: "GitProcess.test.version",
|
||||
cwd: process.cwd(),
|
||||
args: ["--version"],
|
||||
});
|
||||
|
||||
assert.equal(result.code, 0);
|
||||
assert.ok(result.stdout.toLowerCase().includes("git version"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("runGit can return non-zero exit codes when allowed", () =>
|
||||
Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
const result = yield* gitService.execute({
|
||||
operation: "GitProcess.test.allowNonZero",
|
||||
cwd: process.cwd(),
|
||||
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
|
||||
assert.notEqual(result.code, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
|
||||
Effect.gen(function* () {
|
||||
const gitService = yield* GitService;
|
||||
const result = yield* Effect.result(
|
||||
gitService.execute({
|
||||
operation: "GitProcess.test.failOnNonZero",
|
||||
cwd: process.cwd(),
|
||||
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
if (result._tag === "Failure") {
|
||||
assert.ok(result.failure instanceof GitCommandError);
|
||||
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
|
||||
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,144 +0,0 @@
|
||||
/**
|
||||
* Git process helpers - Effect-native git execution with typed errors.
|
||||
*
|
||||
* Centralizes child-process git invocation for server modules. This module
|
||||
* only executes git commands and reports structured failures.
|
||||
*
|
||||
* @module GitServiceLive
|
||||
*/
|
||||
import { Effect, Layer, Option, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
ExecuteGitInput,
|
||||
ExecuteGitResult,
|
||||
GitService,
|
||||
GitServiceShape,
|
||||
} from "../Services/GitService.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function toGitCommandError(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
detail: string,
|
||||
) {
|
||||
return (cause: unknown) =>
|
||||
cause instanceof GitCommandError
|
||||
? cause
|
||||
: new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const collectOutput = Effect.fn(function* (
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, unknown>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
bytes += chunk.byteLength;
|
||||
if (bytes > maxOutputBytes) {
|
||||
return yield* new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: quoteGitCommand(input.args),
|
||||
cwd: input.cwd,
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
|
||||
text += decoder.decode();
|
||||
return text;
|
||||
});
|
||||
|
||||
const makeGitService = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||
const commandInput = {
|
||||
...input,
|
||||
args: [...input.args],
|
||||
} as const;
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
||||
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
return yield* new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail:
|
||||
trimmedStderr.length > 0
|
||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
||||
});
|
||||
|
||||
return yield* commandEffect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(timeoutMs),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: commandInput.operation,
|
||||
command: quoteGitCommand(commandInput.args),
|
||||
cwd: commandInput.cwd,
|
||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
execute,
|
||||
} satisfies GitServiceShape;
|
||||
});
|
||||
|
||||
export const GitServiceLive = Layer.effect(GitService, makeGitService);
|
||||
@@ -1,146 +0,0 @@
|
||||
/**
|
||||
* GitCore - Effect service contract for low-level Git operations.
|
||||
*
|
||||
* Wraps core repository primitives used by higher-level orchestration
|
||||
* services and WebSocket routes.
|
||||
*
|
||||
* @module GitCore
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
GitCreateWorktreeInput,
|
||||
GitCreateWorktreeResult,
|
||||
GitInitInput,
|
||||
GitListBranchesInput,
|
||||
GitListBranchesResult,
|
||||
GitPullResult,
|
||||
GitRemoveWorktreeInput,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface GitPushResult {
|
||||
status: "pushed" | "skipped_up_to_date";
|
||||
branch: string;
|
||||
upstreamBranch?: string | undefined;
|
||||
setUpstream?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface GitRangeContext {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitCoreShape - Service API for low-level Git repository interactions.
|
||||
*/
|
||||
export interface GitCoreShape {
|
||||
/**
|
||||
* Read Git status for a repository.
|
||||
*/
|
||||
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read detailed working tree / branch status for a repository.
|
||||
*/
|
||||
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Build staged change context for commit generation.
|
||||
*/
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Create a commit with provided subject/body.
|
||||
*/
|
||||
readonly commit: (
|
||||
cwd: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Push current branch, setting upstream if needed.
|
||||
*/
|
||||
readonly pushCurrentBranch: (
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
) => Effect.Effect<GitPushResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Collect commit/diff context between base branch and current HEAD.
|
||||
*/
|
||||
readonly readRangeContext: (
|
||||
cwd: string,
|
||||
baseBranch: string,
|
||||
) => Effect.Effect<GitRangeContext, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Read a Git config value from the local repository.
|
||||
*/
|
||||
readonly readConfigValue: (
|
||||
cwd: string,
|
||||
key: string,
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branches and branch metadata.
|
||||
*/
|
||||
readonly listBranches: (
|
||||
input: GitListBranchesInput,
|
||||
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Pull current branch from upstream using fast-forward only.
|
||||
*/
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Create a worktree and branch from a base branch.
|
||||
*/
|
||||
readonly createWorktree: (
|
||||
input: GitCreateWorktreeInput,
|
||||
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Remove an existing worktree.
|
||||
*/
|
||||
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Create a local branch.
|
||||
*/
|
||||
readonly createBranch: (input: GitCreateBranchInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||
*/
|
||||
readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* Initialize a repository in the provided directory.
|
||||
*/
|
||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitCore - Service tag for low-level Git repository operations.
|
||||
*/
|
||||
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()("git/GitCore") {}
|
||||
@@ -1,66 +0,0 @@
|
||||
/**
|
||||
* GitHubCli - Effect service contract for `gh` process interactions.
|
||||
*
|
||||
* Provides thin command execution helpers used by Git workflow orchestration.
|
||||
*
|
||||
* @module GitHubCli
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner";
|
||||
import type { GitHubCliError } from "../Errors.ts";
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHubCliShape - Service API for executing GitHub CLI commands.
|
||||
*/
|
||||
export interface GitHubCliShape {
|
||||
/**
|
||||
* Execute a GitHub CLI command and return full process output.
|
||||
*/
|
||||
readonly execute: (input: {
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* List open pull requests for a head branch.
|
||||
*/
|
||||
readonly listOpenPullRequests: (input: {
|
||||
readonly cwd: string;
|
||||
readonly headBranch: string;
|
||||
readonly limit?: number;
|
||||
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Create a pull request from branch context and body file.
|
||||
*/
|
||||
readonly createPullRequest: (input: {
|
||||
readonly cwd: string;
|
||||
readonly baseBranch: string;
|
||||
readonly headBranch: string;
|
||||
readonly title: string;
|
||||
readonly bodyFile: string;
|
||||
}) => Effect.Effect<void, GitHubCliError>;
|
||||
|
||||
/**
|
||||
* Resolve repository default branch through GitHub metadata.
|
||||
*/
|
||||
readonly getDefaultBranch: (input: {
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<string | null, GitHubCliError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHubCli - Service tag for GitHub CLI process execution.
|
||||
*/
|
||||
export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()("git/GitHubCli") {}
|
||||
@@ -1,41 +0,0 @@
|
||||
/**
|
||||
* GitManager - Effect service contract for stacked Git workflows.
|
||||
*
|
||||
* Orchestrates status inspection and commit/push/PR flows by composing
|
||||
* lower-level Git and external tool services.
|
||||
*
|
||||
* @module GitManager
|
||||
*/
|
||||
import {
|
||||
GitRunStackedActionInput,
|
||||
GitRunStackedActionResult,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "../Errors.ts";
|
||||
|
||||
/**
|
||||
* GitManagerShape - Service API for high-level Git workflow actions.
|
||||
*/
|
||||
export interface GitManagerShape {
|
||||
/**
|
||||
* Read current repository Git status plus open PR metadata when available.
|
||||
*/
|
||||
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||
*/
|
||||
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
|
||||
"git/GitManager",
|
||||
) {}
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
* GitService - Service for Git command execution.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||
* domain errors for Git command execution.
|
||||
*
|
||||
* @module GitService
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface ExecuteGitInput {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
readonly code: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitServiceShape - Service API for Git command execution.
|
||||
*/
|
||||
export interface GitServiceShape {
|
||||
/**
|
||||
* Execute a Git command.
|
||||
*/
|
||||
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitService - Service for Git command execution.
|
||||
*/
|
||||
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
|
||||
"git/GitService",
|
||||
) {}
|
||||
@@ -1,71 +0,0 @@
|
||||
/**
|
||||
* TextGeneration - Effect service contract for AI-generated Git content.
|
||||
*
|
||||
* Generates commit messages and pull request titles/bodies from repository
|
||||
* context prepared by Git services.
|
||||
*
|
||||
* @module TextGeneration
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { TextGenerationError } from "../Errors.ts";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
subject: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationInput {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult>;
|
||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGenerationShape - Service API for commit/PR text generation.
|
||||
*/
|
||||
export interface TextGenerationShape {
|
||||
/**
|
||||
* Generate a commit message from staged change context.
|
||||
*/
|
||||
readonly generateCommitMessage: (
|
||||
input: CommitMessageGenerationInput,
|
||||
) => Effect.Effect<CommitMessageGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Generate pull request title/body from branch and diff context.
|
||||
*/
|
||||
readonly generatePrContent: (
|
||||
input: PrContentGenerationInput,
|
||||
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
*/
|
||||
export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
|
||||
"git/TextGeneration",
|
||||
) {}
|
||||
@@ -0,0 +1,482 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { GitManager } from "./gitManager";
|
||||
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
createdPrUrl?: string;
|
||||
defaultBranch?: string;
|
||||
failWith?: Error;
|
||||
}
|
||||
|
||||
interface FakeGitTextGenerator {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}) => Promise<{ subject: string; body: string }>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}) => Promise<{ title: string; body: string }>;
|
||||
}
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Promise<ProcessRunResult> {
|
||||
return runProcess("git", args, { cwd, allowNonZeroExit });
|
||||
}
|
||||
|
||||
async function runGitStdout(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await runGit(cwd, args);
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
async function initRepo(cwd: string): Promise<void> {
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
await runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
await runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "hello\n");
|
||||
await runGit(cwd, ["add", "README.md"]);
|
||||
await runGit(cwd, ["commit", "-m", "Initial commit"]);
|
||||
}
|
||||
|
||||
async function createBareRemote(): Promise<string> {
|
||||
const remoteDir = makeTempDir("t3code-git-remote-");
|
||||
await runProcess("git", ["init", "--bare"], { cwd: remoteDir });
|
||||
return remoteDir;
|
||||
}
|
||||
|
||||
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
|
||||
return {
|
||||
generateCommitMessage: async () => ({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
}),
|
||||
generatePrContent: async () => ({
|
||||
title: "Add stacked git actions",
|
||||
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
runner: (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>;
|
||||
ghCalls: string[];
|
||||
} {
|
||||
const prListQueue = [...(scenario.prListSequence ?? [])];
|
||||
const ghCalls: string[] = [];
|
||||
|
||||
const runner = async (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
): Promise<ProcessRunResult> => {
|
||||
if (command !== "gh") {
|
||||
return runProcess(command, args, options);
|
||||
}
|
||||
|
||||
ghCalls.push(args.join(" "));
|
||||
if (scenario.failWith) {
|
||||
throw scenario.failWith;
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "list") {
|
||||
const stdout = (prListQueue.shift() ?? "[]") + "\n";
|
||||
return {
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "create") {
|
||||
return {
|
||||
stdout:
|
||||
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "view") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (args[0] === "repo" && args[1] === "view") {
|
||||
return {
|
||||
stdout: `${scenario.defaultBranch ?? "main"}\n`,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected gh command: ${args.join(" ")}`);
|
||||
};
|
||||
|
||||
return { runner, ghCalls };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("GitManager", () => {
|
||||
it("status includes open PR metadata when branch already has an open PR", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
const status = await manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.openPr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
});
|
||||
});
|
||||
|
||||
it("status is resilient to gh lookup failures and returns openPr null", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
failWith: new Error("Command not found: gh"),
|
||||
});
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
const status = await manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.openPr).toBeNull();
|
||||
});
|
||||
|
||||
it("creates a commit when working tree is dirty", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
|
||||
"Implement stacked git actions",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses custom commit message when provided", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator({
|
||||
generateCommitMessage: async () => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
};
|
||||
},
|
||||
}),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
|
||||
"feat: custom summary line",
|
||||
);
|
||||
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%b"])).toContain(
|
||||
"- details from user",
|
||||
);
|
||||
});
|
||||
|
||||
it("skips commit when there are no uncommitted changes", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
});
|
||||
|
||||
it("commits and pushes with upstream auto-setup when needed", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
expect(await runGitStdout(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
"origin/feature/stacked-flow",
|
||||
);
|
||||
});
|
||||
|
||||
it("skips push when branch is already up to date", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
|
||||
it("returns existing PR metadata for commit/push/pr action", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
|
||||
|
||||
const { runner, ghCalls } = createRunnerWithFakeGh({
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 42,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/existing-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("opened_existing");
|
||||
expect(result.pr.number).toBe(42);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
});
|
||||
|
||||
it("creates PR when one does not already exist", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
|
||||
await runGit(repoDir, ["add", "changes.txt"]);
|
||||
await runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
|
||||
await runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
|
||||
|
||||
const { runner, ghCalls } = createRunnerWithFakeGh({
|
||||
prListSequence: [
|
||||
"[]",
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 88,
|
||||
title: "Add stacked git actions",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/88",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature-create-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||
).toBe(true);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects push/pr actions from detached HEAD", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "--detach", "HEAD"]);
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
await expect(
|
||||
manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
}),
|
||||
).rejects.toThrow("detached HEAD");
|
||||
});
|
||||
|
||||
it("surfaces missing gh binary errors", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
failWith: new Error("Command not found: gh"),
|
||||
});
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
await expect(
|
||||
manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}),
|
||||
).rejects.toThrow("GitHub CLI (`gh`) is required");
|
||||
});
|
||||
|
||||
it("surfaces gh auth errors with guidance", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
failWith: new Error("authentication failed"),
|
||||
});
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
await expect(
|
||||
manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}),
|
||||
).rejects.toThrow("gh auth login");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,467 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
gitRunStackedActionInputSchema,
|
||||
gitRunStackedActionResultSchema,
|
||||
gitStatusInputSchema,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type GitStatusInput,
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type {
|
||||
CommitMessageGenerationResult,
|
||||
PrContentGenerationResult,
|
||||
TextGenerationService,
|
||||
} from "./coreServices";
|
||||
import { CodexTextGenerator } from "./codexTextGenerator";
|
||||
import { GitCoreService } from "./git";
|
||||
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
|
||||
|
||||
const GH_CLI_TIMEOUT_MS = 30_000;
|
||||
|
||||
interface GitManagerDeps {
|
||||
runProcess?: (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>;
|
||||
textGenerator?: TextGenerationService;
|
||||
gitCore?: GitCoreService;
|
||||
}
|
||||
|
||||
interface OpenPrInfo {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
function parseOpenPrList(raw: unknown): OpenPrInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: OpenPrInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function trimStdout(value: string): string {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function limitContext(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitMessage(
|
||||
generated: CommitMessageGenerationResult,
|
||||
): CommitMessageGenerationResult {
|
||||
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
||||
const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
|
||||
return {
|
||||
subject: safeSubject,
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function parseCustomCommitMessage(raw: string): CommitMessageGenerationResult | null {
|
||||
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
||||
if (normalized.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [firstLine, ...rest] = normalized.split("\n");
|
||||
const subject = firstLine?.trim() ?? "";
|
||||
if (subject.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
subject,
|
||||
body: rest.join("\n").trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function extractBranchFromRef(ref: string): string {
|
||||
const normalized = ref.trim();
|
||||
|
||||
if (normalized.startsWith("refs/remotes/")) {
|
||||
const withoutPrefix = normalized.slice("refs/remotes/".length);
|
||||
const firstSlash = withoutPrefix.indexOf("/");
|
||||
if (firstSlash === -1) {
|
||||
return withoutPrefix.trim();
|
||||
}
|
||||
return withoutPrefix.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
const firstSlash = normalized.indexOf("/");
|
||||
if (firstSlash === -1) {
|
||||
return normalized;
|
||||
}
|
||||
return normalized.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
function asCommandNotFound(command: string, error: unknown): Error | undefined {
|
||||
if (!(error instanceof Error)) return undefined;
|
||||
if (!error.message.includes(`Command not found: ${command}`)) return undefined;
|
||||
if (command === "gh") {
|
||||
return new Error("GitHub CLI (`gh`) is required but not available on PATH.");
|
||||
}
|
||||
if (command === "codex") {
|
||||
return new Error("Codex CLI (`codex`) is required but not available on PATH.");
|
||||
}
|
||||
return new Error(`${command} is required but not available on PATH.`);
|
||||
}
|
||||
|
||||
function normalizeGitHubAuthError(error: unknown): Error | undefined {
|
||||
if (!(error instanceof Error)) return undefined;
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new Error("GitHub CLI is not authenticated. Run `gh auth login` and retry.");
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
};
|
||||
}
|
||||
|
||||
export class GitManager {
|
||||
private readonly run: NonNullable<GitManagerDeps["runProcess"]>;
|
||||
private readonly textGenerator: TextGenerationService;
|
||||
private readonly gitCore: GitCoreService;
|
||||
|
||||
constructor(deps: GitManagerDeps = {}) {
|
||||
this.run = deps.runProcess ?? runProcess;
|
||||
this.textGenerator = deps.textGenerator ?? new CodexTextGenerator();
|
||||
this.gitCore = deps.gitCore ?? new GitCoreService();
|
||||
}
|
||||
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.gitCore.statusDetails(input.cwd);
|
||||
|
||||
let openPr: ReturnType<typeof toStatusOpenPr> | null = null;
|
||||
if (details.branch && details.hasUpstream) {
|
||||
try {
|
||||
const existing = await this.findOpenPr(input.cwd, details.branch);
|
||||
if (existing) {
|
||||
openPr = toStatusOpenPr(existing);
|
||||
}
|
||||
} catch {
|
||||
// PR lookup is best-effort for status rendering.
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
workingTree: details.workingTree,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr,
|
||||
};
|
||||
}
|
||||
|
||||
async runStackedAction(raw: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
|
||||
const input = gitRunStackedActionInputSchema.parse(raw);
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
const initialStatus = await this.gitCore.statusDetails(input.cwd);
|
||||
if (wantsPush && !initialStatus.branch) {
|
||||
throw new Error("Cannot push from detached HEAD.");
|
||||
}
|
||||
if (wantsPr && !initialStatus.branch) {
|
||||
throw new Error("Cannot create a pull request from detached HEAD.");
|
||||
}
|
||||
|
||||
const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
||||
|
||||
const push = wantsPush
|
||||
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? await this.runPrStep(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return gitRunStackedActionResultSchema.parse({
|
||||
action: input.action,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
});
|
||||
}
|
||||
|
||||
private async runCommitStep(
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
): Promise<{
|
||||
status: "created" | "skipped_no_changes";
|
||||
commitSha?: string | undefined;
|
||||
subject?: string | undefined;
|
||||
}> {
|
||||
const context = await this.gitCore.prepareCommitContext(cwd);
|
||||
if (!context) {
|
||||
return { status: "skipped_no_changes" };
|
||||
}
|
||||
|
||||
let generated: CommitMessageGenerationResult | null = parseCustomCommitMessage(
|
||||
commitMessage ?? "",
|
||||
);
|
||||
|
||||
if (!generated) {
|
||||
try {
|
||||
generated = sanitizeCommitMessage(
|
||||
await this.textGenerator.generateCommitMessage({
|
||||
cwd,
|
||||
branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
throw asCommandNotFound("codex", error) ?? error;
|
||||
}
|
||||
}
|
||||
|
||||
const { commitSha } = await this.gitCore.commit(cwd, generated.subject, generated.body);
|
||||
return {
|
||||
status: "created",
|
||||
commitSha,
|
||||
subject: generated.subject,
|
||||
};
|
||||
}
|
||||
|
||||
private async runPrStep(
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
): Promise<{
|
||||
status: "created" | "opened_existing" | "skipped_not_requested";
|
||||
url?: string | undefined;
|
||||
number?: number | undefined;
|
||||
baseBranch?: string | undefined;
|
||||
headBranch?: string | undefined;
|
||||
title?: string | undefined;
|
||||
}> {
|
||||
const details = await this.gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
throw new Error("Cannot create a pull request from detached HEAD.");
|
||||
}
|
||||
if (!details.hasUpstream) {
|
||||
throw new Error("Current branch has not been pushed. Push before creating a PR.");
|
||||
}
|
||||
|
||||
const existing = await this.findOpenPr(cwd, branch);
|
||||
if (existing) {
|
||||
return {
|
||||
status: "opened_existing",
|
||||
url: existing.url,
|
||||
number: existing.number,
|
||||
baseBranch: existing.baseRefName,
|
||||
headBranch: existing.headRefName,
|
||||
title: existing.title,
|
||||
};
|
||||
}
|
||||
|
||||
const baseBranch = await this.resolveBaseBranch(cwd, branch, details.upstreamRef);
|
||||
const rangeContext = await this.gitCore.readRangeContext(cwd, baseBranch);
|
||||
|
||||
let generated: PrContentGenerationResult;
|
||||
try {
|
||||
generated = await this.textGenerator.generatePrContent({
|
||||
cwd,
|
||||
baseBranch,
|
||||
headBranch: branch,
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
});
|
||||
} catch (error) {
|
||||
throw asCommandNotFound("codex", error) ?? error;
|
||||
}
|
||||
|
||||
const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
||||
await fs.writeFile(bodyFile, generated.body, "utf8");
|
||||
|
||||
try {
|
||||
await this.runGh(cwd, [
|
||||
"pr",
|
||||
"create",
|
||||
"--base",
|
||||
baseBranch,
|
||||
"--head",
|
||||
branch,
|
||||
"--title",
|
||||
generated.title,
|
||||
"--body-file",
|
||||
bodyFile,
|
||||
]);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(bodyFile);
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
}
|
||||
|
||||
const created = await this.findOpenPr(cwd, branch);
|
||||
|
||||
if (!created) {
|
||||
return {
|
||||
status: "created",
|
||||
baseBranch,
|
||||
headBranch: branch,
|
||||
title: generated.title,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: "created",
|
||||
url: created.url,
|
||||
number: created.number,
|
||||
baseBranch: created.baseRefName,
|
||||
headBranch: created.headRefName,
|
||||
title: created.title,
|
||||
};
|
||||
}
|
||||
|
||||
private async findOpenPr(cwd: string, branch: string): Promise<OpenPrInfo | null> {
|
||||
const stdout = await this.runGhStdout(cwd, [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"open",
|
||||
"--limit",
|
||||
"1",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName",
|
||||
]);
|
||||
|
||||
const raw = trimStdout(stdout);
|
||||
if (raw.length === 0) return null;
|
||||
|
||||
let parsedJson: unknown;
|
||||
try {
|
||||
parsedJson = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new Error("GitHub CLI returned invalid PR list JSON.");
|
||||
}
|
||||
|
||||
const parsed = parseOpenPrList(parsedJson);
|
||||
return parsed[0] ?? null;
|
||||
}
|
||||
|
||||
private async resolveBaseBranch(
|
||||
cwd: string,
|
||||
branch: string,
|
||||
upstreamRef: string | null,
|
||||
): Promise<string> {
|
||||
const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||
if (configured) return configured;
|
||||
|
||||
if (upstreamRef) {
|
||||
const upstreamBranch = extractBranchFromRef(upstreamRef);
|
||||
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
|
||||
return upstreamBranch;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const ghDefault = await this.runGhStdout(cwd, [
|
||||
"repo",
|
||||
"view",
|
||||
"--json",
|
||||
"defaultBranchRef",
|
||||
"--jq",
|
||||
".defaultBranchRef.name",
|
||||
]);
|
||||
const defaultBranch = trimStdout(ghDefault);
|
||||
if (defaultBranch.length > 0) return defaultBranch;
|
||||
} catch {
|
||||
// Fall through to deterministic fallback.
|
||||
}
|
||||
|
||||
return "main";
|
||||
}
|
||||
|
||||
private async runGh(cwd: string, args: readonly string[]): Promise<void> {
|
||||
await this.runGhCommand(cwd, args);
|
||||
}
|
||||
|
||||
private async runGhStdout(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await this.runGhCommand(cwd, args);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
private async runGhCommand(cwd: string, args: readonly string[]): Promise<ProcessRunResult> {
|
||||
try {
|
||||
return await this.run("gh", args, {
|
||||
cwd,
|
||||
timeoutMs: GH_CLI_TIMEOUT_MS,
|
||||
});
|
||||
} catch (error) {
|
||||
throw (
|
||||
asCommandNotFound("gh", error) ??
|
||||
normalizeGitHubAuthError(error) ??
|
||||
(error instanceof Error ? error : new Error("GitHub CLI command failed."))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+173
-18
@@ -1,21 +1,176 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { CliConfig, t3Cli } from "./main";
|
||||
import { OpenLive } from "./open";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
import { NetService } from "./config";
|
||||
import { fixPath } from "./fixPath";
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { createServer } from "./wsServer";
|
||||
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
Layer.provideMerge(ServerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
fixPath();
|
||||
|
||||
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
|
||||
const DEFAULT_PORT = 3773;
|
||||
const cwd = process.cwd();
|
||||
const logger = createLogger("server");
|
||||
|
||||
type RuntimeMode = "web" | "desktop";
|
||||
|
||||
function parseBooleanEnv(value: string | undefined): boolean | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) return true;
|
||||
if (["0", "false", "no", "off"].includes(normalized)) return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parsePort(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
|
||||
throw new Error(`Invalid T3CODE_PORT: ${value}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function expandHomePath(input: string): string {
|
||||
if (input === "~") return os.homedir();
|
||||
if (input.startsWith("~/")) {
|
||||
return path.join(os.homedir(), input.slice(2));
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
function resolveStateDir(raw: string | undefined): string {
|
||||
if (!raw || raw.trim().length === 0) {
|
||||
return path.join(os.homedir(), ".t3", "userdata");
|
||||
}
|
||||
return path.resolve(expandHomePath(raw.trim()));
|
||||
}
|
||||
|
||||
async function findAvailablePort(preferred: number): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.listen(preferred, () => {
|
||||
server.close(() => resolve(preferred));
|
||||
});
|
||||
server.on("error", () => {
|
||||
// Preferred port busy — let the OS pick one
|
||||
const fallback = net.createServer();
|
||||
fallback.listen(0, () => {
|
||||
const addr = fallback.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
fallback.close(() => {
|
||||
if (port > 0) resolve(port);
|
||||
else reject(new Error("Could not find an available port."));
|
||||
});
|
||||
});
|
||||
fallback.on("error", reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function resolveStaticDir(): string | undefined {
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// Check for bundled client (npm publish / npx scenario):
|
||||
// dist/client/ lives alongside dist/index.js
|
||||
const bundledClient = path.resolve(__dirname, "client");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(bundledClient, "index.html"));
|
||||
if (stat.isFile()) return bundledClient;
|
||||
} catch {
|
||||
// Not bundled — check monorepo layout
|
||||
}
|
||||
|
||||
// Monorepo layout: apps/server/dist/index.js → apps/web/dist/
|
||||
const monorepoClient = path.resolve(__dirname, "../../web/dist");
|
||||
try {
|
||||
const stat = fs.statSync(path.join(monorepoClient, "index.html"));
|
||||
if (stat.isFile()) return monorepoClient;
|
||||
} catch {
|
||||
// Not found — probably dev mode, Vite will serve
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web";
|
||||
const requestedPort = parsePort(process.env.T3CODE_PORT);
|
||||
const port =
|
||||
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
|
||||
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const projectRegistry = new ProjectRegistry(stateDir);
|
||||
const devUrl = process.env.VITE_DEV_SERVER_URL;
|
||||
const noBrowser = parseBooleanEnv(process.env.T3CODE_NO_BROWSER) ?? mode === "desktop";
|
||||
const authToken = process.env.T3CODE_AUTH_TOKEN;
|
||||
const staticDir = devUrl ? undefined : resolveStaticDir();
|
||||
|
||||
if (!devUrl && !staticDir) {
|
||||
logger.warn("web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable", {
|
||||
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
});
|
||||
}
|
||||
|
||||
const server = createServer({
|
||||
port,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
staticDir,
|
||||
devUrl,
|
||||
projectRegistry,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
|
||||
const url = `http://localhost:${port}`;
|
||||
logger.info("T3 Code running", {
|
||||
url,
|
||||
cwd,
|
||||
mode,
|
||||
stateDir,
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
// Open browser (dynamic import because `open` is ESM-only)
|
||||
if (!noBrowser) {
|
||||
try {
|
||||
const open = await import("open");
|
||||
const target = devUrl ?? url;
|
||||
await open.default(target);
|
||||
} catch {
|
||||
logger.info("browser auto-open unavailable", {
|
||||
hint: `Open ${devUrl ?? url} in your browser.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Graceful shutdown
|
||||
let shuttingDown = false;
|
||||
async function shutdown() {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
logger.info("shutting down");
|
||||
try {
|
||||
await server.stop();
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
logger.error("failed to stop server cleanly", { error });
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
void shutdown();
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
void shutdown();
|
||||
});
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
logger.error("failed to start T3 Code", { error: err });
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,479 +0,0 @@
|
||||
import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
Keybindings,
|
||||
KeybindingsConfigError,
|
||||
KeybindingsLive,
|
||||
ResolvedKeybindingFromConfig,
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
} from "./keybindings";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const makeKeybindingsLayer = () =>
|
||||
KeybindingsLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { join } = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
|
||||
const configPath = join(dir, "keybindings.json");
|
||||
return { keybindingsConfigPath: configPath } as ServerConfigShape;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
||||
effect.pipe(
|
||||
Effect.mapError((error) => error.detail),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
|
||||
yield* fileSystem.writeFileString(configPath, encoded);
|
||||
});
|
||||
|
||||
const readKeybindingsConfig = (configPath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const rawConfig = yield* fileSystem.readFileString(configPath);
|
||||
return yield* Schema.decodeUnknownEffect(KeybindingsConfigJson)(rawConfig);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
it.effect("parses shortcuts including plus key", () =>
|
||||
Effect.sync(() => {
|
||||
assert.deepEqual(parseKeybindingShortcut("mod+j"), {
|
||||
key: "j",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
});
|
||||
assert.deepEqual(parseKeybindingShortcut("mod++"), {
|
||||
key: "+",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("compiles valid rule with parsed when AST", () =>
|
||||
Effect.sync(() => {
|
||||
const compiled = compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalOpen && !terminalFocus",
|
||||
});
|
||||
|
||||
assert.deepEqual(compiled, {
|
||||
command: "terminal.split",
|
||||
shortcut: {
|
||||
key: "d",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "and",
|
||||
left: { type: "identifier", name: "terminalOpen" },
|
||||
right: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("encodes resolved plus-key shortcuts", () =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* Schema.encodeEffect(ResolvedKeybindingFromConfig)({
|
||||
command: "terminal.toggle",
|
||||
shortcut: {
|
||||
key: "+",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(encoded.key, "mod++");
|
||||
assert.equal(encoded.command, "terminal.toggle");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid rules", () =>
|
||||
Effect.sync(() => {
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+shift+d+o",
|
||||
command: "terminal.new",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalFocus && (",
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: `${"!".repeat(300)}terminalFocus`,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("bootstraps default keybindings when config file is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
assert.isFalse(yield* fs.exists(keybindingsConfigPath));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
yield* keybindings.syncDefaultKeybindingsOnStartup;
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
assert.deepEqual(persisted, DEFAULT_KEYBINDINGS);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("uses defaults in runtime when config is malformed without overriding file", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
|
||||
|
||||
const configState = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.loadConfigState;
|
||||
});
|
||||
|
||||
assert.deepEqual(configState.keybindings, compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS));
|
||||
assert.deepEqual(configState.issues, [
|
||||
{
|
||||
kind: "keybindings.malformed-config",
|
||||
message: configState.issues[0]?.message ?? "",
|
||||
},
|
||||
]);
|
||||
assert.equal(yield* fs.readFileString(keybindingsConfigPath), "{ not-json");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("ignores invalid entries in runtime and reports them as issues", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* fs.writeFileString(
|
||||
keybindingsConfigPath,
|
||||
JSON.stringify([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+d+o", command: "terminal.new" },
|
||||
{ key: "mod+x", command: "invalid.command" },
|
||||
]),
|
||||
);
|
||||
|
||||
const configState = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.loadConfigState;
|
||||
});
|
||||
|
||||
assert.isTrue(configState.keybindings.some((entry) => entry.command === "terminal.toggle"));
|
||||
assert.isFalse(configState.keybindings.some((entry) => entry.command === "invalid.command"));
|
||||
assert.deepEqual(configState.issues, [
|
||||
{ kind: "keybindings.invalid-entry", index: 1, message: configState.issues[0]?.message ?? "" },
|
||||
{ kind: "keybindings.invalid-entry", index: 2, message: configState.issues[1]?.message ?? "" },
|
||||
]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"upserts missing default keybindings on startup without overriding existing command rules",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+shift+t", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
yield* keybindings.syncDefaultKeybindingsOnStartup;
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const byCommand = new Map(persisted.map((entry) => [entry.command, entry]));
|
||||
|
||||
const persistedToggle = byCommand.get("terminal.toggle");
|
||||
assert.isNotNull(persistedToggle);
|
||||
assert.equal(persistedToggle?.key, "mod+shift+t");
|
||||
assert.isFalse(
|
||||
persisted.some((entry) => entry.command === "terminal.toggle" && entry.key === "mod+j"),
|
||||
);
|
||||
|
||||
for (const defaultRule of DEFAULT_KEYBINDINGS) {
|
||||
assert.isTrue(byCommand.has(defaultRule.command), `expected ${defaultRule.command}`);
|
||||
}
|
||||
assert.isTrue(byCommand.has("script.run-tests.run"));
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("skips conflicting default keybindings on startup and logs a detailed warning", () => {
|
||||
const messages: string[] = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
messages.push(String(message));
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+j", command: "script.custom-action.run" },
|
||||
]);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
yield* keybindings.syncDefaultKeybindingsOnStartup;
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
assert.isFalse(persisted.some((entry) => entry.command === "terminal.toggle"));
|
||||
assert.isTrue(persisted.some((entry) => entry.command === "script.custom-action.run"));
|
||||
|
||||
assert.isTrue(
|
||||
messages.some((message) =>
|
||||
message.includes("skipping default keybinding due to shortcut conflict"),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeKeybindingsLayer(),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("upserts custom keybindings to configured path", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
]);
|
||||
|
||||
const resolved = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
|
||||
assert.deepEqual(persistedView, [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
assert.isTrue(resolved.some((entry) => entry.command === "script.run-tests.run"));
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("replaces existing custom keybinding for the same command", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("refuses to overwrite malformed keybindings config", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* fs.writeFileString(keybindingsConfigPath, "{ not-json");
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(result, "expected JSON array");
|
||||
|
||||
const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
|
||||
assert.equal(persistedRaw, "{ not-json");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("reports non-array config parse errors without duplicate prefix", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* fs.writeFileString(
|
||||
keybindingsConfigPath,
|
||||
'{"key":"mod+j","command":"terminal.toggle"}',
|
||||
);
|
||||
|
||||
const firstResult = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(firstResult, "expected JSON array");
|
||||
|
||||
const secondResult = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(secondResult, "expected JSON array");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("fails when config directory is not writable", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
const { dirname } = yield* Path.Path;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
]);
|
||||
yield* fs.chmod(dirname(keybindingsConfigPath), 0o500);
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
}).pipe(toDetailResult);
|
||||
assertFailure(result, "failed to write keybindings config");
|
||||
|
||||
yield* fs.chmod(dirname(keybindingsConfigPath), 0o700);
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
assert.deepEqual(persistedView, [{ key: "mod+j", command: "terminal.toggle" }]);
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("caches loaded resolved config across repeated reads", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
]);
|
||||
|
||||
const [first, second] = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
const firstLoad = (yield* keybindings.loadConfigState).keybindings;
|
||||
const secondLoad = (yield* keybindings.loadConfigState).keybindings;
|
||||
return [firstLoad, secondLoad] as const;
|
||||
});
|
||||
|
||||
assert.deepEqual(first, second);
|
||||
assert.isTrue(second.some((entry) => entry.command === "terminal.toggle"));
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("updates cached resolved config after upsert", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
]);
|
||||
|
||||
const loadedAfterUpsert = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
yield* keybindings.loadConfigState;
|
||||
yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
return (yield* keybindings.loadConfigState).keybindings;
|
||||
});
|
||||
|
||||
assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "script.run-tests.run"));
|
||||
assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "terminal.toggle"));
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent upserts to avoid lost updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, []);
|
||||
|
||||
const commands = Array.from(
|
||||
{ length: 20 },
|
||||
(_, index): KeybindingCommand => `script.concurrent-${index}.run`,
|
||||
);
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
yield* Effect.all(
|
||||
commands.map((command, index) =>
|
||||
keybindings.upsertKeybindingRule({
|
||||
key: `mod+${String.fromCharCode(97 + index)}`,
|
||||
command,
|
||||
}),
|
||||
),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedCommands = new Set(persisted.map((entry) => entry.command));
|
||||
for (const command of commands) {
|
||||
assert.isTrue(persistedCommands.has(command), `expected persisted command ${command}`);
|
||||
}
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
});
|
||||
@@ -1,842 +0,0 @@
|
||||
/**
|
||||
* Keybindings - Keybinding configuration service definitions.
|
||||
*
|
||||
* Owns parsing, validation, merge, and persistence of user keybinding
|
||||
* configuration consumed by the server runtime.
|
||||
*
|
||||
* @module Keybindings
|
||||
*/
|
||||
import {
|
||||
KeybindingRule,
|
||||
KeybindingsConfig,
|
||||
KeybindingShortcut,
|
||||
KeybindingWhenNode,
|
||||
MAX_KEYBINDINGS_COUNT,
|
||||
MAX_WHEN_EXPRESSION_DEPTH,
|
||||
ResolvedKeybindingRule,
|
||||
ResolvedKeybindingsConfig,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import { Mutable } from "effect/Types";
|
||||
import {
|
||||
Array,
|
||||
Cache,
|
||||
Cause,
|
||||
Effect,
|
||||
FileSystem,
|
||||
Path,
|
||||
Layer,
|
||||
Option,
|
||||
Predicate,
|
||||
PubSub,
|
||||
Schema,
|
||||
SchemaGetter,
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
ServiceMap,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
|
||||
"KeybindingsConfigParseError",
|
||||
{
|
||||
configPath: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
type WhenToken =
|
||||
| { type: "identifier"; value: string }
|
||||
| { type: "not" }
|
||||
| { type: "and" }
|
||||
| { type: "or" }
|
||||
| { type: "lparen" }
|
||||
| { type: "rparen" };
|
||||
|
||||
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
{ key: "mod+o", command: "editor.openFavorite" },
|
||||
];
|
||||
|
||||
function normalizeKeyToken(token: string): string {
|
||||
if (token === "space") return " ";
|
||||
if (token === "esc") return "escape";
|
||||
return token;
|
||||
}
|
||||
|
||||
/** @internal - Exported for testing */
|
||||
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
|
||||
const rawTokens = value
|
||||
.toLowerCase()
|
||||
.split("+")
|
||||
.map((token) => token.trim());
|
||||
const tokens = [...rawTokens];
|
||||
let trailingEmptyCount = 0;
|
||||
while (tokens[tokens.length - 1] === "") {
|
||||
trailingEmptyCount += 1;
|
||||
tokens.pop();
|
||||
}
|
||||
if (trailingEmptyCount > 0) {
|
||||
tokens.push("+");
|
||||
}
|
||||
if (tokens.some((token) => token.length === 0)) {
|
||||
return null;
|
||||
}
|
||||
if (tokens.length === 0) return null;
|
||||
|
||||
let key: string | null = null;
|
||||
let metaKey = false;
|
||||
let ctrlKey = false;
|
||||
let shiftKey = false;
|
||||
let altKey = false;
|
||||
let modKey = false;
|
||||
|
||||
for (const token of tokens) {
|
||||
switch (token) {
|
||||
case "cmd":
|
||||
case "meta":
|
||||
metaKey = true;
|
||||
break;
|
||||
case "ctrl":
|
||||
case "control":
|
||||
ctrlKey = true;
|
||||
break;
|
||||
case "shift":
|
||||
shiftKey = true;
|
||||
break;
|
||||
case "alt":
|
||||
case "option":
|
||||
altKey = true;
|
||||
break;
|
||||
case "mod":
|
||||
modKey = true;
|
||||
break;
|
||||
default: {
|
||||
if (key !== null) return null;
|
||||
key = normalizeKeyToken(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (key === null) return null;
|
||||
return {
|
||||
key,
|
||||
metaKey,
|
||||
ctrlKey,
|
||||
shiftKey,
|
||||
altKey,
|
||||
modKey,
|
||||
};
|
||||
}
|
||||
|
||||
function tokenizeWhenExpression(expression: string): WhenToken[] | null {
|
||||
const tokens: WhenToken[] = [];
|
||||
let index = 0;
|
||||
|
||||
while (index < expression.length) {
|
||||
const current = expression[index];
|
||||
if (!current) break;
|
||||
|
||||
if (/\s/.test(current)) {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (expression.startsWith("&&", index)) {
|
||||
tokens.push({ type: "and" });
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (expression.startsWith("||", index)) {
|
||||
tokens.push({ type: "or" });
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
if (current === "!") {
|
||||
tokens.push({ type: "not" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (current === "(") {
|
||||
tokens.push({ type: "lparen" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (current === ")") {
|
||||
tokens.push({ type: "rparen" });
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));
|
||||
if (!identifier) {
|
||||
return null;
|
||||
}
|
||||
tokens.push({ type: "identifier", value: identifier[0] });
|
||||
index += identifier[0].length;
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
|
||||
const tokens = tokenizeWhenExpression(expression);
|
||||
if (!tokens || tokens.length === 0) return null;
|
||||
let index = 0;
|
||||
|
||||
const parsePrimary = (depth: number): KeybindingWhenNode | null => {
|
||||
if (depth > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||
return null;
|
||||
}
|
||||
const token = tokens[index];
|
||||
if (!token) return null;
|
||||
|
||||
if (token.type === "identifier") {
|
||||
index += 1;
|
||||
return { type: "identifier", name: token.value };
|
||||
}
|
||||
|
||||
if (token.type === "lparen") {
|
||||
index += 1;
|
||||
const expressionNode = parseOr(depth + 1);
|
||||
const closeToken = tokens[index];
|
||||
if (!expressionNode || !closeToken || closeToken.type !== "rparen") {
|
||||
return null;
|
||||
}
|
||||
index += 1;
|
||||
return expressionNode;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseUnary = (depth: number): KeybindingWhenNode | null => {
|
||||
let notCount = 0;
|
||||
while (tokens[index]?.type === "not") {
|
||||
index += 1;
|
||||
notCount += 1;
|
||||
if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let node = parsePrimary(depth);
|
||||
if (!node) return null;
|
||||
|
||||
while (notCount > 0) {
|
||||
node = { type: "not", node };
|
||||
notCount -= 1;
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
const parseAnd = (depth: number): KeybindingWhenNode | null => {
|
||||
let left = parseUnary(depth);
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "and") {
|
||||
index += 1;
|
||||
const right = parseUnary(depth);
|
||||
if (!right) return null;
|
||||
left = { type: "and", left, right };
|
||||
}
|
||||
|
||||
return left;
|
||||
};
|
||||
|
||||
const parseOr = (depth: number): KeybindingWhenNode | null => {
|
||||
let left = parseAnd(depth);
|
||||
if (!left) return null;
|
||||
|
||||
while (tokens[index]?.type === "or") {
|
||||
index += 1;
|
||||
const right = parseAnd(depth);
|
||||
if (!right) return null;
|
||||
left = { type: "or", left, right };
|
||||
}
|
||||
|
||||
return left;
|
||||
};
|
||||
|
||||
const ast = parseOr(0);
|
||||
if (!ast || index !== tokens.length) return null;
|
||||
return ast;
|
||||
}
|
||||
|
||||
/** @internal - Exported for testing */
|
||||
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
|
||||
const shortcut = parseKeybindingShortcut(rule.key);
|
||||
if (!shortcut) return null;
|
||||
|
||||
if (rule.when !== undefined) {
|
||||
const whenAst = parseKeybindingWhenExpression(rule.when);
|
||||
if (!whenAst) return null;
|
||||
return {
|
||||
command: rule.command,
|
||||
shortcut,
|
||||
whenAst,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
command: rule.command,
|
||||
shortcut,
|
||||
};
|
||||
}
|
||||
|
||||
export function compileResolvedKeybindingsConfig(
|
||||
config: KeybindingsConfig,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const compiled: Mutable<ResolvedKeybindingsConfig> = [];
|
||||
for (const rule of config) {
|
||||
const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
|
||||
if (result._tag === "Success") {
|
||||
compiled.push(result.value);
|
||||
}
|
||||
}
|
||||
return compiled;
|
||||
}
|
||||
|
||||
export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ResolvedKeybindingRule),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (rule) =>
|
||||
Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(
|
||||
Effect.filterOrFail(
|
||||
Predicate.isNotNull,
|
||||
() =>
|
||||
new SchemaIssue.InvalidValue(Option.some(rule), {
|
||||
title: "Invalid keybinding rule",
|
||||
}),
|
||||
),
|
||||
Effect.map((resolved) => resolved),
|
||||
),
|
||||
|
||||
encode: (resolved) =>
|
||||
Effect.gen(function* () {
|
||||
const key = encodeShortcut(resolved.shortcut);
|
||||
if (!key) {
|
||||
return yield* Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(resolved), {
|
||||
title: "Resolved shortcut cannot be encoded to key string",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;
|
||||
return {
|
||||
key,
|
||||
command: resolved.command,
|
||||
when,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(
|
||||
Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),
|
||||
);
|
||||
|
||||
function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {
|
||||
return (
|
||||
left.command === right.command &&
|
||||
left.key === right.key &&
|
||||
(left.when ?? undefined) === (right.when ?? undefined)
|
||||
);
|
||||
}
|
||||
|
||||
function keybindingShortcutContext(rule: KeybindingRule): string | null {
|
||||
const parsed = parseKeybindingShortcut(rule.key);
|
||||
if (!parsed) return null;
|
||||
const encoded = encodeShortcut(parsed);
|
||||
if (!encoded) return null;
|
||||
return `${encoded}\u0000${rule.when ?? ""}`;
|
||||
}
|
||||
|
||||
function hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {
|
||||
const leftContext = keybindingShortcutContext(left);
|
||||
const rightContext = keybindingShortcutContext(right);
|
||||
if (!leftContext || !rightContext) return false;
|
||||
return leftContext === rightContext;
|
||||
}
|
||||
|
||||
function encodeShortcut(shortcut: KeybindingShortcut): string | null {
|
||||
const modifiers: string[] = [];
|
||||
if (shortcut.modKey) modifiers.push("mod");
|
||||
if (shortcut.metaKey) modifiers.push("meta");
|
||||
if (shortcut.ctrlKey) modifiers.push("ctrl");
|
||||
if (shortcut.altKey) modifiers.push("alt");
|
||||
if (shortcut.shiftKey) modifiers.push("shift");
|
||||
if (!shortcut.key) return null;
|
||||
if (shortcut.key !== "+" && shortcut.key.includes("+")) return null;
|
||||
const key = shortcut.key === " " ? "space" : shortcut.key;
|
||||
return [...modifiers, key].join("+");
|
||||
}
|
||||
|
||||
function encodeWhenAst(node: KeybindingWhenNode): string {
|
||||
switch (node.type) {
|
||||
case "identifier":
|
||||
return node.name;
|
||||
case "not":
|
||||
return `!(${encodeWhenAst(node.node)})`;
|
||||
case "and":
|
||||
return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;
|
||||
case "or":
|
||||
return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
||||
|
||||
const RawKeybindingsEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown));
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
);
|
||||
const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
|
||||
Schema.encode({
|
||||
decode: PrettyJsonString,
|
||||
encode: PrettyJsonString,
|
||||
}),
|
||||
);
|
||||
|
||||
export interface KeybindingsConfigState {
|
||||
readonly keybindings: ResolvedKeybindingsConfig;
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
}
|
||||
|
||||
export interface KeybindingsChangeEvent {
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
}
|
||||
|
||||
function trimIssueMessage(message: string): string {
|
||||
const trimmed = message.trim();
|
||||
return trimmed.length > 0 ? trimmed : "Invalid keybindings configuration.";
|
||||
}
|
||||
|
||||
function malformedConfigIssue(detail: string): ServerConfigIssue {
|
||||
return {
|
||||
kind: "keybindings.malformed-config",
|
||||
message: trimIssueMessage(detail),
|
||||
};
|
||||
}
|
||||
|
||||
function invalidEntryIssue(index: number, detail: string): ServerConfigIssue {
|
||||
return {
|
||||
kind: "keybindings.invalid-entry",
|
||||
index,
|
||||
message: trimIssueMessage(detail),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
if (custom.length === 0) {
|
||||
return [...DEFAULT_RESOLVED_KEYBINDINGS];
|
||||
}
|
||||
|
||||
const overriddenCommands = new Set(custom.map((binding) => binding.command));
|
||||
const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(
|
||||
(binding) => !overriddenCommands.has(binding.command),
|
||||
);
|
||||
const merged = [...retainedDefaults, ...custom];
|
||||
|
||||
if (merged.length <= MAX_KEYBINDINGS_COUNT) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
|
||||
return merged.slice(-MAX_KEYBINDINGS_COUNT);
|
||||
}
|
||||
|
||||
/**
|
||||
* KeybindingsShape - Service API for keybinding configuration operations.
|
||||
*/
|
||||
export interface KeybindingsShape {
|
||||
/**
|
||||
* Ensure the on-disk keybindings file exists and includes all default
|
||||
* commands so newly-added defaults are backfilled on startup.
|
||||
*/
|
||||
readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;
|
||||
|
||||
/**
|
||||
* Load runtime keybindings state along with non-fatal configuration issues.
|
||||
*/
|
||||
readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;
|
||||
|
||||
/**
|
||||
* Stream keybindings config change events.
|
||||
*/
|
||||
readonly changes: Stream.Stream<KeybindingsChangeEvent>;
|
||||
|
||||
/**
|
||||
* Upsert a keybinding rule and persist the resulting configuration.
|
||||
*
|
||||
* Writes config atomically and enforces the max rule count by truncating
|
||||
* oldest entries when needed.
|
||||
*/
|
||||
readonly upsertKeybindingRule: (
|
||||
rule: KeybindingRule,
|
||||
) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keybindings - Service tag for keybinding configuration operations.
|
||||
*/
|
||||
export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
|
||||
"server/Keybindings",
|
||||
) {}
|
||||
|
||||
const makeKeybindings = Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const upsertSemaphore = yield* Semaphore.make(1);
|
||||
const resolvedConfigCacheKey = "resolved" as const;
|
||||
const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();
|
||||
|
||||
const emitChange = (issues: readonly ServerConfigIssue[]) =>
|
||||
PubSub.publish(changesPubSub, { issues }).pipe(Effect.asVoid);
|
||||
|
||||
const readConfigExists = fs.exists(keybindingsConfigPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to access keybindings config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to read keybindings config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
|
||||
readonly KeybindingRule[],
|
||||
KeybindingsConfigError
|
||||
> {
|
||||
if (!(yield* readConfigExists)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rawConfig = yield* readRawConfig.pipe(
|
||||
Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "expected JSON array",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Effect.forEach(rawConfig, (entry) =>
|
||||
Effect.gen(function* () {
|
||||
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
entry,
|
||||
error: Cause.pretty(decodedRule.cause),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
|
||||
if (resolved._tag === "Failure") {
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
entry,
|
||||
error: Cause.pretty(resolved.cause),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
return decodedRule.value;
|
||||
}),
|
||||
).pipe(Effect.map(Array.filter(Predicate.isNotNull)));
|
||||
});
|
||||
|
||||
const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
|
||||
{
|
||||
readonly keybindings: readonly KeybindingRule[];
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
},
|
||||
KeybindingsConfigError
|
||||
> {
|
||||
if (!(yield* readConfigExists)) {
|
||||
return { keybindings: [], issues: [] };
|
||||
}
|
||||
|
||||
const rawConfig = yield* readRawConfig;
|
||||
const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig);
|
||||
if (decodedEntries._tag === "Failure") {
|
||||
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
|
||||
return {
|
||||
keybindings: [],
|
||||
issues: [malformedConfigIssue(detail)],
|
||||
};
|
||||
}
|
||||
|
||||
const keybindings: KeybindingRule[] = [];
|
||||
const issues: ServerConfigIssue[] = [];
|
||||
for (const [index, entry] of decodedEntries.value.entries()) {
|
||||
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
|
||||
if (decodedRule._tag === "Failure") {
|
||||
const detail = Cause.pretty(decodedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
index,
|
||||
entry,
|
||||
error: detail,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
|
||||
if (resolvedRule._tag === "Failure") {
|
||||
const detail = Cause.pretty(resolvedRule.cause);
|
||||
issues.push(invalidEntryIssue(index, detail));
|
||||
yield* Effect.logWarning("ignoring invalid keybinding entry", {
|
||||
path: keybindingsConfigPath,
|
||||
index,
|
||||
entry,
|
||||
error: detail,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
keybindings.push(decodedRule.value);
|
||||
}
|
||||
|
||||
return { keybindings, issues };
|
||||
});
|
||||
|
||||
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
|
||||
const tempPath = `${keybindingsConfigPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
|
||||
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
configPath: keybindingsConfigPath,
|
||||
detail: "failed to write keybindings config",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(
|
||||
Effect.map(({ keybindings, issues }) => ({
|
||||
keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),
|
||||
issues,
|
||||
})),
|
||||
);
|
||||
|
||||
const resolvedConfigCache = yield* Cache.make<
|
||||
typeof resolvedConfigCacheKey,
|
||||
KeybindingsConfigState,
|
||||
KeybindingsConfigError
|
||||
>({
|
||||
capacity: 1,
|
||||
lookup: () => loadConfigStateFromDisk,
|
||||
});
|
||||
|
||||
const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
|
||||
const revalidateAndEmit = upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
const configState = yield* loadConfigStateFromCacheOrDisk;
|
||||
yield* emitChange(configState.issues);
|
||||
}),
|
||||
);
|
||||
|
||||
const keybindingsConfigDir = path.dirname(keybindingsConfigPath);
|
||||
const keybindingsConfigFile = path.basename(keybindingsConfigPath);
|
||||
const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);
|
||||
yield* fs
|
||||
.makeDirectory(keybindingsConfigDir, { recursive: true })
|
||||
.pipe(Effect.orElseSucceed(() => undefined));
|
||||
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
|
||||
const isTargetConfigEvent =
|
||||
event.path === keybindingsConfigFile ||
|
||||
event.path === keybindingsConfigPath ||
|
||||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
|
||||
if (!isTargetConfigEvent) {
|
||||
return Effect.void;
|
||||
}
|
||||
return revalidateAndEmit.pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to revalidate keybindings config after file update", {
|
||||
path: keybindingsConfigPath,
|
||||
detail: error.detail,
|
||||
cause: error.cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("keybindings config watcher stopped unexpectedly", {
|
||||
path: keybindingsConfigPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const configExists = yield* readConfigExists;
|
||||
if (!configExists) {
|
||||
yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);
|
||||
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();
|
||||
if (runtimeConfig.issues.length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
"skipping startup keybindings default sync because config has issues",
|
||||
{
|
||||
path: keybindingsConfigPath,
|
||||
issues: runtimeConfig.issues,
|
||||
},
|
||||
);
|
||||
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
return;
|
||||
}
|
||||
const customConfig = runtimeConfig.keybindings;
|
||||
const existingCommands = new Set(customConfig.map((entry) => entry.command));
|
||||
const missingDefaults: KeybindingRule[] = [];
|
||||
const shortcutConflictWarnings: Array<{
|
||||
defaultCommand: KeybindingRule["command"];
|
||||
conflictingCommand: KeybindingRule["command"];
|
||||
key: string;
|
||||
when: string | null;
|
||||
}> = [];
|
||||
for (const defaultRule of DEFAULT_KEYBINDINGS) {
|
||||
if (existingCommands.has(defaultRule.command)) {
|
||||
continue;
|
||||
}
|
||||
const conflictingEntry = customConfig.find((entry) =>
|
||||
hasSameShortcutContext(entry, defaultRule),
|
||||
);
|
||||
if (conflictingEntry) {
|
||||
shortcutConflictWarnings.push({
|
||||
defaultCommand: defaultRule.command,
|
||||
conflictingCommand: conflictingEntry.command,
|
||||
key: defaultRule.key,
|
||||
when: defaultRule.when ?? null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
missingDefaults.push(defaultRule);
|
||||
}
|
||||
for (const conflict of shortcutConflictWarnings) {
|
||||
yield* Effect.logWarning("skipping default keybinding due to shortcut conflict", {
|
||||
path: keybindingsConfigPath,
|
||||
defaultCommand: conflict.defaultCommand,
|
||||
conflictingCommand: conflict.conflictingCommand,
|
||||
key: conflict.key,
|
||||
when: conflict.when,
|
||||
reason: "shortcut context already used by existing rule",
|
||||
});
|
||||
}
|
||||
if (missingDefaults.length === 0) {
|
||||
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) =>
|
||||
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)),
|
||||
).map((rule) => rule.command);
|
||||
if (matchingDefaults.length > 0) {
|
||||
yield* Effect.logWarning("default keybinding rule already defined in user config", {
|
||||
path: keybindingsConfigPath,
|
||||
commands: matchingDefaults,
|
||||
});
|
||||
}
|
||||
|
||||
const nextConfig = [...customConfig, ...missingDefaults];
|
||||
const cappedConfig =
|
||||
nextConfig.length > MAX_KEYBINDINGS_COUNT
|
||||
? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
|
||||
: nextConfig;
|
||||
if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
|
||||
yield* Effect.logWarning("truncating keybindings config to max entries", {
|
||||
path: keybindingsConfigPath,
|
||||
maxEntries: MAX_KEYBINDINGS_COUNT,
|
||||
});
|
||||
}
|
||||
|
||||
yield* writeConfigAtomically(cappedConfig);
|
||||
yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
syncDefaultKeybindingsOnStartup,
|
||||
loadConfigState: loadConfigStateFromCacheOrDisk,
|
||||
changes: Stream.fromPubSub(changesPubSub),
|
||||
upsertKeybindingRule: (rule) =>
|
||||
upsertSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const customConfig = yield* loadWritableCustomKeybindingsConfig();
|
||||
const nextConfig = [
|
||||
...customConfig.filter((entry) => entry.command !== rule.command),
|
||||
rule,
|
||||
];
|
||||
const cappedConfig =
|
||||
nextConfig.length > MAX_KEYBINDINGS_COUNT
|
||||
? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)
|
||||
: nextConfig;
|
||||
if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {
|
||||
yield* Effect.logWarning("truncating keybindings config to max entries", {
|
||||
path: keybindingsConfigPath,
|
||||
maxEntries: MAX_KEYBINDINGS_COUNT,
|
||||
});
|
||||
}
|
||||
yield* writeConfigAtomically(cappedConfig);
|
||||
const nextResolved = mergeWithDefaultKeybindings(
|
||||
compileResolvedKeybindingsConfig(cappedConfig),
|
||||
);
|
||||
yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {
|
||||
keybindings: nextResolved,
|
||||
issues: [],
|
||||
});
|
||||
yield* emitChange([]);
|
||||
return nextResolved;
|
||||
}),
|
||||
),
|
||||
} satisfies KeybindingsShape;
|
||||
});
|
||||
|
||||
export const KeybindingsLive = Layer.effect(Keybindings, makeKeybindings);
|
||||
@@ -1,242 +0,0 @@
|
||||
import * as Http from "node:http";
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { beforeEach } from "vitest";
|
||||
|
||||
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
|
||||
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
|
||||
const start = vi.fn(() => undefined);
|
||||
const stop = vi.fn(() => undefined);
|
||||
let resolvedConfig: ServerConfigShape | null = null;
|
||||
const serverStart = Effect.acquireRelease(
|
||||
Effect.gen(function* () {
|
||||
resolvedConfig = yield* ServerConfig;
|
||||
start();
|
||||
return {} as unknown as Http.Server;
|
||||
}),
|
||||
() => Effect.sync(() => stop()),
|
||||
);
|
||||
const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred));
|
||||
|
||||
// Shared service layer used by this CLI test suite.
|
||||
const testLayer = Layer.mergeAll(
|
||||
Layer.succeed(CliConfig, {
|
||||
cwd: "/tmp/t3-test-workspace",
|
||||
fixPath: Effect.void,
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
findAvailablePort,
|
||||
}),
|
||||
Layer.succeed(Server, {
|
||||
start: serverStart,
|
||||
stopSignal: Effect.void,
|
||||
} satisfies ServerShape),
|
||||
Layer.succeed(Open, {
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
const runCli = (
|
||||
args: ReadonlyArray<string>,
|
||||
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||
) =>
|
||||
Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))),
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resolvedConfig = null;
|
||||
start.mockImplementation(() => undefined);
|
||||
stop.mockImplementation(() => undefined);
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
it.layer(testLayer)("server cli", (it) => {
|
||||
it.effect("parses all CLI flags and wires scoped start/stop", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([
|
||||
"--mode",
|
||||
"desktop",
|
||||
"--port",
|
||||
"4010",
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--state-dir",
|
||||
"/tmp/t3-cli-state",
|
||||
"--dev-url",
|
||||
"http://127.0.0.1:5173",
|
||||
"--no-browser",
|
||||
"--auth-token",
|
||||
"auth-secret",
|
||||
]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4010);
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-state");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "auth-secret");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
assert.equal(stop.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports --token as an alias for --auth-token", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--token", "token-secret"]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.authToken, "token-secret");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses env fallbacks when flags are not provided", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_PORT: "4999",
|
||||
T3CODE_HOST: "100.88.10.4",
|
||||
T3CODE_STATE_DIR: "/tmp/t3-env-state",
|
||||
VITE_DEV_SERVER_URL: "http://localhost:5173",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTH_TOKEN: "env-token",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.port, 4999);
|
||||
assert.equal(resolvedConfig?.host, "100.88.10.4");
|
||||
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-state");
|
||||
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
assert.equal(resolvedConfig?.authToken, "env-token");
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, true);
|
||||
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --mode over T3CODE_MODE", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666));
|
||||
yield* runCli(["--mode", "web"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4666);
|
||||
assert.equal(resolvedConfig?.host, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers --no-browser over T3CODE_NO_BROWSER", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--no-browser"], {
|
||||
T3CODE_NO_BROWSER: "false",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.noBrowser, true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses dynamic port discovery in web mode when port is omitted", () =>
|
||||
Effect.gen(function* () {
|
||||
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444));
|
||||
yield* runCli([]);
|
||||
|
||||
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.port, 5444);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses fixed localhost defaults in desktop mode", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(findAvailablePort.mock.calls.length, 0);
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.port, 3773);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows overriding desktop host with --host", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--host", "0.0.0.0"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "desktop");
|
||||
assert.equal(resolvedConfig?.host, "0.0.0.0");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("supports CLI and env for bootstrap/log websocket toggles", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--auto-bootstrap-project-from-cwd"], {
|
||||
T3CODE_MODE: "desktop",
|
||||
T3CODE_LOG_WS_EVENTS: "false",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
|
||||
assert.equal(resolvedConfig?.logWebSocketEvents, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for invalid --mode values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--mode", "invalid"]);
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for invalid --dev-url values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for out-of-range --port values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--port", "70000"]);
|
||||
|
||||
// effect/unstable/cli renders help/errors for parse failures and returns success.
|
||||
assert.equal(start.mock.calls.length, 0);
|
||||
assert.equal(stop.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,319 +0,0 @@
|
||||
/**
|
||||
* CliConfig - CLI/runtime bootstrap service definitions.
|
||||
*
|
||||
* Defines startup-only service contracts used while resolving process config
|
||||
* and constructing server runtime layers.
|
||||
*
|
||||
* @module CliConfig
|
||||
*/
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
NetService,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { fixPath, resolveStateDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { Server } from "./wsServer";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
interface CliInput {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly stateDir: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfigShape - Startup helpers required while building server layers.
|
||||
*/
|
||||
export interface CliConfigShape {
|
||||
/**
|
||||
* Current process working directory.
|
||||
*/
|
||||
readonly cwd: string;
|
||||
|
||||
/**
|
||||
* Apply OS-specific PATH normalization.
|
||||
*/
|
||||
readonly fixPath: Effect.Effect<void>;
|
||||
|
||||
/**
|
||||
* Resolve static web asset directory for server mode.
|
||||
*/
|
||||
readonly resolveStaticDir: Effect.Effect<string | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfig - Service tag for startup CLI/runtime helpers.
|
||||
*/
|
||||
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()("server/CliConfig") {
|
||||
static readonly layer = Layer.effect(
|
||||
CliConfig,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return {
|
||||
cwd: process.cwd(),
|
||||
fixPath: Effect.sync(fixPath),
|
||||
resolveStaticDir: resolveStaticDir().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
} satisfies CliConfigShape;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const CliEnvConfig = Config.all({
|
||||
mode: Config.string("T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(
|
||||
Option.match<RuntimeMode, string>({
|
||||
onNone: () => "web",
|
||||
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
stateDir: Config.string("T3CODE_STATE_DIR").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const env = yield* CliEnvConfig.asEffect().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new StartupError({ message: "Failed to read environment configuration", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const mode = Option.getOrElse(input.mode, () => env.mode);
|
||||
|
||||
const port = yield* Option.match(input.port, {
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (env.port) {
|
||||
return Effect.succeed(env.port);
|
||||
}
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
});
|
||||
const stateDir = yield* resolveStateDir(
|
||||
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
|
||||
);
|
||||
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||
const noBrowser = Option.match(input.noBrowser, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.noBrowser ?? mode === "desktop")),
|
||||
onNone: () => env.noBrowser ?? mode === "desktop",
|
||||
});
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const autoBootstrapProjectFromCwd = Option.match(input.autoBootstrapProjectFromCwd, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.autoBootstrapProjectFromCwd ?? mode === "web")),
|
||||
onNone: () => env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
});
|
||||
const logWebSocketEvents = Option.match(input.logWebSocketEvents, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/dev fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.logWebSocketEvents ?? Boolean(devUrl))),
|
||||
onNone: () => env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
});
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const { join } = yield* Path.Path;
|
||||
const keybindingsConfigPath = join(stateDir, "keybindings.json");
|
||||
const host =
|
||||
Option.getOrUndefined(input.host) ??
|
||||
env.host ??
|
||||
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
|
||||
return {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
keybindingsConfigPath,
|
||||
host,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
}),
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
yield* cliConfig.fixPath;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
if (!config.devUrl && !config.staticDir) {
|
||||
yield* Effect.logWarning(
|
||||
"web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
|
||||
{
|
||||
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
yield* start;
|
||||
|
||||
const localUrl = `http://localhost:${config.port}`;
|
||||
const bindUrl =
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
url: bindUrl,
|
||||
localUrl,
|
||||
bindHost: config.host ?? "default",
|
||||
cwd: config.cwd,
|
||||
mode: config.mode,
|
||||
stateDir: config.stateDir,
|
||||
authEnabled: Boolean(config.authToken),
|
||||
});
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return yield* stopSignal;
|
||||
}).pipe(Effect.provide(LayerLive(input)));
|
||||
|
||||
/**
|
||||
* These flags mirrors the environment variables and the config shape.
|
||||
*/
|
||||
|
||||
const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const stateDirFlag = Flag.string("state-dir").pipe(
|
||||
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
export const t3Cli = Command.make("t3", {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
stateDir: stateDirFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
|
||||
);
|
||||
@@ -1,73 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { launchDetached, resolveEditorLaunch } from "./open";
|
||||
import { Effect } from "effect";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
|
||||
describe("resolveEditorLaunch", () => {
|
||||
it.effect("returns cursor command for cursor editor", () =>
|
||||
Effect.gen(function* () {
|
||||
const launch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps file-manager editor to OS open commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const launch1 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(launch1, {
|
||||
command: "open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const launch2 = yield* resolveEditorLaunch(
|
||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||
"win32",
|
||||
);
|
||||
assert.deepEqual(launch2, {
|
||||
command: "explorer",
|
||||
args: ["C:\\workspace"],
|
||||
});
|
||||
|
||||
const launch3 = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||
"linux",
|
||||
);
|
||||
assert.deepEqual(launch3, {
|
||||
command: "xdg-open",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("launchDetached", () => {
|
||||
it.effect("resolves when command can be spawned", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: process.execPath,
|
||||
args: ["-e", "process.exit(0)"],
|
||||
}).pipe(Effect.result);
|
||||
assertSuccess(result, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects when command does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* launchDetached({
|
||||
command: `t3code-no-such-command-${Date.now()}`,
|
||||
args: [],
|
||||
}).pipe(Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
/**
|
||||
* Open - Browser/editor launch service interface.
|
||||
*
|
||||
* Owns process launch helpers for opening URLs in a browser and workspace
|
||||
* paths in a configured editor.
|
||||
*
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
readonly editor: EditorId;
|
||||
}
|
||||
|
||||
interface EditorLaunch {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenShape - Service API for browser and editor launch actions.
|
||||
*/
|
||||
export interface OpenShape {
|
||||
/**
|
||||
* Open a URL target in the default browser.
|
||||
*/
|
||||
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
|
||||
|
||||
/**
|
||||
* Open a workspace path in a selected editor integration.
|
||||
*
|
||||
* Launches the editor as a detached process so server startup is not blocked.
|
||||
*/
|
||||
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class Open extends ServiceMap.Service<Open, OpenShape>()("server/Open") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
// ==============================
|
||||
|
||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
input: OpenInEditorInput,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||
if (!editorDef) {
|
||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
if (editorDef.command) {
|
||||
return { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return { command: "open", args: [input.cwd] };
|
||||
case "win32":
|
||||
return { command: "explorer", args: [input.cwd] };
|
||||
default:
|
||||
return { command: "xdg-open", args: [input.cwd] };
|
||||
}
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.promise(() => import("open"));
|
||||
|
||||
return {
|
||||
openBrowser: (target) =>
|
||||
Effect.tryPromise({
|
||||
try: () => open.default(target),
|
||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||
}),
|
||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||
} satisfies OpenShape;
|
||||
});
|
||||
|
||||
export const OpenLive = Layer.effect(Open, make);
|
||||
@@ -1,123 +0,0 @@
|
||||
import { SchemaIssue, Schema } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
|
||||
export class OrchestrationCommandJsonParseError extends Schema.TaggedErrorClass<OrchestrationCommandJsonParseError>()(
|
||||
"OrchestrationCommandJsonParseError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Invalid orchestration command JSON: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OrchestrationCommandDecodeError extends Schema.TaggedErrorClass<OrchestrationCommandDecodeError>()(
|
||||
"OrchestrationCommandDecodeError",
|
||||
{
|
||||
issue: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Invalid orchestration command payload: ${this.issue}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OrchestrationCommandInvariantError extends Schema.TaggedErrorClass<OrchestrationCommandInvariantError>()(
|
||||
"OrchestrationCommandInvariantError",
|
||||
{
|
||||
commandType: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Orchestration command invariant failed (${this.commandType}): ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OrchestrationCommandPreviouslyRejectedError extends Schema.TaggedErrorClass<OrchestrationCommandPreviouslyRejectedError>()(
|
||||
"OrchestrationCommandPreviouslyRejectedError",
|
||||
{
|
||||
commandId: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Command previously rejected (${this.commandId}): ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OrchestrationProjectorDecodeError extends Schema.TaggedErrorClass<OrchestrationProjectorDecodeError>()(
|
||||
"OrchestrationProjectorDecodeError",
|
||||
{
|
||||
eventType: Schema.String,
|
||||
issue: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Projector decode failed for ${this.eventType}: ${this.issue}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OrchestrationListenerCallbackError extends Schema.TaggedErrorClass<OrchestrationListenerCallbackError>()(
|
||||
"OrchestrationListenerCallbackError",
|
||||
{
|
||||
listener: Schema.Literals(["read-model", "domain-event"]),
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Orchestration ${this.listener} listener failed: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export type OrchestrationDispatchError =
|
||||
| ProjectionRepositoryError
|
||||
| OrchestrationCommandInvariantError
|
||||
| OrchestrationCommandPreviouslyRejectedError
|
||||
| OrchestrationProjectorDecodeError
|
||||
| OrchestrationListenerCallbackError;
|
||||
|
||||
export type OrchestrationEngineError =
|
||||
| OrchestrationDispatchError
|
||||
| OrchestrationCommandJsonParseError
|
||||
| OrchestrationCommandDecodeError;
|
||||
|
||||
export function toOrchestrationCommandDecodeError(error: Schema.SchemaError) {
|
||||
return new OrchestrationCommandDecodeError({
|
||||
issue: SchemaIssue.makeFormatterDefault()(error.issue),
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
export function toProjectorDecodeError(eventType: string) {
|
||||
return (error: Schema.SchemaError): OrchestrationProjectorDecodeError =>
|
||||
new OrchestrationProjectorDecodeError({
|
||||
eventType,
|
||||
issue: SchemaIssue.makeFormatterDefault()(error.issue),
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
export function toOrchestrationJsonParseError(cause: unknown) {
|
||||
return new OrchestrationCommandJsonParseError({
|
||||
detail: `Failed to parse orchestration command JSON`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
export function toListenerCallbackError(listener: "read-model" | "domain-event") {
|
||||
return (cause: unknown): OrchestrationListenerCallbackError =>
|
||||
new OrchestrationListenerCallbackError({
|
||||
listener,
|
||||
detail: `Failed to invoke orchestration ${listener} listener`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
@@ -1,819 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
||||
const now = new Date().toISOString();
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const rollbackConversation = vi.fn(
|
||||
(_input: { readonly sessionId: ProviderSessionId; readonly numTurns: number }) => Effect.void,
|
||||
);
|
||||
|
||||
const unsupported = <A>() =>
|
||||
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
|
||||
const listSessions = () =>
|
||||
hasSession
|
||||
? Effect.succeed([
|
||||
{
|
||||
sessionId: asSessionId("sess-1"),
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
cwd: sessionCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderSession>)
|
||||
: Effect.succeed([] as ReadonlyArray<ProviderSession>);
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions,
|
||||
rollbackConversation,
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
|
||||
};
|
||||
|
||||
return {
|
||||
service,
|
||||
rollbackConversation,
|
||||
emit,
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForThread(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: {
|
||||
latestTurnId: string | null;
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}) => boolean,
|
||||
timeoutMs = 2000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<{
|
||||
latestTurnId: string | null;
|
||||
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for thread state.");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return poll();
|
||||
};
|
||||
return poll();
|
||||
}
|
||||
|
||||
async function waitForEvent(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (event: { type: string }) => boolean,
|
||||
timeoutMs = 2000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async () => {
|
||||
const events = await Effect.runPromise(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(Effect.map((chunk) => Array.from(chunk))),
|
||||
);
|
||||
if (events.some(predicate)) {
|
||||
return events;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for orchestration event.");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return poll();
|
||||
};
|
||||
return poll();
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
function createGitRepository() {
|
||||
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "t3-checkpoint-handler-"));
|
||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
|
||||
runGit(cwd, ["add", "."]);
|
||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
function gitRefExists(cwd: string, ref: string): boolean {
|
||||
try {
|
||||
runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
|
||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||
}
|
||||
|
||||
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 2000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (gitRefExists(cwd, ref)) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error(`Timed out waiting for git ref '${ref}'.`);
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return poll();
|
||||
};
|
||||
return poll();
|
||||
}
|
||||
|
||||
describe("CheckpointReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | CheckpointReactor | CheckpointStore,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
scope = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop();
|
||||
if (dir) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function createHarness(options?: {
|
||||
readonly hasSession?: boolean;
|
||||
readonly seedFilesystemCheckpoints?: boolean;
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
const provider = createProviderServiceHarness(
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
|
||||
const layer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(checkpointStoreLayer),
|
||||
);
|
||||
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const reactor = await runtime.runPromise(Effect.service(CheckpointReactor));
|
||||
const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(Effect.sleep("10 millis"));
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: options?.threadWorktreePath ?? cwd,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
if (options?.seedFilesystemCheckpoints ?? true) {
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
engine,
|
||||
provider,
|
||||
cwd,
|
||||
};
|
||||
}
|
||||
|
||||
it("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) => entry.latestTurnId === "turn-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v1\n");
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
|
||||
const harness = await createHarness({ seedFilesystemCheckpoints: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-missing-baseline"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 &&
|
||||
entry.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
|
||||
);
|
||||
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
thread.activities.some((activity) => activity.kind === "checkpoint.capture.failed"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
seedFilesystemCheckpoints: false,
|
||||
threadWorktreePath: null,
|
||||
});
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.makeUnsafe("message-user-1"),
|
||||
role: "user",
|
||||
text: "start turn",
|
||||
attachments: [],
|
||||
},
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v1\n");
|
||||
});
|
||||
|
||||
it("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
seedFilesystemCheckpoints: false,
|
||||
threadWorktreePath: null,
|
||||
});
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-missing"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
activeTurnId: asTurnId("turn-missing-cwd"),
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-missing"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
turnId: asTurnId("turn-missing-cwd"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("maps runtime checkpoint.captured into thread.turn.diff.complete when missing in read model", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-3"),
|
||||
turnCount: 3,
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3),
|
||||
);
|
||||
expect(thread.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("continues processing runtime events after a single checkpoint runtime failure", async () => {
|
||||
const nonRepositorySessionCwd = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "t3-checkpoint-runtime-non-repo-"),
|
||||
);
|
||||
tempDirs.push(nonRepositorySessionCwd);
|
||||
|
||||
const harness = await createHarness({
|
||||
seedFilesystemCheckpoints: false,
|
||||
providerSessionCwd: nonRepositorySessionCwd,
|
||||
});
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-runtime-failure"),
|
||||
turnCount: 1,
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-after-runtime-failure"),
|
||||
});
|
||||
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
const thread = await waitForThread(harness.engine, (entry) => entry.checkpoints.length === 1);
|
||||
|
||||
expect(thread.latestTurnId).toBe("turn-1");
|
||||
expect(thread.checkpoints).toHaveLength(1);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 0,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const deadline = Date.now() + 2000;
|
||||
const waitForRollbackCalls = async (): Promise<void> => {
|
||||
if (harness.provider.rollbackConversation.mock.calls.length >= 2) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for rollbackConversation calls.");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return waitForRollbackCalls();
|
||||
};
|
||||
await waitForRollbackCalls();
|
||||
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("appends an error activity when revert is requested without an active session", async () => {
|
||||
const harness = await createHarness({ hasSession: false });
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-no-session"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "checkpoint.revert.failed"),
|
||||
);
|
||||
|
||||
expect(thread.activities.some((activity) => activity.kind === "checkpoint.revert.failed")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(harness.provider.rollbackConversation).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,710 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
|
||||
import {
|
||||
checkpointRefForThreadTurn,
|
||||
resolveThreadWorkspaceCwd,
|
||||
} from "../../checkpointing/Utils.ts";
|
||||
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
readonly source: "runtime";
|
||||
readonly event: ProviderRuntimeEvent;
|
||||
}
|
||||
| {
|
||||
readonly source: "domain";
|
||||
readonly event: OrchestrationEvent;
|
||||
};
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | null {
|
||||
return value === undefined ? null : TurnId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
|
||||
switch (status) {
|
||||
case "failed":
|
||||
return "error";
|
||||
case "cancelled":
|
||||
case "interrupted":
|
||||
return "missing";
|
||||
case "completed":
|
||||
default:
|
||||
return "ready";
|
||||
}
|
||||
}
|
||||
|
||||
const serverCommandId = (tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
|
||||
const appendRevertFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnCount: number;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-revert-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.revert.failed",
|
||||
summary: "Checkpoint revert failed",
|
||||
payload: {
|
||||
turnCount: input.turnCount,
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const appendCaptureFailureActivity = (input: {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === input.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }>
|
||||
> {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const projectedSessionId = thread?.session?.providerSessionId ?? null;
|
||||
const projectedProviderThreadId = thread?.session?.providerThreadId ?? undefined;
|
||||
|
||||
const sessions = yield* providerService.listSessions();
|
||||
|
||||
const findSessionWithCwd = (
|
||||
session: (typeof sessions)[number] | undefined,
|
||||
): Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }> => {
|
||||
if (!session?.cwd) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
};
|
||||
|
||||
if (projectedSessionId !== null) {
|
||||
const projectedSession = sessions.find((session) => session.sessionId === projectedSessionId);
|
||||
const fromProjected = findSessionWithCwd(projectedSession);
|
||||
if (Option.isSome(fromProjected)) {
|
||||
return fromProjected;
|
||||
}
|
||||
}
|
||||
|
||||
if (projectedProviderThreadId) {
|
||||
const matchedSession = sessions.find(
|
||||
(session) => session.threadId === projectedProviderThreadId,
|
||||
);
|
||||
const fromProviderThread = findSessionWithCwd(matchedSession);
|
||||
if (Option.isSome(fromProviderThread)) {
|
||||
return fromProviderThread;
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
|
||||
) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (thread.checkpoints.some((checkpoint) => checkpoint.turnId === turnId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
|
||||
const checkpointCwd =
|
||||
Option.match(sessionRuntime, {
|
||||
onNone: () => undefined,
|
||||
onSome: (runtime) => runtime.cwd,
|
||||
}) ??
|
||||
resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
yield* Effect.logWarning("checkpoint capture skipped: no active provider session cwd", {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
const nextTurnCount = currentTurnCount + 1;
|
||||
const fromTurnCount = Math.max(0, nextTurnCount - 1);
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
|
||||
const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, nextTurnCount);
|
||||
|
||||
const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
});
|
||||
if (!fromCheckpointExists) {
|
||||
yield* Effect.logWarning("checkpoint completion missing pre-turn baseline", {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
fromTurnCount,
|
||||
});
|
||||
}
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: checkpointCwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
|
||||
path: file.path,
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
})),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
sessionId: event.sessionId,
|
||||
turnId,
|
||||
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
|
||||
createdAt: event.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("failed to derive checkpoint file summary", {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
turnCount: nextTurnCount,
|
||||
detail: error.message,
|
||||
}).pipe(Effect.as([])),
|
||||
),
|
||||
);
|
||||
|
||||
const assistantMessageId =
|
||||
thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
|
||||
MessageId.makeUnsafe(`assistant:${turnId}`);
|
||||
|
||||
const now = event.createdAt;
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: serverCommandId("checkpoint-turn-diff-complete"),
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: now,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: nextTurnCount,
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-captured-activity"),
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "info",
|
||||
kind: "checkpoint.captured",
|
||||
summary: "Checkpoint captured",
|
||||
payload: {
|
||||
turnCount: nextTurnCount,
|
||||
...(event.status !== undefined ? { status: event.status } : {}),
|
||||
},
|
||||
turnId,
|
||||
createdAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
|
||||
) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
const checkpointCwd =
|
||||
checkpointCwdFromThreadOrProject ??
|
||||
Option.match(yield* resolveSessionRuntimeForThread(thread.id), {
|
||||
onNone: () => undefined,
|
||||
onSome: (runtime) => runtime.cwd,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
|
||||
const baselineExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
if (baselineExists) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
|
||||
event: Extract<
|
||||
OrchestrationEvent,
|
||||
{ type: "thread.turn-start-requested" | "thread.message-sent" }
|
||||
>,
|
||||
) {
|
||||
if (event.type === "thread.message-sent") {
|
||||
if (
|
||||
event.payload.role !== "user" ||
|
||||
event.payload.streaming ||
|
||||
event.payload.turnId !== null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const threadId = event.payload.threadId;
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointCwdFromThreadOrProject = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
const checkpointCwd =
|
||||
checkpointCwdFromThreadOrProject ??
|
||||
Option.match(yield* resolveSessionRuntimeForThread(threadId), {
|
||||
onNone: () => undefined,
|
||||
onSome: (runtime) => runtime.cwd,
|
||||
});
|
||||
if (!checkpointCwd) {
|
||||
yield* Effect.logWarning("checkpoint pre-turn capture skipped: no workspace cwd", {
|
||||
threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount);
|
||||
const baselineExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
if (baselineExists) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
checkpointRef: baselineCheckpointRef,
|
||||
});
|
||||
});
|
||||
|
||||
const handleRevertRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
|
||||
if (!thread) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "Thread was not found in read model.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(event.payload.threadId);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: "No active provider session with workspace cwd is bound to this thread.",
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTurnCount = thread.checkpoints.reduce(
|
||||
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
|
||||
0,
|
||||
);
|
||||
|
||||
if (event.payload.turnCount > currentTurnCount) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`,
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const targetCheckpointRef =
|
||||
event.payload.turnCount === 0
|
||||
? checkpointRefForThreadTurn(event.payload.threadId, 0)
|
||||
: thread.checkpoints.find(
|
||||
(checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount,
|
||||
)?.checkpointRef;
|
||||
|
||||
if (!targetCheckpointRef) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`,
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const restored = yield* checkpointStore.restoreCheckpoint({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
fallbackToHead: event.payload.turnCount === 0,
|
||||
});
|
||||
if (!restored) {
|
||||
yield* appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`,
|
||||
createdAt: now,
|
||||
}).pipe(Effect.catch(() => Effect.void));
|
||||
return;
|
||||
}
|
||||
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||
if (rolledBackTurns > 0) {
|
||||
yield* providerService.rollbackConversation({
|
||||
sessionId: sessionRuntime.value.sessionId,
|
||||
numTurns: rolledBackTurns,
|
||||
});
|
||||
}
|
||||
|
||||
const staleCheckpointRefs = thread.checkpoints
|
||||
.filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount)
|
||||
.map((checkpoint) => checkpoint.checkpointRef);
|
||||
|
||||
if (staleCheckpointRefs.length > 0) {
|
||||
yield* checkpointStore.deleteCheckpointRefs({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRefs: staleCheckpointRefs,
|
||||
});
|
||||
}
|
||||
|
||||
yield* orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.revert.complete",
|
||||
commandId: serverCommandId("checkpoint-revert-complete"),
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
createdAt: now,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: error.message,
|
||||
createdAt: now,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
|
||||
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
|
||||
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
|
||||
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "thread.checkpoint-revert-requested") {
|
||||
yield* handleRevertRequested(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
appendRevertFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
detail: error.message,
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
|
||||
if (event.type === "turn.started") {
|
||||
yield* ensurePreTurnBaselineFromTurnStart(event);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
yield* captureCheckpointFromTurnCompletion(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
sessionId: event.sessionId,
|
||||
turnId,
|
||||
detail: error.message,
|
||||
createdAt: new Date().toISOString(),
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "checkpoint.captured") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
thread.checkpoints.some(
|
||||
(checkpoint) =>
|
||||
checkpoint.turnId === turnId || checkpoint.checkpointTurnCount === event.turnCount,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fromTurnCount = Math.max(0, event.turnCount - 1);
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
|
||||
const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, event.turnCount);
|
||||
|
||||
const targetExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
if (!targetExists) {
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
}
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
|
||||
path: file.path,
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed([])),
|
||||
);
|
||||
|
||||
const assistantMessageId =
|
||||
thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
|
||||
MessageId.makeUnsafe(`assistant:${turnId}`);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: serverCommandId("checkpoint-runtime-captured-diff-complete"),
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: event.createdAt,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: event.turnCount,
|
||||
createdAt: event.createdAt,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const processInput = (
|
||||
input: ReactorInput,
|
||||
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
|
||||
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
|
||||
|
||||
const processInputSafely = (input: ReactorInput) =>
|
||||
processInput(input).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("checkpoint reactor failed to process input", {
|
||||
source: input.source,
|
||||
eventType: input.event.type,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
|
||||
const queue = yield* Queue.unbounded<ReactorInput>();
|
||||
yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processInputSafely))),
|
||||
);
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
event.type !== "thread.turn-start-requested" &&
|
||||
event.type !== "thread.message-sent" &&
|
||||
event.type !== "thread.checkpoint-revert-requested"
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Queue.offer(queue, { source: "domain", event }).pipe(Effect.asVoid);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(providerService.streamEvents, (event) => {
|
||||
if (
|
||||
event.type !== "turn.started" &&
|
||||
event.type !== "turn.completed" &&
|
||||
event.type !== "checkpoint.captured"
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
return Queue.offer(queue, { source: "runtime", event }).pipe(Effect.asVoid);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
} satisfies CheckpointReactorShape;
|
||||
});
|
||||
|
||||
export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make);
|
||||
@@ -1,644 +0,0 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PersistenceSqlError } from "../../persistence/Errors.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
OrchestrationEventStore,
|
||||
type OrchestrationEventStoreShape,
|
||||
} from "../../persistence/Services/OrchestrationEventStore.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
OrchestrationProjectionPipeline,
|
||||
type OrchestrationProjectionPipelineShape,
|
||||
} from "../Services/ProjectionPipeline.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
|
||||
async function createOrchestrationSystem() {
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
return {
|
||||
engine,
|
||||
run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
|
||||
dispose: () => runtime.dispose(),
|
||||
};
|
||||
}
|
||||
|
||||
function now() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
describe("OrchestrationEngine", () => {
|
||||
it("returns deterministic read models for repeated reads", async () => {
|
||||
const createdAt = now();
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-1-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-1-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-1"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const readModelA = await system.run(engine.getReadModel());
|
||||
const readModelB = await system.run(engine.getReadModel());
|
||||
expect(readModelB).toEqual(readModelA);
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("replays append-only events from sequence", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
const createdAt = now();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-replay-create"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "Replay Project",
|
||||
workspaceRoot: "/tmp/project-replay",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
}),
|
||||
);
|
||||
|
||||
const events = await system.run(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
"thread.deleted",
|
||||
]);
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("streams persisted domain events in order", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
const createdAt = now();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-stream-create"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "Stream Project",
|
||||
workspaceRoot: "/tmp/project-stream",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const eventTypes: string[] = [];
|
||||
await system.run(
|
||||
Effect.gen(function* () {
|
||||
const eventQueue = yield* Queue.unbounded<OrchestrationEvent>();
|
||||
yield* Effect.forkScoped(
|
||||
Stream.take(engine.streamDomainEvents, 2).pipe(
|
||||
Stream.runForEach((event) => Queue.offer(eventQueue, event).pipe(Effect.asVoid)),
|
||||
),
|
||||
);
|
||||
yield* Effect.sleep("10 millis");
|
||||
yield* engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
});
|
||||
yield* engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
title: "domain-stream-updated",
|
||||
});
|
||||
eventTypes.push((yield* Queue.take(eventQueue)).type);
|
||||
eventTypes.push((yield* Queue.take(eventQueue)).type);
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
expect(eventTypes).toEqual(["thread.created", "thread.meta-updated"]);
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("stores completed checkpoint summaries even when no files changed", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
const createdAt = now();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn Diff Project",
|
||||
workspaceRoot: "/tmp/project-turn-diff",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const thread = (await system.run(engine.getReadModel())).threads.find(
|
||||
(entry) => entry.id === "thread-turn-diff",
|
||||
);
|
||||
expect(thread?.checkpoints).toEqual([
|
||||
{
|
||||
turnId: asTurnId("turn-1"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: null,
|
||||
completedAt: createdAt,
|
||||
},
|
||||
]);
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("keeps processing queued commands after a storage failure", async () => {
|
||||
type StoredEvent =
|
||||
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
|
||||
? A
|
||||
: never;
|
||||
const events: StoredEvent[] = [];
|
||||
let nextSequence = 1;
|
||||
let shouldFailFirstAppend = true;
|
||||
|
||||
const flakyStore: OrchestrationEventStoreShape = {
|
||||
append(event) {
|
||||
if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {
|
||||
shouldFailFirstAppend = false;
|
||||
return Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "test.append",
|
||||
detail: "append failed",
|
||||
}),
|
||||
);
|
||||
}
|
||||
const savedEvent = {
|
||||
...event,
|
||||
sequence: nextSequence,
|
||||
} as StoredEvent;
|
||||
nextSequence += 1;
|
||||
events.push(savedEvent);
|
||||
return Effect.succeed(savedEvent);
|
||||
},
|
||||
readFromSequence(sequenceExclusive) {
|
||||
return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
|
||||
},
|
||||
readAll() {
|
||||
return Stream.fromIterable(events);
|
||||
},
|
||||
};
|
||||
|
||||
const runtime = ManagedRuntime.make(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
),
|
||||
);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const createdAt = now();
|
||||
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "Flaky Project",
|
||||
workspaceRoot: "/tmp/project-flaky",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-flaky-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("append failed");
|
||||
|
||||
const result = await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-flaky-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.sequence).toBe(2);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
it("rolls back all events for a multi-event command when projection fails mid-dispatch", async () => {
|
||||
let shouldFailRequestedProjection = true;
|
||||
const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
|
||||
bootstrap: Effect.void,
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailRequestedProjection &&
|
||||
event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&
|
||||
event.type === "thread.turn-start-requested"
|
||||
) {
|
||||
shouldFailRequestedProjection = false;
|
||||
return Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "test.projection",
|
||||
detail: "projection failed",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
},
|
||||
};
|
||||
|
||||
const runtime = ManagedRuntime.make(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
),
|
||||
);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const createdAt = now();
|
||||
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "Atomic Project",
|
||||
workspaceRoot: "/tmp/project-atomic",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const turnStartCommand = {
|
||||
type: "thread.turn.start" as const,
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-atomic-1"),
|
||||
role: "user" as const,
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
createdAt,
|
||||
};
|
||||
|
||||
await expect(runtime.runPromise(engine.dispatch(turnStartCommand))).rejects.toThrow(
|
||||
"projection failed",
|
||||
);
|
||||
|
||||
const eventsAfterFailure = await runtime.runPromise(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(eventsAfterFailure.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
]);
|
||||
expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
|
||||
|
||||
const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
|
||||
expect(retryResult.sequence).toBe(4);
|
||||
|
||||
const eventsAfterRetry = await runtime.runPromise(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(eventsAfterRetry.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
"thread.message-sent",
|
||||
"thread.turn-start-requested",
|
||||
]);
|
||||
expect(
|
||||
eventsAfterRetry.filter((event) => event.commandId === turnStartCommand.commandId),
|
||||
).toHaveLength(2);
|
||||
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
it("reconciles in-memory state when append persists but projection fails", async () => {
|
||||
type StoredEvent =
|
||||
ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
|
||||
? A
|
||||
: never;
|
||||
const events: StoredEvent[] = [];
|
||||
let nextSequence = 1;
|
||||
|
||||
const nonTransactionalStore: OrchestrationEventStoreShape = {
|
||||
append(event) {
|
||||
const savedEvent = {
|
||||
...event,
|
||||
sequence: nextSequence,
|
||||
} as StoredEvent;
|
||||
nextSequence += 1;
|
||||
events.push(savedEvent);
|
||||
return Effect.succeed(savedEvent);
|
||||
},
|
||||
readFromSequence(sequenceExclusive) {
|
||||
return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
|
||||
},
|
||||
readAll() {
|
||||
return Stream.fromIterable(events);
|
||||
},
|
||||
};
|
||||
|
||||
let shouldFailProjection = true;
|
||||
const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
|
||||
bootstrap: Effect.void,
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailProjection &&
|
||||
event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail")
|
||||
) {
|
||||
shouldFailProjection = false;
|
||||
return Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
operation: "test.projection",
|
||||
detail: "projection failed",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
},
|
||||
};
|
||||
|
||||
const runtime = ManagedRuntime.make(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
),
|
||||
);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const createdAt = now();
|
||||
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-sync-create"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "Sync Project",
|
||||
workspaceRoot: "/tmp/project-sync",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-sync-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"),
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
title: "sync-after-failed-projection",
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("projection failed");
|
||||
|
||||
const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
|
||||
const updatedThread = readModelAfterFailure.threads.find((thread) => thread.id === "thread-sync");
|
||||
expect(readModelAfterFailure.snapshotSequence).toBe(3);
|
||||
expect(updatedThread?.title).toBe("sync-after-failed-projection");
|
||||
|
||||
await runtime.dispose();
|
||||
});
|
||||
|
||||
it("fails command dispatch when command invariants are violated", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
await expect(
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),
|
||||
threadId: ThreadId.makeUnsafe("thread-missing"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-missing"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
createdAt: now(),
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("Thread 'thread-missing' does not exist");
|
||||
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("rejects duplicate thread creation", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
const createdAt = now();
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project-duplicate",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("already exists");
|
||||
|
||||
await system.dispose();
|
||||
});
|
||||
});
|
||||
@@ -1,246 +0,0 @@
|
||||
import type {
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { OrchestrationCommand } from "@t3tools/contracts";
|
||||
import { Deferred, Effect, Layer, Option, PubSub, Queue, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { toPersistenceSqlError } from "../../persistence/Errors.ts";
|
||||
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
|
||||
import {
|
||||
OrchestrationCommandInvariantError,
|
||||
OrchestrationCommandPreviouslyRejectedError,
|
||||
type OrchestrationDispatchError,
|
||||
} from "../Errors.ts";
|
||||
import { decideOrchestrationCommand } from "../decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "../projector.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
|
||||
interface CommandEnvelope {
|
||||
command: OrchestrationCommand;
|
||||
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
|
||||
}
|
||||
|
||||
function commandToAggregateRef(command: OrchestrationCommand): {
|
||||
readonly aggregateKind: "project" | "thread";
|
||||
readonly aggregateId: ProjectId | ThreadId;
|
||||
} {
|
||||
switch (command.type) {
|
||||
case "project.create":
|
||||
case "project.meta.update":
|
||||
case "project.delete":
|
||||
return {
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
};
|
||||
default:
|
||||
return {
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function formatDispatchError(error: OrchestrationDispatchError): string {
|
||||
if (error instanceof Error && error.message.length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
const makeOrchestrationEngine = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
let readModel = createEmptyReadModel(new Date().toISOString());
|
||||
|
||||
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
|
||||
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
|
||||
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
|
||||
const dispatchStartSequence = readModel.snapshotSequence;
|
||||
const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
|
||||
const persistedEvents = yield* Stream.runCollect(
|
||||
eventStore.readFromSequence(dispatchStartSequence),
|
||||
).pipe(Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)));
|
||||
if (persistedEvents.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let nextReadModel = readModel;
|
||||
for (const persistedEvent of persistedEvents) {
|
||||
nextReadModel = yield* projectEvent(nextReadModel, persistedEvent);
|
||||
}
|
||||
readModel = nextReadModel;
|
||||
|
||||
for (const persistedEvent of persistedEvents) {
|
||||
yield* PubSub.publish(eventPubSub, persistedEvent);
|
||||
}
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
|
||||
commandId: envelope.command.commandId,
|
||||
});
|
||||
if (Option.isSome(existingReceipt)) {
|
||||
if (existingReceipt.value.status === "accepted") {
|
||||
yield* Deferred.succeed(envelope.result, {
|
||||
sequence: existingReceipt.value.resultSequence,
|
||||
});
|
||||
return;
|
||||
}
|
||||
yield* Deferred.fail(
|
||||
envelope.result,
|
||||
new OrchestrationCommandPreviouslyRejectedError({
|
||||
commandId: envelope.command.commandId,
|
||||
detail: existingReceipt.value.error ?? "Previously rejected.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const eventBase = yield* decideOrchestrationCommand({
|
||||
command: envelope.command,
|
||||
readModel,
|
||||
});
|
||||
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
|
||||
const committedCommand = yield* sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const committedEvents: OrchestrationEvent[] = [];
|
||||
let nextReadModel = readModel;
|
||||
|
||||
for (const nextEvent of eventBases) {
|
||||
const savedEvent = yield* eventStore.append(nextEvent);
|
||||
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
|
||||
yield* projectionPipeline.projectEvent(savedEvent);
|
||||
committedEvents.push(savedEvent);
|
||||
}
|
||||
|
||||
const lastSavedEvent = committedEvents.at(-1) ?? null;
|
||||
if (lastSavedEvent === null) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: envelope.command.type,
|
||||
detail: "Command produced no events.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* commandReceiptRepository.upsert({
|
||||
commandId: envelope.command.commandId,
|
||||
aggregateKind: lastSavedEvent.aggregateKind,
|
||||
aggregateId: lastSavedEvent.aggregateId,
|
||||
acceptedAt: lastSavedEvent.occurredAt,
|
||||
resultSequence: lastSavedEvent.sequence,
|
||||
status: "accepted",
|
||||
error: null,
|
||||
});
|
||||
|
||||
return {
|
||||
committedEvents,
|
||||
lastSequence: lastSavedEvent.sequence,
|
||||
nextReadModel,
|
||||
} as const;
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(
|
||||
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
readModel = committedCommand.nextReadModel;
|
||||
for (const event of committedCommand.committedEvents) {
|
||||
yield* PubSub.publish(eventPubSub, event);
|
||||
}
|
||||
yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });
|
||||
}).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.gen(function* () {
|
||||
yield* reconcileReadModelAfterDispatchFailure.pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logWarning(
|
||||
"failed to reconcile orchestration read model after dispatch failure",
|
||||
).pipe(
|
||||
Effect.annotateLogs({
|
||||
commandId: envelope.command.commandId,
|
||||
snapshotSequence: readModel.snapshotSequence,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (error instanceof OrchestrationCommandInvariantError) {
|
||||
const aggregateRef = commandToAggregateRef(envelope.command);
|
||||
yield* commandReceiptRepository
|
||||
.upsert({
|
||||
commandId: envelope.command.commandId,
|
||||
aggregateKind: aggregateRef.aggregateKind,
|
||||
aggregateId: aggregateRef.aggregateId,
|
||||
acceptedAt: new Date().toISOString(),
|
||||
resultSequence: readModel.snapshotSequence,
|
||||
status: "rejected",
|
||||
error: formatDispatchError(error),
|
||||
})
|
||||
.pipe(Effect.catch(() => Effect.void));
|
||||
}
|
||||
yield* Deferred.fail(envelope.result, error);
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
// bootstrap in-memory read model from event store
|
||||
yield* Stream.runForEach(eventStore.readAll(), (event) =>
|
||||
Effect.gen(function* () {
|
||||
readModel = yield* projectEvent(readModel, event);
|
||||
}),
|
||||
);
|
||||
|
||||
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
|
||||
yield* Effect.forkScoped(worker);
|
||||
yield* Effect.log("orchestration engine started").pipe(
|
||||
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
|
||||
);
|
||||
|
||||
const getReadModel: OrchestrationEngineShape["getReadModel"] = () =>
|
||||
Effect.sync((): OrchestrationReadModel => readModel);
|
||||
|
||||
const readEvents: OrchestrationEngineShape["readEvents"] = (fromSequenceExclusive) =>
|
||||
eventStore.readFromSequence(fromSequenceExclusive);
|
||||
|
||||
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
|
||||
yield* Queue.offer(commandQueue, { command, result });
|
||||
return yield* Deferred.await(result);
|
||||
});
|
||||
|
||||
const streamDomainEvents: OrchestrationEngineShape["streamDomainEvents"] =
|
||||
Stream.fromPubSub(eventPubSub);
|
||||
|
||||
return {
|
||||
getReadModel,
|
||||
readEvents,
|
||||
dispatch,
|
||||
streamDomainEvents,
|
||||
} satisfies OrchestrationEngineShape;
|
||||
});
|
||||
|
||||
export const OrchestrationEngineLive = Layer.effect(
|
||||
OrchestrationEngineService,
|
||||
makeOrchestrationEngine,
|
||||
);
|
||||
@@ -1,61 +0,0 @@
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
|
||||
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
|
||||
|
||||
describe("OrchestrationReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<OrchestrationReactor, never> | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
it("starts provider ingestion, provider command, and checkpoint reactors", async () => {
|
||||
const started: string[] = [];
|
||||
|
||||
runtime = ManagedRuntime.make(
|
||||
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderRuntimeIngestionService, {
|
||||
start: Effect.sync(() => {
|
||||
started.push("provider-runtime-ingestion");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProviderCommandReactor, {
|
||||
start: Effect.sync(() => {
|
||||
started.push("provider-command-reactor");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(CheckpointReactor, {
|
||||
start: Effect.sync(() => {
|
||||
started.push("checkpoint-reactor");
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
|
||||
|
||||
expect(started).toEqual([
|
||||
"provider-runtime-ingestion",
|
||||
"provider-command-reactor",
|
||||
"checkpoint-reactor",
|
||||
]);
|
||||
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
});
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import {
|
||||
OrchestrationReactor,
|
||||
type OrchestrationReactorShape,
|
||||
} from "../Services/OrchestrationReactor.ts";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
|
||||
export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
|
||||
const providerCommandReactor = yield* ProviderCommandReactor;
|
||||
const checkpointReactor = yield* CheckpointReactor;
|
||||
|
||||
const start: OrchestrationReactorShape["start"] = Effect.gen(function* () {
|
||||
yield* providerRuntimeIngestion.start;
|
||||
yield* providerCommandReactor.start;
|
||||
yield* checkpointReactor.start;
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
} satisfies OrchestrationReactorShape;
|
||||
});
|
||||
|
||||
export const OrchestrationReactorLive = Layer.effect(
|
||||
OrchestrationReactor,
|
||||
makeOrchestrationReactor,
|
||||
);
|
||||
@@ -1,969 +0,0 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
CorrelationId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { NodeServices } from "@effect/platform-node";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import {
|
||||
makeSqlitePersistenceLive,
|
||||
SqlitePersistenceMemory,
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import {
|
||||
ORCHESTRATION_PROJECTOR_NAMES,
|
||||
OrchestrationProjectionPipelineLive,
|
||||
} from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
|
||||
|
||||
const projectionLayer = it.layer(
|
||||
OrchestrationProjectionPipelineLive.pipe(
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
),
|
||||
);
|
||||
|
||||
projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
it.effect("bootstraps all projection states and writes projection rows", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe("evt-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.makeUnsafe("project-1"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe("evt-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: MessageId.makeUnsafe("message-1"),
|
||||
role: "assistant",
|
||||
text: "hello",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const projectRows = yield* sql<{
|
||||
readonly projectId: string;
|
||||
readonly title: string;
|
||||
readonly scriptsJson: string;
|
||||
}>`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
scripts_json AS "scriptsJson"
|
||||
FROM projection_projects
|
||||
`;
|
||||
assert.deepEqual(projectRows, [
|
||||
{ projectId: "project-1", title: "Project 1", scriptsJson: "[]" },
|
||||
]);
|
||||
|
||||
const messageRows = yield* sql<{
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
}>`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
text
|
||||
FROM projection_thread_messages
|
||||
`;
|
||||
assert.deepEqual(messageRows, [{ messageId: "message-1", text: "hello" }]);
|
||||
|
||||
const stateRows = yield* sql<{
|
||||
readonly projector: string;
|
||||
readonly lastAppliedSequence: number;
|
||||
}>`
|
||||
SELECT
|
||||
projector,
|
||||
last_applied_sequence AS "lastAppliedSequence"
|
||||
FROM projection_state
|
||||
ORDER BY projector ASC
|
||||
`;
|
||||
assert.equal(stateRows.length, Object.keys(ORCHESTRATION_PROJECTOR_NAMES).length);
|
||||
for (const row of stateRows) {
|
||||
assert.equal(row.lastAppliedSequence, 3);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resumes from projector last_applied_sequence without replaying older events", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe("evt-a1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.makeUnsafe("project-a"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-a1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-a1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe("evt-a2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-a"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-a2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-a2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-a"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-a3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-a"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-a3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-a3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-a"),
|
||||
messageId: MessageId.makeUnsafe("message-a"),
|
||||
role: "assistant",
|
||||
text: "hello",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-a4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-a"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-a4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-a4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-a"),
|
||||
messageId: MessageId.makeUnsafe("message-a"),
|
||||
role: "assistant",
|
||||
text: " world",
|
||||
turnId: null,
|
||||
streaming: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const messageRows = yield* sql<{ readonly text: string }>`
|
||||
SELECT text FROM projection_thread_messages WHERE message_id = 'message-a'
|
||||
`;
|
||||
assert.deepEqual(messageRows, [{ text: "hello world" }]);
|
||||
|
||||
const stateRows = yield* sql<{
|
||||
readonly projector: string;
|
||||
readonly lastAppliedSequence: number;
|
||||
}>`
|
||||
SELECT
|
||||
projector,
|
||||
last_applied_sequence AS "lastAppliedSequence"
|
||||
FROM projection_state
|
||||
`;
|
||||
const maxSequenceRows = yield* sql<{ readonly maxSequence: number }>`
|
||||
SELECT MAX(sequence) AS "maxSequence" FROM orchestration_events
|
||||
`;
|
||||
const maxSequence = maxSequenceRows[0]?.maxSequence ?? 0;
|
||||
for (const row of stateRows) {
|
||||
assert.equal(row.lastAppliedSequence, maxSequence);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps accumulated assistant text when completion payload text is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe("evt-empty-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.makeUnsafe("project-empty"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-empty-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-empty-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Project Empty",
|
||||
workspaceRoot: "/tmp/project-empty",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe("evt-empty-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-empty"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-empty-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-empty-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-empty"),
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Thread Empty",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-empty-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-empty"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-empty-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-empty-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-empty"),
|
||||
messageId: MessageId.makeUnsafe("assistant-empty"),
|
||||
role: "assistant",
|
||||
text: "Hello",
|
||||
turnId: null,
|
||||
streaming: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-empty-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-empty"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-empty-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-empty-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-empty"),
|
||||
messageId: MessageId.makeUnsafe("assistant-empty"),
|
||||
role: "assistant",
|
||||
text: " world",
|
||||
turnId: null,
|
||||
streaming: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-empty-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-empty"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-empty-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-empty-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-empty"),
|
||||
messageId: MessageId.makeUnsafe("assistant-empty"),
|
||||
role: "assistant",
|
||||
text: "",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const messageRows = yield* sql<{ readonly text: string; readonly isStreaming: unknown }>`
|
||||
SELECT
|
||||
text,
|
||||
is_streaming AS "isStreaming"
|
||||
FROM projection_thread_messages
|
||||
WHERE message_id = 'assistant-empty'
|
||||
`;
|
||||
assert.equal(messageRows.length, 1);
|
||||
assert.equal(messageRows[0]?.text, "Hello world");
|
||||
assert.isFalse(Boolean(messageRows[0]?.isStreaming));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves turn-count conflicts when checkpoint completion rewrites provisional turns", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe("evt-conflict-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.makeUnsafe("project-conflict"),
|
||||
occurredAt: "2026-02-26T13:00:00.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-conflict-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-conflict-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Project Conflict",
|
||||
workspaceRoot: "/tmp/project-conflict",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T13:00:00.000Z",
|
||||
updatedAt: "2026-02-26T13:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe("evt-conflict-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
occurredAt: "2026-02-26T13:00:01.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-conflict-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-conflict-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Thread Conflict",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T13:00:01.000Z",
|
||||
updatedAt: "2026-02-26T13:00:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-interrupt-requested",
|
||||
eventId: EventId.makeUnsafe("evt-conflict-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
occurredAt: "2026-02-26T13:00:02.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-conflict-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-conflict-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
turnId: TurnId.makeUnsafe("turn-interrupted"),
|
||||
createdAt: "2026-02-26T13:00:02.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-conflict-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
occurredAt: "2026-02-26T13:00:03.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-conflict-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-conflict-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
messageId: MessageId.makeUnsafe("assistant-conflict"),
|
||||
role: "assistant",
|
||||
text: "done",
|
||||
turnId: TurnId.makeUnsafe("turn-completed"),
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T13:00:03.000Z",
|
||||
updatedAt: "2026-02-26T13:00:03.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: EventId.makeUnsafe("evt-conflict-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
occurredAt: "2026-02-26T13:00:04.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-conflict-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-conflict-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
turnId: TurnId.makeUnsafe("turn-completed"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-conflict/turn/1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant-conflict"),
|
||||
completedAt: "2026-02-26T13:00:04.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
const turnRows = yield* sql<{
|
||||
readonly turnId: string;
|
||||
readonly checkpointTurnCount: number | null;
|
||||
readonly status: string;
|
||||
}>`
|
||||
SELECT
|
||||
turn_id AS "turnId",
|
||||
checkpoint_turn_count AS "checkpointTurnCount",
|
||||
state AS "status"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = 'thread-conflict'
|
||||
ORDER BY
|
||||
CASE
|
||||
WHEN checkpoint_turn_count IS NULL THEN 1
|
||||
ELSE 0
|
||||
END ASC,
|
||||
checkpoint_turn_count ASC,
|
||||
requested_at ASC
|
||||
`;
|
||||
assert.deepEqual(turnRows, [
|
||||
{ turnId: "turn-completed", checkpointTurnCount: 1, status: "completed" },
|
||||
{ turnId: "turn-interrupted", checkpointTurnCount: null, status: "interrupted" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not fallback-retain messages whose turnId is removed by revert", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe("evt-revert-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.makeUnsafe("project-revert"),
|
||||
occurredAt: "2026-02-26T12:00:00.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Project Revert",
|
||||
workspaceRoot: "/tmp/project-revert",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:00:00.000Z",
|
||||
updatedAt: "2026-02-26T12:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe("evt-revert-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-revert"),
|
||||
occurredAt: "2026-02-26T12:00:01.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Thread Revert",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:00:01.000Z",
|
||||
updatedAt: "2026-02-26T12:00:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: EventId.makeUnsafe("evt-revert-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-revert"),
|
||||
occurredAt: "2026-02-26T12:00:02.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/1"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant-keep"),
|
||||
completedAt: "2026-02-26T12:00:02.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-revert-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-revert"),
|
||||
occurredAt: "2026-02-26T12:00:02.100Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
messageId: MessageId.makeUnsafe("assistant-keep"),
|
||||
role: "assistant",
|
||||
text: "kept",
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T12:00:02.100Z",
|
||||
updatedAt: "2026-02-26T12:00:02.100Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: EventId.makeUnsafe("evt-revert-5"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-revert"),
|
||||
occurredAt: "2026-02-26T12:00:03.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-5"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-5"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
checkpointTurnCount: 2,
|
||||
checkpointRef: CheckpointRef.makeUnsafe("refs/t3/checkpoints/thread-revert/turn/2"),
|
||||
status: "ready",
|
||||
files: [],
|
||||
assistantMessageId: MessageId.makeUnsafe("assistant-remove"),
|
||||
completedAt: "2026-02-26T12:00:03.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-revert-6"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-revert"),
|
||||
occurredAt: "2026-02-26T12:00:03.050Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-6"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-6"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
messageId: MessageId.makeUnsafe("user-remove"),
|
||||
role: "user",
|
||||
text: "removed",
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T12:00:03.050Z",
|
||||
updatedAt: "2026-02-26T12:00:03.050Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.makeUnsafe("evt-revert-7"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-revert"),
|
||||
occurredAt: "2026-02-26T12:00:03.100Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-7"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-7"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
messageId: MessageId.makeUnsafe("assistant-remove"),
|
||||
role: "assistant",
|
||||
text: "removed",
|
||||
turnId: TurnId.makeUnsafe("turn-2"),
|
||||
streaming: false,
|
||||
createdAt: "2026-02-26T12:00:03.100Z",
|
||||
updatedAt: "2026-02-26T12:00:03.100Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.reverted",
|
||||
eventId: EventId.makeUnsafe("evt-revert-8"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-revert"),
|
||||
occurredAt: "2026-02-26T12:00:04.000Z",
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-8"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-revert-8"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
turnCount: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const messageRows = yield* sql<{
|
||||
readonly messageId: string;
|
||||
readonly turnId: string | null;
|
||||
readonly role: string;
|
||||
}>`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
turn_id AS "turnId",
|
||||
role
|
||||
FROM projection_thread_messages
|
||||
WHERE thread_id = 'thread-revert'
|
||||
ORDER BY created_at ASC, message_id ASC
|
||||
`;
|
||||
assert.deepEqual(messageRows, [
|
||||
{
|
||||
messageId: "assistant-keep",
|
||||
turnId: "turn-1",
|
||||
role: "assistant",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
});
|
||||
|
||||
it.effect("restores pending turn-start metadata across projection pipeline restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-pipeline-restart-"));
|
||||
const dbPath = path.join(tempDir, "orchestration.sqlite");
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const firstProjectionLayer = OrchestrationProjectionPipelineLive.pipe(
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(persistenceLayer),
|
||||
);
|
||||
const secondProjectionLayer = OrchestrationProjectionPipelineLive.pipe(
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(persistenceLayer),
|
||||
);
|
||||
|
||||
const threadId = ThreadId.makeUnsafe("thread-restart");
|
||||
const turnId = TurnId.makeUnsafe("turn-restart");
|
||||
const messageId = MessageId.makeUnsafe("message-restart");
|
||||
const turnStartedAt = "2026-02-26T14:00:00.000Z";
|
||||
const sessionSetAt = "2026-02-26T14:00:05.000Z";
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.turn-start-requested",
|
||||
eventId: EventId.makeUnsafe("evt-restart-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: turnStartedAt,
|
||||
commandId: CommandId.makeUnsafe("cmd-restart-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-restart-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId,
|
||||
createdAt: turnStartedAt,
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
}).pipe(Effect.provide(firstProjectionLayer));
|
||||
|
||||
const turnRows = yield* Effect.gen(function* () {
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.makeUnsafe("evt-restart-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: sessionSetAt,
|
||||
commandId: CommandId.makeUnsafe("cmd-restart-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-restart-2"),
|
||||
metadata: {
|
||||
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
||||
},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: sessionSetAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const pendingRows = yield* sql<{ readonly threadId: string }>`
|
||||
SELECT thread_id AS "threadId"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
AND turn_id IS NULL
|
||||
AND state = 'pending'
|
||||
`;
|
||||
assert.deepEqual(pendingRows, []);
|
||||
|
||||
return yield* sql<{
|
||||
readonly turnId: string;
|
||||
readonly userMessageId: string | null;
|
||||
readonly startedAt: string;
|
||||
}>`
|
||||
SELECT
|
||||
turn_id AS "turnId",
|
||||
pending_message_id AS "userMessageId",
|
||||
started_at AS "startedAt"
|
||||
FROM projection_turns
|
||||
WHERE turn_id = ${turnId}
|
||||
`;
|
||||
}).pipe(Effect.provide(secondProjectionLayer));
|
||||
|
||||
assert.deepEqual(turnRows, [
|
||||
{
|
||||
turnId: "turn-restart",
|
||||
userMessageId: "message-restart",
|
||||
startedAt: turnStartedAt,
|
||||
},
|
||||
]);
|
||||
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const engineLayer = it.layer(
|
||||
OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provideMerge(SqlitePersistenceMemory),
|
||||
),
|
||||
);
|
||||
|
||||
engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
it.effect("projects dispatched engine events immediately", () =>
|
||||
Effect.gen(function* () {
|
||||
const engine = yield* OrchestrationEngineService;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
yield* engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-live-project"),
|
||||
projectId: ProjectId.makeUnsafe("project-live"),
|
||||
title: "Live Project",
|
||||
workspaceRoot: "/tmp/project-live",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const projectRows = yield* sql<{ readonly title: string; readonly scriptsJson: string }>`
|
||||
SELECT
|
||||
title,
|
||||
scripts_json AS "scriptsJson"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-live'
|
||||
`;
|
||||
assert.deepEqual(projectRows, [{ title: "Live Project", scriptsJson: "[]" }]);
|
||||
|
||||
const projectorRows = yield* sql<{ readonly lastAppliedSequence: number }>`
|
||||
SELECT
|
||||
last_applied_sequence AS "lastAppliedSequence"
|
||||
FROM projection_state
|
||||
WHERE projector = 'projection.projects'
|
||||
`;
|
||||
assert.deepEqual(projectorRows, [{ lastAppliedSequence: 1 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("projects persist updated scripts from project.meta.update", () =>
|
||||
Effect.gen(function* () {
|
||||
const engine = yield* OrchestrationEngineService;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
yield* engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-scripts-project-create"),
|
||||
projectId: ProjectId.makeUnsafe("project-scripts"),
|
||||
title: "Scripts Project",
|
||||
workspaceRoot: "/tmp/project-scripts",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
yield* engine.dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-scripts-project-update"),
|
||||
projectId: ProjectId.makeUnsafe("project-scripts"),
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
name: "Build",
|
||||
command: "bun run build",
|
||||
icon: "build",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
defaultModel: "gpt-5",
|
||||
});
|
||||
|
||||
const projectRows = yield* sql<{
|
||||
readonly scriptsJson: string;
|
||||
readonly defaultModel: string;
|
||||
}>`
|
||||
SELECT
|
||||
scripts_json AS "scriptsJson",
|
||||
default_model AS "defaultModel"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-scripts'
|
||||
`;
|
||||
assert.deepEqual(projectRows, [
|
||||
{
|
||||
scriptsJson:
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
defaultModel: "gpt-5",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,898 +0,0 @@
|
||||
import { ApprovalRequestId, type OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
|
||||
import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { ProjectionProjectRepository } from "../../persistence/Services/ProjectionProjects.ts";
|
||||
import { ProjectionStateRepository } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { type ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import {
|
||||
type ProjectionThreadMessage,
|
||||
ProjectionThreadMessageRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import { type ProjectionTurn, ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
|
||||
import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
|
||||
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
import {
|
||||
OrchestrationProjectionPipeline,
|
||||
type OrchestrationProjectionPipelineShape,
|
||||
} from "../Services/ProjectionPipeline.ts";
|
||||
|
||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
projects: "projection.projects",
|
||||
threads: "projection.threads",
|
||||
threadMessages: "projection.thread-messages",
|
||||
threadActivities: "projection.thread-activities",
|
||||
threadSessions: "projection.thread-sessions",
|
||||
threadTurns: "projection.thread-turns",
|
||||
checkpoints: "projection.checkpoints",
|
||||
pendingApprovals: "projection.pending-approvals",
|
||||
} as const;
|
||||
|
||||
type ProjectorName =
|
||||
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
|
||||
|
||||
interface ProjectorDefinition {
|
||||
readonly name: ProjectorName;
|
||||
readonly apply: (event: OrchestrationEvent) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
return null;
|
||||
}
|
||||
const requestId = (payload as Record<string, unknown>).requestId;
|
||||
return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null;
|
||||
}
|
||||
|
||||
function retainProjectionMessagesAfterRevert(
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
turnCount: number,
|
||||
): ReadonlyArray<ProjectionThreadMessage> {
|
||||
const retainedMessageIds = new Set<string>();
|
||||
const retainedTurnIds = new Set<string>();
|
||||
const keptTurns = turns.filter(
|
||||
(turn) => turn.turnId !== null && turn.checkpointTurnCount !== null && turn.checkpointTurnCount <= turnCount,
|
||||
);
|
||||
for (const turn of keptTurns) {
|
||||
if (turn.turnId !== null) {
|
||||
retainedTurnIds.add(turn.turnId);
|
||||
}
|
||||
if (turn.pendingMessageId !== null) {
|
||||
retainedMessageIds.add(turn.pendingMessageId);
|
||||
}
|
||||
if (turn.assistantMessageId !== null) {
|
||||
retainedMessageIds.add(turn.assistantMessageId);
|
||||
}
|
||||
}
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.role === "system") {
|
||||
retainedMessageIds.add(message.messageId);
|
||||
continue;
|
||||
}
|
||||
if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
|
||||
retainedMessageIds.add(message.messageId);
|
||||
}
|
||||
}
|
||||
|
||||
const retainedUserCount = messages.filter(
|
||||
(message) => message.role === "user" && retainedMessageIds.has(message.messageId),
|
||||
).length;
|
||||
const missingUserCount = Math.max(0, turnCount - retainedUserCount);
|
||||
if (missingUserCount > 0) {
|
||||
const fallbackUserMessages = messages
|
||||
.filter(
|
||||
(message) =>
|
||||
message.role === "user" &&
|
||||
!retainedMessageIds.has(message.messageId) &&
|
||||
(message.turnId === null || retainedTurnIds.has(message.turnId)),
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.messageId.localeCompare(right.messageId),
|
||||
)
|
||||
.slice(0, missingUserCount);
|
||||
for (const message of fallbackUserMessages) {
|
||||
retainedMessageIds.add(message.messageId);
|
||||
}
|
||||
}
|
||||
|
||||
const retainedAssistantCount = messages.filter(
|
||||
(message) => message.role === "assistant" && retainedMessageIds.has(message.messageId),
|
||||
).length;
|
||||
const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);
|
||||
if (missingAssistantCount > 0) {
|
||||
const fallbackAssistantMessages = messages
|
||||
.filter(
|
||||
(message) =>
|
||||
message.role === "assistant" &&
|
||||
!retainedMessageIds.has(message.messageId) &&
|
||||
(message.turnId === null || retainedTurnIds.has(message.turnId)),
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.messageId.localeCompare(right.messageId),
|
||||
)
|
||||
.slice(0, missingAssistantCount);
|
||||
for (const message of fallbackAssistantMessages) {
|
||||
retainedMessageIds.add(message.messageId);
|
||||
}
|
||||
}
|
||||
|
||||
return messages.filter((message) => retainedMessageIds.has(message.messageId));
|
||||
}
|
||||
|
||||
function retainProjectionActivitiesAfterRevert(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
turnCount: number,
|
||||
): ReadonlyArray<ProjectionThreadActivity> {
|
||||
const retainedTurnIds = new Set<string>(
|
||||
turns
|
||||
.filter(
|
||||
(turn) =>
|
||||
turn.turnId !== null &&
|
||||
turn.checkpointTurnCount !== null &&
|
||||
turn.checkpointTurnCount <= turnCount,
|
||||
)
|
||||
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
|
||||
);
|
||||
return activities.filter(
|
||||
(activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
|
||||
);
|
||||
}
|
||||
|
||||
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionStateRepository = yield* ProjectionStateRepository;
|
||||
const projectionProjectRepository = yield* ProjectionProjectRepository;
|
||||
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "project.created":
|
||||
yield* projectionProjectRepository.upsert({
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
workspaceRoot: event.payload.workspaceRoot,
|
||||
defaultModel: event.payload.defaultModel,
|
||||
scripts: event.payload.scripts,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
|
||||
case "project.meta-updated": {
|
||||
const existingRow = yield* projectionProjectRepository.getById({
|
||||
projectId: event.payload.projectId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionProjectRepository.upsert({
|
||||
...existingRow.value,
|
||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||
...(event.payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: event.payload.workspaceRoot }
|
||||
: {}),
|
||||
...(event.payload.defaultModel !== undefined
|
||||
? { defaultModel: event.payload.defaultModel }
|
||||
: {}),
|
||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "project.deleted": {
|
||||
const existingRow = yield* projectionProjectRepository.getById({
|
||||
projectId: event.payload.projectId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionProjectRepository.upsert({
|
||||
...existingRow.value,
|
||||
deletedAt: event.payload.deletedAt,
|
||||
updatedAt: event.payload.deletedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.created":
|
||||
yield* projectionThreadRepository.upsert({
|
||||
threadId: event.payload.threadId,
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
model: event.payload.model,
|
||||
branch: event.payload.branch,
|
||||
worktreePath: event.payload.worktreePath,
|
||||
latestTurnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.meta-updated": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
|
||||
...(event.payload.worktreePath !== undefined
|
||||
? { worktreePath: event.payload.worktreePath }
|
||||
: {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.deleted": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
deletedAt: event.payload.deletedAt,
|
||||
updatedAt: event.payload.deletedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.activity-appended": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.session-set": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestTurnId: event.payload.session.activeTurnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.turn-diff-completed": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestTurnId: event.payload.turnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadMessagesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent": {
|
||||
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const existingMessage = existingRows.find(
|
||||
(row) => row.messageId === event.payload.messageId,
|
||||
);
|
||||
const nextText =
|
||||
existingMessage && event.payload.streaming
|
||||
? `${existingMessage.text}${event.payload.text}`
|
||||
: existingMessage && event.payload.text.length === 0
|
||||
? existingMessage.text
|
||||
: event.payload.text;
|
||||
yield* projectionThreadMessageRepository.upsert({
|
||||
messageId: event.payload.messageId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
role: event.payload.role,
|
||||
text: nextText,
|
||||
isStreaming: event.payload.streaming,
|
||||
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (existingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const keptRows = retainProjectionMessagesAfterRevert(
|
||||
existingRows,
|
||||
existingTurns,
|
||||
event.payload.turnCount,
|
||||
);
|
||||
if (keptRows.length === existingRows.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* projectionThreadMessageRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended":
|
||||
yield* projectionThreadActivityRepository.upsert({
|
||||
activityId: event.payload.activity.id,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.activity.turnId,
|
||||
tone: event.payload.activity.tone,
|
||||
kind: event.payload.activity.kind,
|
||||
summary: event.payload.activity.summary,
|
||||
payload: event.payload.activity.payload,
|
||||
createdAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingRows = yield* projectionThreadActivityRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (existingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const keptRows = retainProjectionActivitiesAfterRevert(
|
||||
existingRows,
|
||||
existingTurns,
|
||||
event.payload.turnCount,
|
||||
);
|
||||
if (keptRows.length === existingRows.length) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadActivityRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (event.type !== "thread.session-set") {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadSessionRepository.upsert({
|
||||
threadId: event.payload.threadId,
|
||||
status: event.payload.session.status,
|
||||
providerName: event.payload.session.providerName,
|
||||
providerSessionId: event.payload.session.providerSessionId,
|
||||
providerThreadId: event.payload.session.providerThreadId,
|
||||
activeTurnId: event.payload.session.activeTurnId,
|
||||
lastError: event.payload.session.lastError,
|
||||
updatedAt: event.payload.session.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.turn-start-requested": {
|
||||
yield* projectionTurnRepository.replacePendingTurnStart({
|
||||
threadId: event.payload.threadId,
|
||||
messageId: event.payload.messageId,
|
||||
requestedAt: event.payload.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.session-set": {
|
||||
const turnId = event.payload.session.activeTurnId;
|
||||
if (turnId === null || event.payload.session.status !== "running") {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId,
|
||||
});
|
||||
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isSome(existingTurn)) {
|
||||
const nextState =
|
||||
existingTurn.value.state === "completed" || existingTurn.value.state === "error"
|
||||
? existingTurn.value.state
|
||||
: "running";
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
state: nextState,
|
||||
pendingMessageId:
|
||||
existingTurn.value.pendingMessageId ??
|
||||
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
|
||||
startedAt:
|
||||
existingTurn.value.startedAt ??
|
||||
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.requestedAt : event.occurredAt),
|
||||
requestedAt:
|
||||
existingTurn.value.requestedAt ??
|
||||
(Option.isSome(pendingTurnStart) ? pendingTurnStart.value.requestedAt : event.occurredAt),
|
||||
});
|
||||
} else {
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
turnId,
|
||||
threadId: event.payload.threadId,
|
||||
pendingMessageId: Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null,
|
||||
assistantMessageId: null,
|
||||
state: "running",
|
||||
requestedAt: Option.isSome(pendingTurnStart)
|
||||
? pendingTurnStart.value.requestedAt
|
||||
: event.occurredAt,
|
||||
startedAt: Option.isSome(pendingTurnStart)
|
||||
? pendingTurnStart.value.requestedAt
|
||||
: event.occurredAt,
|
||||
completedAt: null,
|
||||
checkpointTurnCount: null,
|
||||
checkpointRef: null,
|
||||
checkpointStatus: null,
|
||||
checkpointFiles: [],
|
||||
});
|
||||
}
|
||||
|
||||
yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.message-sent": {
|
||||
if (event.payload.turnId === null || event.payload.role !== "assistant") {
|
||||
return;
|
||||
}
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
});
|
||||
if (Option.isSome(existingTurn)) {
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
state: event.payload.streaming
|
||||
? existingTurn.value.state
|
||||
: existingTurn.value.state === "interrupted"
|
||||
? "interrupted"
|
||||
: existingTurn.value.state === "error"
|
||||
? "error"
|
||||
: "completed",
|
||||
completedAt: event.payload.streaming
|
||||
? existingTurn.value.completedAt
|
||||
: (existingTurn.value.completedAt ?? event.payload.updatedAt),
|
||||
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
|
||||
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
turnId: event.payload.turnId,
|
||||
threadId: event.payload.threadId,
|
||||
pendingMessageId: null,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
state: event.payload.streaming ? "running" : "completed",
|
||||
requestedAt: event.payload.createdAt,
|
||||
startedAt: event.payload.createdAt,
|
||||
completedAt: event.payload.streaming ? null : event.payload.updatedAt,
|
||||
checkpointTurnCount: null,
|
||||
checkpointRef: null,
|
||||
checkpointStatus: null,
|
||||
checkpointFiles: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.turn-interrupt-requested": {
|
||||
if (event.payload.turnId === undefined) {
|
||||
return;
|
||||
}
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
});
|
||||
if (Option.isSome(existingTurn)) {
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
state: "interrupted",
|
||||
completedAt: existingTurn.value.completedAt ?? event.payload.createdAt,
|
||||
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
|
||||
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
turnId: event.payload.turnId,
|
||||
threadId: event.payload.threadId,
|
||||
pendingMessageId: null,
|
||||
assistantMessageId: null,
|
||||
state: "interrupted",
|
||||
requestedAt: event.payload.createdAt,
|
||||
startedAt: event.payload.createdAt,
|
||||
completedAt: event.payload.createdAt,
|
||||
checkpointTurnCount: null,
|
||||
checkpointRef: null,
|
||||
checkpointStatus: null,
|
||||
checkpointFiles: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.turn-diff-completed": {
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
});
|
||||
const nextState = event.payload.status === "error" ? "error" : "completed";
|
||||
yield* projectionTurnRepository.clearCheckpointTurnConflict({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
checkpointTurnCount: event.payload.checkpointTurnCount,
|
||||
});
|
||||
|
||||
if (Option.isSome(existingTurn)) {
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
assistantMessageId: event.payload.assistantMessageId,
|
||||
state: nextState,
|
||||
checkpointTurnCount: event.payload.checkpointTurnCount,
|
||||
checkpointRef: event.payload.checkpointRef,
|
||||
checkpointStatus: event.payload.status,
|
||||
checkpointFiles: event.payload.files,
|
||||
startedAt: existingTurn.value.startedAt ?? event.payload.completedAt,
|
||||
requestedAt: existingTurn.value.requestedAt ?? event.payload.completedAt,
|
||||
completedAt: event.payload.completedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
turnId: event.payload.turnId,
|
||||
threadId: event.payload.threadId,
|
||||
pendingMessageId: null,
|
||||
assistantMessageId: event.payload.assistantMessageId,
|
||||
state: nextState,
|
||||
requestedAt: event.payload.completedAt,
|
||||
startedAt: event.payload.completedAt,
|
||||
completedAt: event.payload.completedAt,
|
||||
checkpointTurnCount: event.payload.checkpointTurnCount,
|
||||
checkpointRef: event.payload.checkpointRef,
|
||||
checkpointStatus: event.payload.status,
|
||||
checkpointFiles: event.payload.files,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const keptTurns = existingTurns.filter(
|
||||
(turn) =>
|
||||
turn.turnId !== null &&
|
||||
turn.checkpointTurnCount !== null &&
|
||||
turn.checkpointTurnCount <= event.payload.turnCount,
|
||||
);
|
||||
yield* projectionTurnRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
keptTurns,
|
||||
(turn) =>
|
||||
turn.turnId === null
|
||||
? Effect.void
|
||||
: projectionTurnRepository.upsertByTurnId({
|
||||
...turn,
|
||||
turnId: turn.turnId,
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
|
||||
|
||||
const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = (event) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.activity-appended": {
|
||||
const requestId =
|
||||
extractActivityRequestId(event.payload.activity.payload) ??
|
||||
event.metadata.requestId ??
|
||||
null;
|
||||
if (requestId === null) {
|
||||
return;
|
||||
}
|
||||
const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({
|
||||
requestId,
|
||||
});
|
||||
if (event.payload.activity.kind === "approval.resolved") {
|
||||
const resolvedDecisionRaw =
|
||||
typeof event.payload.activity.payload === "object" &&
|
||||
event.payload.activity.payload !== null &&
|
||||
"decision" in event.payload.activity.payload
|
||||
? (event.payload.activity.payload as { decision?: unknown }).decision
|
||||
: null;
|
||||
const resolvedDecision =
|
||||
resolvedDecisionRaw === "accept" ||
|
||||
resolvedDecisionRaw === "acceptForSession" ||
|
||||
resolvedDecisionRaw === "decline" ||
|
||||
resolvedDecisionRaw === "cancel"
|
||||
? resolvedDecisionRaw
|
||||
: null;
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId,
|
||||
threadId: Option.isSome(existingRow)
|
||||
? existingRow.value.threadId
|
||||
: event.payload.threadId,
|
||||
turnId: Option.isSome(existingRow)
|
||||
? existingRow.value.turnId
|
||||
: event.payload.activity.turnId,
|
||||
status: "resolved",
|
||||
decision: resolvedDecision,
|
||||
createdAt: Option.isSome(existingRow)
|
||||
? existingRow.value.createdAt
|
||||
: event.payload.activity.createdAt,
|
||||
resolvedAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.activity.turnId,
|
||||
status: "pending",
|
||||
decision: null,
|
||||
createdAt: Option.isSome(existingRow)
|
||||
? existingRow.value.createdAt
|
||||
: event.payload.activity.createdAt,
|
||||
resolvedAt: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.approval-response-requested": {
|
||||
const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId: event.payload.requestId,
|
||||
threadId: Option.isSome(existingRow)
|
||||
? existingRow.value.threadId
|
||||
: event.payload.threadId,
|
||||
turnId: Option.isSome(existingRow) ? existingRow.value.turnId : null,
|
||||
status: "resolved",
|
||||
decision: event.payload.decision,
|
||||
createdAt: Option.isSome(existingRow)
|
||||
? existingRow.value.createdAt
|
||||
: event.payload.createdAt,
|
||||
resolvedAt: event.payload.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const projectors: ReadonlyArray<ProjectorDefinition> = [
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
apply: applyProjectsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
apply: applyThreadMessagesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
apply: applyThreadActivitiesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
apply: applyThreadSessionsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
|
||||
apply: applyThreadTurnsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
apply: applyCheckpointsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
|
||||
apply: applyPendingApprovalsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threads,
|
||||
apply: applyThreadsProjection,
|
||||
},
|
||||
];
|
||||
|
||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||
sql.withTransaction(
|
||||
projector.apply(event).pipe(
|
||||
Effect.flatMap(() =>
|
||||
projectionStateRepository.upsert({
|
||||
projector: projector.name,
|
||||
lastAppliedSequence: event.sequence,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const bootstrapProjector = (projector: ProjectorDefinition) =>
|
||||
projectionStateRepository
|
||||
.getByProjector({
|
||||
projector: projector.name,
|
||||
})
|
||||
.pipe(
|
||||
Effect.flatMap((stateRow) =>
|
||||
Stream.runForEach(
|
||||
eventStore.readFromSequence(
|
||||
Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
|
||||
),
|
||||
(event) => runProjectorForEvent(projector, event),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
|
||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||
concurrency: 1,
|
||||
}).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||
),
|
||||
);
|
||||
|
||||
const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
|
||||
projectors,
|
||||
bootstrapProjector,
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.tap(() =>
|
||||
Effect.log("orchestration projection pipeline bootstrapped").pipe(
|
||||
Effect.annotateLogs({ projectors: projectors.length }),
|
||||
),
|
||||
),
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
bootstrap,
|
||||
projectEvent,
|
||||
} satisfies OrchestrationProjectionPipelineShape;
|
||||
});
|
||||
|
||||
export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
OrchestrationProjectionPipeline,
|
||||
makeOrchestrationProjectionPipeline,
|
||||
).pipe(
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
|
||||
Layer.provideMerge(ProjectionTurnRepositoryLive),
|
||||
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
|
||||
Layer.provideMerge(ProjectionStateRepositoryLive),
|
||||
);
|
||||
@@ -1,293 +0,0 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
|
||||
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
|
||||
const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
);
|
||||
|
||||
projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
it.effect("hydrates read model from projection tables and computes snapshot sequence", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`DELETE FROM projection_projects`;
|
||||
yield* sql`DELETE FROM projection_state`;
|
||||
yield* sql`DELETE FROM projection_turns`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_projects (
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'gpt-5-codex',
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:01.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
created_at,
|
||||
updated_at,
|
||||
deleted_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'gpt-5-codex',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
'2026-02-24T00:00:02.000Z',
|
||||
'2026-02-24T00:00:03.000Z',
|
||||
NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'message-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'assistant',
|
||||
'hello from projection',
|
||||
0,
|
||||
'2026-02-24T00:00:04.000Z',
|
||||
'2026-02-24T00:00:05.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
created_at
|
||||
)
|
||||
VALUES (
|
||||
'activity-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'info',
|
||||
'runtime.note',
|
||||
'provider started',
|
||||
'{"stage":"start"}',
|
||||
'2026-02-24T00:00:06.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_sessions (
|
||||
thread_id,
|
||||
status,
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'running',
|
||||
'codex',
|
||||
'provider-session-1',
|
||||
'provider-thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'2026-02-24T00:00:07.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_turns (
|
||||
thread_id,
|
||||
turn_id,
|
||||
pending_message_id,
|
||||
assistant_message_id,
|
||||
state,
|
||||
requested_at,
|
||||
started_at,
|
||||
completed_at,
|
||||
checkpoint_turn_count,
|
||||
checkpoint_ref,
|
||||
checkpoint_status,
|
||||
checkpoint_files_json
|
||||
)
|
||||
VALUES (
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
1,
|
||||
'checkpoint-1',
|
||||
'ready',
|
||||
'[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]'
|
||||
)
|
||||
`;
|
||||
|
||||
let sequence = 5;
|
||||
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
|
||||
yield* sql`
|
||||
INSERT INTO projection_state (
|
||||
projector,
|
||||
last_applied_sequence,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
${projector},
|
||||
${sequence},
|
||||
'2026-02-24T00:00:09.000Z'
|
||||
)
|
||||
`;
|
||||
sequence += 1;
|
||||
}
|
||||
|
||||
const snapshot = yield* snapshotQuery.getSnapshot();
|
||||
|
||||
assert.equal(snapshot.snapshotSequence, 5);
|
||||
assert.equal(snapshot.updatedAt, "2026-02-24T00:00:09.000Z");
|
||||
assert.deepEqual(snapshot.projects, [
|
||||
{
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
name: "Build",
|
||||
command: "bun run build",
|
||||
icon: "build",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-24T00:00:00.000Z",
|
||||
updatedAt: "2026-02-24T00:00:01.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(snapshot.threads, [
|
||||
{
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: asTurnId("turn-1"),
|
||||
createdAt: "2026-02-24T00:00:02.000Z",
|
||||
updatedAt: "2026-02-24T00:00:03.000Z",
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
id: asMessageId("message-1"),
|
||||
role: "assistant",
|
||||
text: "hello from projection",
|
||||
turnId: asTurnId("turn-1"),
|
||||
streaming: false,
|
||||
createdAt: "2026-02-24T00:00:04.000Z",
|
||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "provider started",
|
||||
payload: { stage: "start" },
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: "2026-02-24T00:00:06.000Z",
|
||||
},
|
||||
],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: asTurnId("turn-1"),
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: asCheckpointRef("checkpoint-1"),
|
||||
status: "ready",
|
||||
files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }],
|
||||
assistantMessageId: asMessageId("message-1"),
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
},
|
||||
],
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asProviderSessionId("provider-session-1"),
|
||||
providerThreadId: asProviderThreadId("provider-thread-1"),
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
},
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,446 +0,0 @@
|
||||
import {
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import {
|
||||
isPersistenceError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
type ProjectionRepositoryError,
|
||||
} from "../../persistence/Errors.ts";
|
||||
import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";
|
||||
import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";
|
||||
import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
import {
|
||||
ProjectionSnapshotQuery,
|
||||
type ProjectionSnapshotQueryShape,
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
Struct.assign({
|
||||
isStreaming: Schema.Number,
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
|
||||
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
|
||||
Struct.assign({
|
||||
files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),
|
||||
}),
|
||||
);
|
||||
const ProjectionStateDbRowSchema = ProjectionState;
|
||||
|
||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threads,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
] as const;
|
||||
|
||||
function maxIso(left: string | null, right: string): string {
|
||||
if (left === null) {
|
||||
return right;
|
||||
}
|
||||
return left > right ? left : right;
|
||||
}
|
||||
|
||||
function computeSnapshotSequence(
|
||||
stateRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionStateDbRowSchema>>,
|
||||
): number {
|
||||
if (stateRows.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const sequenceByProjector = new Map(
|
||||
stateRows.map((row) => [row.projector, row.lastAppliedSequence] as const),
|
||||
);
|
||||
|
||||
let minSequence = Number.POSITIVE_INFINITY;
|
||||
for (const projector of REQUIRED_SNAPSHOT_PROJECTORS) {
|
||||
const sequence = sequenceByProjector.get(projector);
|
||||
if (sequence === undefined) {
|
||||
return 0;
|
||||
}
|
||||
if (sequence < minSequence) {
|
||||
minSequence = sequence;
|
||||
}
|
||||
}
|
||||
|
||||
return Number.isFinite(minSequence) ? minSequence : 0;
|
||||
}
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown): ProjectionRepositoryError =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const listProjectRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_projects
|
||||
ORDER BY created_at ASC, project_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
deleted_at AS "deletedAt"
|
||||
FROM projection_threads
|
||||
ORDER BY created_at ASC, thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadMessageRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_messages
|
||||
ORDER BY thread_id ASC, created_at ASC, message_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
ORDER BY thread_id ASC, created_at ASC, activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadSessionRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
status,
|
||||
provider_name AS "providerName",
|
||||
provider_session_id AS "providerSessionId",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_sessions
|
||||
ORDER BY thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listCheckpointRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionCheckpointDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
checkpoint_turn_count AS "checkpointTurnCount",
|
||||
checkpoint_ref AS "checkpointRef",
|
||||
checkpoint_status AS "status",
|
||||
checkpoint_files_json AS "files",
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
completed_at AS "completedAt"
|
||||
FROM projection_turns
|
||||
WHERE checkpoint_turn_count IS NOT NULL
|
||||
ORDER BY thread_id ASC, checkpoint_turn_count ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionStateRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionStateDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
projector,
|
||||
last_applied_sequence AS "lastAppliedSequence",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_state
|
||||
`,
|
||||
});
|
||||
|
||||
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
|
||||
sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const [
|
||||
projectRows,
|
||||
threadRows,
|
||||
messageRows,
|
||||
activityRows,
|
||||
sessionRows,
|
||||
checkpointRows,
|
||||
stateRows,
|
||||
] = yield* Effect.all([
|
||||
listProjectRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listProjects:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreads:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadMessageRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listCheckpointRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listProjectionStateRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listProjectionState:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||
|
||||
let updatedAt: string | null = null;
|
||||
|
||||
for (const row of projectRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of threadRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
for (const row of stateRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
}
|
||||
|
||||
for (const row of messageRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
const threadMessages = messagesByThread.get(row.threadId) ?? [];
|
||||
threadMessages.push({
|
||||
id: row.messageId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
turnId: row.turnId,
|
||||
streaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
});
|
||||
messagesByThread.set(row.threadId, threadMessages);
|
||||
}
|
||||
|
||||
for (const row of activityRows) {
|
||||
updatedAt = maxIso(updatedAt, row.createdAt);
|
||||
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
|
||||
threadActivities.push({
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
}
|
||||
|
||||
for (const row of checkpointRows) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
|
||||
threadCheckpoints.push({
|
||||
turnId: row.turnId,
|
||||
checkpointTurnCount: row.checkpointTurnCount,
|
||||
checkpointRef: row.checkpointRef,
|
||||
status: row.status,
|
||||
files: row.files,
|
||||
assistantMessageId: row.assistantMessageId,
|
||||
completedAt: row.completedAt,
|
||||
});
|
||||
checkpointsByThread.set(row.threadId, threadCheckpoints);
|
||||
}
|
||||
|
||||
for (const row of sessionRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
sessionsByThread.set(row.threadId, {
|
||||
threadId: row.threadId,
|
||||
status: row.status,
|
||||
providerName: row.providerName,
|
||||
providerSessionId: row.providerSessionId,
|
||||
providerThreadId: row.providerThreadId,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModel: row.defaultModel,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}));
|
||||
|
||||
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
model: row.model,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurnId: row.latestTurnId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
}));
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: updatedAt ?? new Date(0).toISOString(),
|
||||
};
|
||||
|
||||
return yield* decodeReadModel(snapshot).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError("ProjectionSnapshotQuery.getSnapshot:decodeReadModel"),
|
||||
),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError((error) => {
|
||||
if (isPersistenceError(error)) {
|
||||
return error;
|
||||
}
|
||||
return toPersistenceSqlError("ProjectionSnapshotQuery.getSnapshot:query")(error);
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
getSnapshot,
|
||||
} satisfies ProjectionSnapshotQueryShape;
|
||||
});
|
||||
|
||||
export const OrchestrationProjectionSnapshotQueryLive = Layer.effect(
|
||||
ProjectionSnapshotQuery,
|
||||
makeProjectionSnapshotQuery,
|
||||
);
|
||||
@@ -1,313 +0,0 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (predicate()) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for expectation.");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return poll();
|
||||
};
|
||||
|
||||
return poll();
|
||||
}
|
||||
|
||||
describe("ProviderCommandReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderCommandReactor,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
scope = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
async function createHarness() {
|
||||
const now = new Date().toISOString();
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const startSession = vi.fn((_: unknown, __: unknown) =>
|
||||
Effect.succeed({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
provider: "codex" as const,
|
||||
status: "ready" as const,
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}),
|
||||
);
|
||||
const sendTurn = vi.fn((_: unknown) =>
|
||||
Effect.succeed({
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("provider-turn-1"),
|
||||
}),
|
||||
);
|
||||
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
||||
const respondToRequest = vi.fn((_: unknown) => Effect.void);
|
||||
const stopSession = vi.fn((_: unknown) => Effect.void);
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: startSession as ProviderServiceShape["startSession"],
|
||||
sendTurn: sendTurn as ProviderServiceShape["sendTurn"],
|
||||
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
|
||||
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed([]),
|
||||
rollbackConversation: () => unsupported(),
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, service)),
|
||||
);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start.pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(Effect.sleep("10 millis"));
|
||||
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
engine,
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
stopSession,
|
||||
};
|
||||
}
|
||||
|
||||
it("reacts to thread.turn.start by ensuring session and sending provider turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-1"),
|
||||
role: "user",
|
||||
text: "hello reactor",
|
||||
attachments: [],
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
cwd: "/tmp/provider-project",
|
||||
model: "gpt-5-codex",
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||
});
|
||||
|
||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.interruptTurn.mock.calls.length === 1);
|
||||
expect(harness.interruptTurn.mock.calls[0]?.[0]).toEqual({
|
||||
sessionId: "sess-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("reacts to thread.approval.respond by forwarding provider approval response", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
requestId: asApprovalRequestId("approval-request-1"),
|
||||
decision: "accept",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.respondToRequest.mock.calls.length === 1);
|
||||
expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({
|
||||
sessionId: "sess-1",
|
||||
requestId: "approval-request-1",
|
||||
decision: "accept",
|
||||
});
|
||||
});
|
||||
|
||||
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-stop"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.stop",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-stop"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session).not.toBeNull();
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
expect(thread?.session?.providerSessionId).toBeNull();
|
||||
expect(thread?.session?.providerThreadId).toBeNull();
|
||||
expect(thread?.session?.activeTurnId).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,381 +0,0 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderKind,
|
||||
type OrchestrationSession,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
type:
|
||||
| "thread.turn-start-requested"
|
||||
| "thread.turn-interrupt-requested"
|
||||
| "thread.approval-response-requested"
|
||||
| "thread.session-stop-requested";
|
||||
}
|
||||
>;
|
||||
|
||||
function toNonEmptyProviderInput(value: string | undefined): string | undefined {
|
||||
const normalized = value?.trim();
|
||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
||||
}
|
||||
|
||||
function mapProviderSessionStatusToOrchestrationStatus(
|
||||
status: "connecting" | "ready" | "running" | "error" | "closed",
|
||||
): OrchestrationSession["status"] {
|
||||
switch (status) {
|
||||
case "connecting":
|
||||
return "starting";
|
||||
case "running":
|
||||
return "running";
|
||||
case "error":
|
||||
return "error";
|
||||
case "closed":
|
||||
return "stopped";
|
||||
case "ready":
|
||||
default:
|
||||
return "ready";
|
||||
}
|
||||
}
|
||||
|
||||
const turnStartKeyForEvent = (event: ProviderIntentEvent): string =>
|
||||
event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;
|
||||
|
||||
const serverCommandId = (tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
capacity: HANDLED_TURN_START_KEY_MAX,
|
||||
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
||||
lookup: () => Effect.succeed(true),
|
||||
});
|
||||
|
||||
const hasHandledTurnStartRecently = (key: string) =>
|
||||
Cache.getOption(handledTurnStartKeys, key).pipe(
|
||||
Effect.flatMap((cached) =>
|
||||
Cache.set(handledTurnStartKeys, key, true).pipe(Effect.as(Option.isSome(cached))),
|
||||
),
|
||||
);
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly kind:
|
||||
| "provider.turn.start.failed"
|
||||
| "provider.turn.interrupt.failed"
|
||||
| "provider.approval.respond.failed"
|
||||
| "provider.session.stop.failed";
|
||||
readonly summary: string;
|
||||
readonly detail: string;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("provider-failure-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: input.kind,
|
||||
summary: input.summary,
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const setThreadSession = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly session: OrchestrationSession;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: serverCommandId("provider-session-set"),
|
||||
threadId: input.threadId,
|
||||
session: input.session,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
return readModel.threads.find((entry) => entry.id === threadId);
|
||||
});
|
||||
|
||||
const ensureSessionForThread = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (!thread) {
|
||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||
}
|
||||
|
||||
const existingSessionId = thread.session?.providerSessionId;
|
||||
if (existingSessionId) {
|
||||
return existingSessionId;
|
||||
}
|
||||
|
||||
const preferredProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
|
||||
const startedSession = yield* providerService.startSession(
|
||||
threadId,
|
||||
{
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(thread.model ? { model: thread.model } : {}),
|
||||
},
|
||||
);
|
||||
|
||||
yield* setThreadSession({
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: mapProviderSessionStatusToOrchestrationStatus(startedSession.status),
|
||||
providerName: startedSession.provider,
|
||||
providerSessionId: startedSession.sessionId,
|
||||
providerThreadId: startedSession.threadId ?? null,
|
||||
// Provider turn ids are not orchestration turn ids.
|
||||
activeTurnId: null,
|
||||
lastError: startedSession.lastError ?? null,
|
||||
updatedAt: startedSession.updatedAt,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
return startedSession.sessionId;
|
||||
});
|
||||
|
||||
const sendTurnForThread = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly model?: string;
|
||||
readonly effort?: string;
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt);
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
sessionId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.effort !== undefined ? { effort: input.effort } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const processTurnStartRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
||||
) {
|
||||
const key = turnStartKeyForEvent(event);
|
||||
if (yield* hasHandledTurnStartRecently(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = thread.messages.find((entry) => entry.id === event.payload.messageId);
|
||||
if (!message || message.role !== "user") {
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail: `User message '${event.payload.messageId}' was not found for turn start request.`,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
yield* sendTurnForThread({
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
const processTurnInterruptRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-interrupt-requested" }>,
|
||||
) {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
if (!sessionId) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.interrupt.failed",
|
||||
summary: "Provider turn interrupt failed",
|
||||
detail: "No active provider session is bound to this thread.",
|
||||
turnId: event.payload.turnId ?? null,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
// Orchestration turn ids are not provider turn ids, so interrupt by session.
|
||||
yield* providerService.interruptTurn({ sessionId });
|
||||
});
|
||||
|
||||
const processApprovalResponseRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.approval-response-requested" }>,
|
||||
) {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
if (!sessionId) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail: "No active provider session is bound to this thread.",
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
yield* providerService.respondToRequest({
|
||||
sessionId,
|
||||
requestId: event.payload.requestId,
|
||||
decision: event.payload.decision,
|
||||
});
|
||||
});
|
||||
|
||||
const processSessionStopRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
|
||||
) {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = event.payload.createdAt;
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
|
||||
if (sessionId) {
|
||||
yield* providerService.stopSession({ sessionId });
|
||||
}
|
||||
|
||||
yield* setThreadSession({
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status: "stopped",
|
||||
providerName: thread.session?.providerName ?? null,
|
||||
providerSessionId: null,
|
||||
providerThreadId: null,
|
||||
activeTurnId: null,
|
||||
lastError: thread.session?.lastError ?? null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
});
|
||||
|
||||
const processDomainEvent = (event: ProviderIntentEvent) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.turn-start-requested":
|
||||
yield* processTurnStartRequested(event);
|
||||
return;
|
||||
case "thread.turn-interrupt-requested":
|
||||
yield* processTurnInterruptRequested(event);
|
||||
return;
|
||||
case "thread.approval-response-requested":
|
||||
yield* processApprovalResponseRequested(event);
|
||||
return;
|
||||
case "thread.session-stop-requested":
|
||||
yield* processSessionStopRequested(event);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const processDomainEventSafely = (event: ProviderIntentEvent) =>
|
||||
processDomainEvent(event).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("provider command reactor failed to process event", {
|
||||
eventType: event.type,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const start: ProviderCommandReactorShape["start"] = Effect.gen(function* () {
|
||||
const queue = yield* Queue.unbounded<ProviderIntentEvent>();
|
||||
yield* Effect.addFinalizer(() => Queue.shutdown(queue).pipe(Effect.asVoid));
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.forever(Queue.take(queue).pipe(Effect.flatMap(processDomainEventSafely))),
|
||||
);
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
event.type !== "thread.turn-start-requested" &&
|
||||
event.type !== "thread.turn-interrupt-requested" &&
|
||||
event.type !== "thread.approval-response-requested" &&
|
||||
event.type !== "thread.session-stop-requested"
|
||||
) {
|
||||
return Effect.void;
|
||||
}
|
||||
|
||||
return Queue.offer(queue, event).pipe(Effect.asVoid);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
} satisfies ProviderCommandReactorShape;
|
||||
});
|
||||
|
||||
export const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);
|
||||
@@ -1,438 +0,0 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ProviderItemId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
|
||||
function createProviderServiceHarness() {
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderServiceShape = {
|
||||
startSession: () => unsupported(),
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions: () => Effect.succeed([]),
|
||||
rollbackConversation: () => unsupported(),
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
|
||||
};
|
||||
|
||||
return {
|
||||
service,
|
||||
emit,
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForThread(
|
||||
engine: OrchestrationEngineShape,
|
||||
predicate: (thread: {
|
||||
session: { status: string; activeTurnId: string | null; lastError: string | null } | null;
|
||||
messages: ReadonlyArray<{ id: string; text: string; streaming: boolean }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}) => boolean,
|
||||
timeoutMs = 2000,
|
||||
) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<{
|
||||
session: { status: string; activeTurnId: string | null; lastError: string | null } | null;
|
||||
messages: ReadonlyArray<{ id: string; text: string; streaming: boolean }>;
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error("Timed out waiting for thread state");
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
return poll();
|
||||
};
|
||||
return poll();
|
||||
}
|
||||
|
||||
describe("ProviderRuntimeIngestion", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderRuntimeIngestionService,
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
}
|
||||
scope = null;
|
||||
if (runtime) {
|
||||
await runtime.dispose();
|
||||
}
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
async function createHarness() {
|
||||
const provider = createProviderServiceHarness();
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(ingestion.start.pipe(Scope.provide(scope)));
|
||||
await Effect.runPromise(Effect.sleep("10 millis"));
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-provider-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
engine,
|
||||
emit: provider.emit,
|
||||
};
|
||||
}
|
||||
|
||||
it("maps turn started/completed events into thread session updates", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) => thread.session?.status === "running" && thread.session?.activeTurnId === "turn-1",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
status: "failed",
|
||||
errorMessage: "turn failed",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
entry.session?.lastError === "turn failed",
|
||||
);
|
||||
expect(thread.session?.status).toBe("error");
|
||||
expect(thread.session?.lastError).toBe("turn failed");
|
||||
});
|
||||
|
||||
it("maps message delta/completed into finalized assistant messages", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-message-delta-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-2"),
|
||||
itemId: asItemId("item-1"),
|
||||
delta: "hello",
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-message-delta-2"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-2"),
|
||||
itemId: asItemId("item-1"),
|
||||
delta: " world",
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
eventId: asEventId("evt-message-completed"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-2"),
|
||||
itemId: asItemId("item-1"),
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some((message) => message.id === "assistant:item-1" && !message.streaming),
|
||||
);
|
||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-1");
|
||||
expect(message?.text).toBe("hello world");
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("does not duplicate assistant completion when message.completed is followed by turn.completed", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-complete-dedup",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-message-delta-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
itemId: asItemId("item-complete-dedup"),
|
||||
delta: "done",
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
eventId: asEventId("evt-message-completed-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
itemId: asItemId("item-complete-dedup"),
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "ready" &&
|
||||
thread.session?.activeTurnId === null &&
|
||||
thread.messages.some(
|
||||
(message) => message.id === "assistant:item-complete-dedup" && !message.streaming,
|
||||
),
|
||||
);
|
||||
|
||||
const events = await Effect.runPromise(
|
||||
Stream.runCollect(harness.engine.readEvents(0)).pipe(Effect.map((chunk) => Array.from(chunk))),
|
||||
);
|
||||
const completionEvents = events.filter((event) => {
|
||||
if (event.type !== "thread.message-sent") {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
event.payload.messageId === "assistant:item-complete-dedup" && event.payload.streaming === false
|
||||
);
|
||||
});
|
||||
expect(completionEvents).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("maps runtime.error into errored session state", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "runtime.error",
|
||||
eventId: asEventId("evt-runtime-error"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-3"),
|
||||
message: "runtime exploded",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-3" &&
|
||||
entry.session?.lastError === "runtime exploded",
|
||||
);
|
||||
expect(thread.session?.status).toBe("error");
|
||||
expect(thread.session?.lastError).toBe("runtime exploded");
|
||||
});
|
||||
|
||||
it("maps session/thread lifecycle and tool.started into session/activity projections", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "session.started",
|
||||
eventId: asEventId("evt-session-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
message: "session started",
|
||||
});
|
||||
harness.emit({
|
||||
type: "thread.started",
|
||||
eventId: asEventId("evt-thread-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-2"),
|
||||
});
|
||||
harness.emit({
|
||||
type: "tool.started",
|
||||
eventId: asEventId("evt-tool-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-9"),
|
||||
toolKind: "other",
|
||||
title: "Read file",
|
||||
detail: "/tmp/file.ts",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session?.activeTurnId === null &&
|
||||
entry.activities.some((activity) => activity.kind === "tool.started"),
|
||||
);
|
||||
|
||||
expect(thread.session?.status).toBe("ready");
|
||||
expect(thread.activities.some((activity) => activity.kind === "tool.started")).toBe(true);
|
||||
});
|
||||
|
||||
it("continues processing runtime events after a single event handler failure", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
eventId: asEventId("evt-invalid-delta"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-invalid"),
|
||||
itemId: asItemId("item-invalid"),
|
||||
delta: undefined,
|
||||
} as unknown as ProviderRuntimeEvent);
|
||||
|
||||
harness.emit({
|
||||
type: "runtime.error",
|
||||
eventId: asEventId("evt-runtime-error-after-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-after-failure"),
|
||||
message: "runtime still processed",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.session?.status === "error" &&
|
||||
entry.session?.activeTurnId === "turn-after-failure" &&
|
||||
entry.session?.lastError === "runtime still processed",
|
||||
);
|
||||
expect(thread.session?.status).toBe("error");
|
||||
expect(thread.session?.lastError).toBe("runtime still processed");
|
||||
});
|
||||
});
|
||||
@@ -1,397 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
ProviderThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ProviderRuntimeIngestionService,
|
||||
type ProviderRuntimeIngestionShape,
|
||||
} from "../Services/ProviderRuntimeIngestion.ts";
|
||||
|
||||
const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return value === undefined ? undefined : TurnId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function truncateDetail(value: string, limit = 180): string {
|
||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||
}
|
||||
|
||||
function runtimeEventToActivities(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
switch (event.type) {
|
||||
case "approval.requested": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary:
|
||||
event.requestKind === "command"
|
||||
? "Command approval requested"
|
||||
: "File-change approval requested",
|
||||
payload: {
|
||||
requestId: event.requestId,
|
||||
requestKind: event.requestKind,
|
||||
...(event.detail ? { detail: truncateDetail(event.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "approval.resolved": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "approval",
|
||||
kind: "approval.resolved",
|
||||
summary: "Approval resolved",
|
||||
payload: {
|
||||
requestId: event.requestId,
|
||||
...(event.requestKind ? { requestKind: event.requestKind } : {}),
|
||||
...(event.decision ? { decision: event.decision } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "runtime.error": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "error",
|
||||
kind: "runtime.error",
|
||||
summary: "Runtime error",
|
||||
payload: {
|
||||
message: truncateDetail(event.message),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
},
|
||||
];
|
||||
}
|
||||
case "tool.completed": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: `${event.title} complete`,
|
||||
payload: {
|
||||
toolKind: event.toolKind,
|
||||
...(event.detail ? { detail: truncateDetail(event.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
},
|
||||
];
|
||||
}
|
||||
case "tool.started": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "tool",
|
||||
kind: "tool.started",
|
||||
summary: `${event.title} started`,
|
||||
payload: {
|
||||
toolKind: event.toolKind,
|
||||
...(event.detail ? { detail: truncateDetail(event.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
|
||||
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
|
||||
lookup: () => Effect.succeed(new Set<MessageId>()),
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (
|
||||
sessionId: ProviderSessionId,
|
||||
turnId: TurnId,
|
||||
messageId: MessageId,
|
||||
) =>
|
||||
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId)).pipe(
|
||||
Effect.flatMap((existingIds) =>
|
||||
Cache.set(
|
||||
turnMessageIdsByTurnKey,
|
||||
providerTurnKey(sessionId, turnId),
|
||||
Option.match(existingIds, {
|
||||
onNone: () => new Set([messageId]),
|
||||
onSome: (ids) => {
|
||||
const nextIds = new Set(ids);
|
||||
nextIds.add(messageId);
|
||||
return nextIds;
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const forgetAssistantMessageId = (
|
||||
sessionId: ProviderSessionId,
|
||||
turnId: TurnId,
|
||||
messageId: MessageId,
|
||||
) =>
|
||||
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId)).pipe(
|
||||
Effect.flatMap((existingIds) =>
|
||||
Option.match(existingIds, {
|
||||
onNone: () => Effect.void,
|
||||
onSome: (ids) => {
|
||||
const nextIds = new Set(ids);
|
||||
nextIds.delete(messageId);
|
||||
if (nextIds.size === 0) {
|
||||
return Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId));
|
||||
}
|
||||
return Cache.set(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId), nextIds);
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const getAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
|
||||
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId)).pipe(
|
||||
Effect.map((existingIds) =>
|
||||
Option.getOrElse(existingIds, (): Set<MessageId> => new Set<MessageId>()),
|
||||
),
|
||||
);
|
||||
|
||||
const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
|
||||
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId));
|
||||
|
||||
const clearTurnStateForSession = (sessionId: ProviderSessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const prefix = `${sessionId}:`;
|
||||
const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));
|
||||
yield* Effect.forEach(
|
||||
turnKeys,
|
||||
(key) =>
|
||||
key.startsWith(prefix) ? Cache.invalidate(turnMessageIdsByTurnKey, key) : Effect.void,
|
||||
{ concurrency: 1 },
|
||||
).pipe(Effect.asVoid);
|
||||
});
|
||||
|
||||
const processEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) return;
|
||||
|
||||
const now = event.createdAt;
|
||||
|
||||
if (
|
||||
event.type === "session.started" ||
|
||||
event.type === "session.exited" ||
|
||||
event.type === "thread.started" ||
|
||||
event.type === "turn.started" ||
|
||||
event.type === "turn.completed"
|
||||
) {
|
||||
const activeTurnId =
|
||||
event.type === "turn.started" ? (toTurnId(event.turnId) ?? null) : null;
|
||||
const providerThreadIdFromEvent =
|
||||
event.type === "thread.started"
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: event.threadId !== undefined
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: null;
|
||||
const providerThreadId =
|
||||
providerThreadIdFromEvent ?? thread.session?.providerThreadId ?? null;
|
||||
const status =
|
||||
event.type === "turn.started"
|
||||
? "running"
|
||||
: event.type === "session.exited"
|
||||
? "stopped"
|
||||
: event.type === "turn.completed" && event.status === "failed"
|
||||
? "error"
|
||||
: "ready";
|
||||
const lastError =
|
||||
event.type === "turn.completed" && event.status === "failed"
|
||||
? (event.errorMessage ?? thread.session?.lastError ?? "Turn failed")
|
||||
: status === "ready"
|
||||
? null
|
||||
: (thread.session?.lastError ?? null);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "thread-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status,
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerThreadId,
|
||||
activeTurnId,
|
||||
lastError,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
if (event.type === "message.delta" && event.delta.length > 0) {
|
||||
const assistantMessageId = MessageId.makeUnsafe(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.sessionId}`,
|
||||
);
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(event, "assistant-delta"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: event.delta,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
if (event.type === "message.completed") {
|
||||
const assistantMessageId = MessageId.makeUnsafe(`assistant:${event.itemId}`);
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
||||
}
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
commandId: providerCommandId(event, "assistant-complete"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
if (turnId) {
|
||||
yield* forgetAssistantMessageId(event.sessionId, turnId, assistantMessageId);
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
const assistantMessageIds = yield* getAssistantMessageIdsForTurn(event.sessionId, turnId);
|
||||
yield* Effect.forEach(assistantMessageIds, (assistantMessageId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
commandId: providerCommandId(event, "assistant-complete-finalize"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* clearAssistantMessageIdsForTurn(event.sessionId, turnId);
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "session.exited") {
|
||||
yield* clearTurnStateForSession(event.sessionId);
|
||||
}
|
||||
|
||||
if (event.type === "runtime.error") {
|
||||
const providerThreadId =
|
||||
event.threadId !== undefined
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: (thread.session?.providerThreadId ?? null);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "runtime-error-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status: "error",
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerThreadId,
|
||||
activeTurnId: toTurnId(event.turnId) ?? null,
|
||||
lastError: event.message,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
const activities = runtimeEventToActivities(event);
|
||||
yield* Effect.forEach(activities, (activity) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: providerCommandId(event, "thread-activity-append"),
|
||||
threadId: thread.id,
|
||||
activity,
|
||||
createdAt: activity.createdAt,
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
});
|
||||
|
||||
const processEventSafely = (event: ProviderRuntimeEvent) =>
|
||||
processEvent(event).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("provider runtime ingestion failed to process event", {
|
||||
eventId: event.eventId,
|
||||
eventType: event.type,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () {
|
||||
const providerEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
yield* Effect.addFinalizer(() => Queue.shutdown(providerEventQueue).pipe(Effect.asVoid));
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Effect.forever(Queue.take(providerEventQueue).pipe(Effect.flatMap(processEventSafely))),
|
||||
);
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(providerService.streamEvents, (event) =>
|
||||
Queue.offer(providerEventQueue, event).pipe(Effect.asVoid),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
} satisfies ProviderRuntimeIngestionShape;
|
||||
});
|
||||
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);
|
||||
@@ -1,42 +0,0 @@
|
||||
import {
|
||||
ProjectCreatedPayload as ContractsProjectCreatedPayloadSchema,
|
||||
ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
|
||||
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
|
||||
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
|
||||
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
|
||||
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
|
||||
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
|
||||
ThreadCheckpointRevertRequestedPayload as ContractsThreadCheckpointRevertRequestedPayloadSchema,
|
||||
ThreadSessionStopRequestedPayload as ContractsThreadSessionStopRequestedPayloadSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
// Server-internal alias surface, backed by contract schemas as the source of truth.
|
||||
export const ProjectCreatedPayload = ContractsProjectCreatedPayloadSchema;
|
||||
export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchema;
|
||||
export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
|
||||
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
|
||||
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
|
||||
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
|
||||
|
||||
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
|
||||
export const ThreadTurnInterruptRequestedPayload =
|
||||
ContractsThreadTurnInterruptRequestedPayloadSchema;
|
||||
export const ThreadApprovalResponseRequestedPayload =
|
||||
ContractsThreadApprovalResponseRequestedPayloadSchema;
|
||||
export const ThreadCheckpointRevertRequestedPayload =
|
||||
ContractsThreadCheckpointRevertRequestedPayloadSchema;
|
||||
export const ThreadSessionStopRequestedPayload = ContractsThreadSessionStopRequestedPayloadSchema;
|
||||
@@ -1,34 +0,0 @@
|
||||
/**
|
||||
* CheckpointReactor - Checkpoint reaction service interface.
|
||||
*
|
||||
* Owns background workers that react to orchestration checkpoint lifecycle
|
||||
* events and apply checkpoint side effects.
|
||||
*
|
||||
* @module CheckpointReactor
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
* CheckpointReactorShape - Service API for checkpoint reactor lifecycle.
|
||||
*/
|
||||
export interface CheckpointReactorShape {
|
||||
/**
|
||||
* Start the checkpoint reactor.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*
|
||||
* Consumes both orchestration-domain and provider-runtime events via an
|
||||
* internal queue.
|
||||
*/
|
||||
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CheckpointReactor - Service tag for checkpoint reactor workers.
|
||||
*/
|
||||
export class CheckpointReactor extends ServiceMap.Service<
|
||||
CheckpointReactor,
|
||||
CheckpointReactorShape
|
||||
>()("orchestration/CheckpointReactor") {}
|
||||
@@ -1,80 +0,0 @@
|
||||
/**
|
||||
* OrchestrationEngineService - Service interface for orchestration command handling.
|
||||
*
|
||||
* Owns command validation/dispatch and in-memory read-model updates backed by
|
||||
* `OrchestrationEventStore` persistence. It does not own provider process
|
||||
* management or transport concerns (e.g. websocket request parsing).
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection. Command dispatch,
|
||||
* replay, and unknown-input decoding all return typed domain errors.
|
||||
*
|
||||
* @module OrchestrationEngineService
|
||||
*/
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import type { OrchestrationEventStoreError } from "../../persistence/Errors.ts";
|
||||
|
||||
/**
|
||||
* OrchestrationEngineShape - Service API for orchestration command and event flow.
|
||||
*/
|
||||
export interface OrchestrationEngineShape {
|
||||
/**
|
||||
* Read the current in-memory orchestration read model.
|
||||
*
|
||||
* @returns Effect containing the latest read model.
|
||||
*/
|
||||
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
|
||||
|
||||
/**
|
||||
* Replay persisted orchestration events from an exclusive sequence cursor.
|
||||
*
|
||||
* @param fromSequenceExclusive - Sequence cursor (exclusive).
|
||||
* @returns Stream containing ordered events.
|
||||
*/
|
||||
readonly readEvents: (
|
||||
fromSequenceExclusive: number,
|
||||
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
|
||||
|
||||
/**
|
||||
* Dispatch a validated orchestration command.
|
||||
*
|
||||
* @param command - Valid orchestration command.
|
||||
* @returns Effect containing the sequence of the persisted event.
|
||||
*
|
||||
* Dispatch is serialized through an internal queue and deduplicated via
|
||||
* command receipts.
|
||||
*/
|
||||
readonly dispatch: (
|
||||
command: OrchestrationCommand,
|
||||
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;
|
||||
|
||||
/**
|
||||
* Stream persisted domain events in dispatch order.
|
||||
*
|
||||
* This is a hot runtime stream (new events only), not a historical replay.
|
||||
*/
|
||||
readonly streamDomainEvents: Stream.Stream<OrchestrationEvent>;
|
||||
}
|
||||
|
||||
/**
|
||||
* OrchestrationEngineService - Service tag for orchestration engine access.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const program = Effect.gen(function* () {
|
||||
* const engine = yield* OrchestrationEngineService
|
||||
* return yield* engine.getReadModel()
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export class OrchestrationEngineService extends ServiceMap.Service<
|
||||
OrchestrationEngineService,
|
||||
OrchestrationEngineShape
|
||||
>()("orchestration/Engine") {}
|
||||
@@ -1,31 +0,0 @@
|
||||
/**
|
||||
* OrchestrationReactor - Composite orchestration reactor service interface.
|
||||
*
|
||||
* Coordinates startup of orchestration runtime reactors that translate domain
|
||||
* events into downstream side effects.
|
||||
*
|
||||
* @module OrchestrationReactor
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
* OrchestrationReactorShape - Service API for orchestration reactor lifecycle.
|
||||
*/
|
||||
export interface OrchestrationReactorShape {
|
||||
/**
|
||||
* Start orchestration-side reactors for provider/runtime/checkpoint flows.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*/
|
||||
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
/**
|
||||
* OrchestrationReactor - Service tag for orchestration reactor coordination.
|
||||
*/
|
||||
export class OrchestrationReactor extends ServiceMap.Service<
|
||||
OrchestrationReactor,
|
||||
OrchestrationReactorShape
|
||||
>()("orchestration/OrchestrationReactor") {}
|
||||
@@ -1,42 +0,0 @@
|
||||
/**
|
||||
* OrchestrationProjectionPipeline - Event projection pipeline service interface.
|
||||
*
|
||||
* Coordinates projection bootstrap/replay and per-event projection updates for
|
||||
* orchestration read models.
|
||||
*
|
||||
* @module OrchestrationProjectionPipeline
|
||||
*/
|
||||
import type { OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||
|
||||
/**
|
||||
* OrchestrationProjectionPipelineShape - Service API for projection execution.
|
||||
*/
|
||||
export interface OrchestrationProjectionPipelineShape {
|
||||
/**
|
||||
* Bootstrap projections by replaying persisted events.
|
||||
*
|
||||
* Resumes each projector from its stored projection-state cursor.
|
||||
*/
|
||||
readonly bootstrap: Effect.Effect<void, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Project a single orchestration event into projection repositories.
|
||||
*
|
||||
* Projectors are executed sequentially to preserve deterministic ordering.
|
||||
*/
|
||||
readonly projectEvent: (
|
||||
event: OrchestrationEvent,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* OrchestrationProjectionPipeline - Service tag for orchestration projections.
|
||||
*/
|
||||
export class OrchestrationProjectionPipeline extends ServiceMap.Service<
|
||||
OrchestrationProjectionPipeline,
|
||||
OrchestrationProjectionPipelineShape
|
||||
>()("orchestration/ProjectionPipeline") {}
|
||||
@@ -1,34 +0,0 @@
|
||||
/**
|
||||
* ProjectionSnapshotQuery - Read-model snapshot query service interface.
|
||||
*
|
||||
* Exposes the current orchestration projection snapshot for read-only API
|
||||
* access.
|
||||
*
|
||||
* @module ProjectionSnapshotQuery
|
||||
*/
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
|
||||
|
||||
/**
|
||||
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
|
||||
*/
|
||||
export interface ProjectionSnapshotQueryShape {
|
||||
/**
|
||||
* Read the latest orchestration projection snapshot.
|
||||
*
|
||||
* Rehydrates from projection tables and derives snapshot sequence from
|
||||
* projector cursor state.
|
||||
*/
|
||||
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProjectionSnapshotQuery - Service tag for projection snapshot queries.
|
||||
*/
|
||||
export class ProjectionSnapshotQuery extends ServiceMap.Service<
|
||||
ProjectionSnapshotQuery,
|
||||
ProjectionSnapshotQueryShape
|
||||
>()("orchestration/ProjectionSnapshotQuery") {}
|
||||
@@ -1,34 +0,0 @@
|
||||
/**
|
||||
* ProviderCommandReactor - Provider command reaction service interface.
|
||||
*
|
||||
* Owns background workers that react to orchestration intent events and
|
||||
* dispatch provider-side command execution.
|
||||
*
|
||||
* @module ProviderCommandReactor
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
* ProviderCommandReactorShape - Service API for provider command reactors.
|
||||
*/
|
||||
export interface ProviderCommandReactorShape {
|
||||
/**
|
||||
* Start reacting to provider-intent orchestration domain events.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*
|
||||
* Filters orchestration domain events to provider-intent types before
|
||||
* processing.
|
||||
*/
|
||||
readonly start: Effect.Effect<void, never, Scope.Scope>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderCommandReactor - Service tag for provider command reaction workers.
|
||||
*/
|
||||
export class ProviderCommandReactor extends ServiceMap.Service<
|
||||
ProviderCommandReactor,
|
||||
ProviderCommandReactorShape
|
||||
>()("orchestration/ProviderCommandReactor") {}
|
||||
Loaded 100 of 320 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user