Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
605c74bb8c | ||
|
|
2880ef8276 | ||
|
|
05aa27a0d9 | ||
|
|
e81c2acb78 | ||
|
|
fda3073e0c | ||
|
|
7214778b64 | ||
|
|
27bd9192ad | ||
|
|
0da96d5c93 | ||
|
|
25dbfa7bc7 | ||
|
|
78b7070042 | ||
|
|
1332c488ad | ||
|
|
384878a3f1 | ||
|
|
bf9f653331 | ||
|
|
e7e289f4ba |
No files matched your search
@@ -8,8 +8,8 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
name: Lint, Typecheck, Test, Build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -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
|
||||
@@ -34,14 +29,6 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -54,14 +41,6 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
|
||||
@@ -1,350 +0,0 @@
|
||||
name: Release Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Release version (for example 1.2.3 or v1.2.3)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${{ github.event.inputs.version }}"
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- 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
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: macos-14
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: macos-15-intel
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: ubuntu-24.04
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- 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
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
CSC_LINK: ${{ secrets.CSC_LINK }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
|
||||
run: |
|
||||
args=(
|
||||
--platform "${{ matrix.platform }}"
|
||||
--target "${{ matrix.target }}"
|
||||
--arch "${{ matrix.arch }}"
|
||||
--build-version "${{ needs.preflight.outputs.version }}"
|
||||
--verbose
|
||||
)
|
||||
|
||||
has_all() {
|
||||
for value in "$@"; do
|
||||
if [[ -z "$value" ]]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
"$AZURE_CLIENT_SECRET" \
|
||||
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
|
||||
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
|
||||
echo "Windows signing enabled (Azure Trusted Signing)."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
|
||||
fi
|
||||
else
|
||||
echo "Signing disabled for ${{ matrix.platform }}."
|
||||
fi
|
||||
|
||||
bun run dist:desktop:artifact -- "${args[@]}"
|
||||
|
||||
- name: Collect release assets
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p release-publish
|
||||
|
||||
shopt -s nullglob
|
||||
for pattern in \
|
||||
"release/*.dmg" \
|
||||
"release/*.zip" \
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/latest*.yml"; do
|
||||
for file in $pattern; do
|
||||
cp "$file" release-publish/
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- 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
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: desktop-*
|
||||
merge-multiple: true
|
||||
path: release-assets
|
||||
|
||||
- name: Publish release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
make_latest: true
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
|
||||
- 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
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
let changed = false;
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
if (packageJson.version !== process.env.RELEASE_VERSION) {
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
console.log("All package.json versions already match release version.");
|
||||
}
|
||||
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
|
||||
'
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bun install
|
||||
|
||||
- name: Commit and push version bump
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
@@ -11,7 +11,3 @@ packages/*/dist
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
+1
-2
@@ -6,8 +6,7 @@
|
||||
"dist-electron",
|
||||
"node_modules",
|
||||
"bun.lock",
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts"
|
||||
"*.tsbuildinfo"
|
||||
],
|
||||
"experimentalSortPackageJson": {}
|
||||
}
|
||||
+1
-3
@@ -15,8 +15,6 @@
|
||||
"perf": "warn"
|
||||
},
|
||||
"rules": {
|
||||
"react-in-jsx-scope": "off",
|
||||
"eslint/no-shadow": "off",
|
||||
"eslint/no-await-in-loop": "off"
|
||||
"react-in-jsx-scope": "off"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
# Plan: Centralize Core Persistence in SQLite (`~/.t3/state.sqlite`)
|
||||
|
||||
## Summary
|
||||
Move durable core app state out of renderer `localStorage` and into a centralized SQLite database at `~/.t3/state.sqlite`, while keeping machine-level editable config in JSON (keybindings) and browser UX preferences in browser-scoped state by default.
|
||||
|
||||
This plan preserves existing checkpoint patch storage in Git (`refs/t3/checkpoints/...`) and adds optional checkpoint diff summaries in SQLite (parsed via `@pierre/diffs`) for fast UI metadata rendering.
|
||||
|
||||
Core migration goals:
|
||||
1. Data persistence scalability.
|
||||
2. Move as much logic and state control as possible to the server, keeping the frontend simple.
|
||||
|
||||
## Why This Revamp
|
||||
Current persistence is split across multiple stores:
|
||||
|
||||
- Renderer core state in `apps/web/src/store.ts` (`localStorage`, key `t3code:renderer-state:v7`)
|
||||
- Server project registry in `~/.t3/userdata/projects.json` (`apps/server/src/projectRegistry.ts`)
|
||||
- Provider thread event logs in `.logs/threads/*.events.ndjson` (`apps/server/src/providerManager.ts`)
|
||||
- Terminal history in `.logs/terminals/*.log` (`apps/server/src/terminalManager.ts`)
|
||||
- Keybindings in `~/.t3/keybindings.json` (`apps/server/src/keybindings.ts`)
|
||||
|
||||
This produces a split-brain model (client-local canonical thread/message state, server-local provider runtime state), weak multi-window consistency, and fragile reconnect/restart behavior.
|
||||
|
||||
## Goals
|
||||
1. Make SQLite the canonical durable store for core app entities:
|
||||
- projects
|
||||
- threads
|
||||
- messages
|
||||
- turn/checkpoint diff metadata (summary only)
|
||||
2. Keep checkpoint patch contents in Git only.
|
||||
3. Keep machine-level editable config in JSON files (keybindings), and keep browser UX preferences browser-scoped by default.
|
||||
4. Make server authoritative for durable state; client becomes a cache/subscriber.
|
||||
5. Support reliable reconnect/catch-up without `localStorage`.
|
||||
|
||||
## Non-Goals
|
||||
1. Replacing Git checkpoint storage with DB blob storage.
|
||||
2. Persisting raw terminal output into SQLite (keep file-based terminal history for now).
|
||||
3. Supporting provider implementations beyond current Codex flow in this revamp.
|
||||
4. Full event-sourcing rewrite of all UI state in v1.
|
||||
|
||||
## Data Classification and Storage Policy
|
||||
| Data class | Examples | Store | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Core durable app data | projects, threads, messages, thread metadata, turn summaries | SQLite (`~/.t3/state.sqlite`) | Canonical source of truth |
|
||||
| Checkpoint patch content | unified diff between checkpoints | Git refs (`refs/t3/checkpoints/...`) | Existing `FilesystemCheckpointStore` remains |
|
||||
| Checkpoint metadata | changed files, +/- per file, checkpoint turn mapping | SQLite | Derived from Git diff + `@pierre/diffs` |
|
||||
| Machine-level editable config | keybindings | `~/.t3/keybindings.json` | Existing behavior, stays human-editable |
|
||||
| Browser-scoped UX preferences | theme, preferred editor, last-invoked script by project | Browser storage (currently `localStorage`) | Not canonical app data; per-browser behavior |
|
||||
| Volatile runtime state | active websocket connections, in-flight turn status, pending approvals | Memory | Rebuilt from runtime/provider events |
|
||||
|
||||
## Preference Scope Clarification
|
||||
1. `project.scripts` belongs to core app data and is persisted in SQLite with the project record.
|
||||
2. `script preference` means UX memory only, specifically the current `t3code:last-invoked-script-by-project` map used to preselect/run convenience actions.
|
||||
3. Theme/editor/script-preference keys are per-browser UX and are intentionally separate from shared project/thread/message data.
|
||||
4. Runtime mode default (`full-access` vs `approval-required`) should be treated as UX preference by default unless we explicitly decide it is a machine policy.
|
||||
|
||||
## Current vs Target Architecture
|
||||
### Current (simplified)
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
|
||||
UI -->|localStorage| LS[(Browser localStorage)]
|
||||
WS --> PR[ProjectRegistry]
|
||||
PR --> PJ[projects.json]
|
||||
WS --> PM[ProviderManager]
|
||||
PM --> CASM[CodexAppServerManager]
|
||||
CASM --> C[codex app-server]
|
||||
PM --> TL[thread .ndjson logs]
|
||||
PM --> FCS[FilesystemCheckpointStore]
|
||||
FCS --> GIT[(Git refs/t3/checkpoints)]
|
||||
```
|
||||
|
||||
### Target
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[apps/web] -->|ws rpc + push| WS[apps/server/wsServer]
|
||||
WS --> PS[PersistenceService]
|
||||
PS --> DB[(~/.t3/state.sqlite)]
|
||||
WS --> CFG[Keybinding Config]
|
||||
CFG --> JSON[(~/.t3/keybindings.json)]
|
||||
UI --> BSTATE[(Browser UX prefs)]
|
||||
WS --> PM[ProviderManager]
|
||||
PM --> CASM[CodexAppServerManager]
|
||||
CASM --> C[codex app-server]
|
||||
PM --> FCS[FilesystemCheckpointStore]
|
||||
FCS --> GIT[(Git refs/t3/checkpoints)]
|
||||
PM --> PS
|
||||
PS -->|state push| WS
|
||||
```
|
||||
|
||||
Provider remains the runtime execution engine. PersistenceService becomes the durable state authority and broadcaster.
|
||||
|
||||
## Core Domain Model (SQLite)
|
||||
Use strict schema + migrations (e.g. `PRAGMA user_version` or migration table), WAL mode, and transactional writes.
|
||||
|
||||
### JSON-first (iteration-friendly) schema
|
||||
Use a document-style core table with a minimal indexed envelope. Put evolving entity fields in `data_json`.
|
||||
|
||||
1. `documents`
|
||||
- `id TEXT PRIMARY KEY`
|
||||
- examples: `project:<uuid>`, `thread:<uuid>`, `message:<uuid>`, `turn_summary:<threadId>:<turnId>`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `project` | `thread` | `message` | `turn_summary`
|
||||
- `project_id TEXT NULL`
|
||||
- `thread_id TEXT NULL`
|
||||
- `sort_key INTEGER NULL`
|
||||
- message order, thread ordering hints, summary ordering, etc.
|
||||
- `schema_version INTEGER NOT NULL DEFAULT 1`
|
||||
- `created_at TEXT NOT NULL`
|
||||
- `updated_at TEXT NOT NULL`
|
||||
- `data_json TEXT NOT NULL`
|
||||
|
||||
2. `provider_events`
|
||||
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
|
||||
- `id TEXT NOT NULL UNIQUE`
|
||||
- `session_id TEXT NOT NULL`
|
||||
- `provider TEXT NOT NULL`
|
||||
- `kind TEXT NOT NULL`
|
||||
- `method TEXT NOT NULL`
|
||||
- `thread_id TEXT NULL`
|
||||
- `turn_id TEXT NULL`
|
||||
- `item_id TEXT NULL`
|
||||
- `request_id TEXT NULL`
|
||||
- `request_kind TEXT NULL`
|
||||
- `text_delta TEXT NULL`
|
||||
- `message TEXT NULL`
|
||||
- `payload_json TEXT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
|
||||
3. `state_events`
|
||||
- `seq INTEGER PRIMARY KEY AUTOINCREMENT`
|
||||
- `event_type TEXT NOT NULL` (e.g. `project.upsert`, `thread.delete`, `message.upsert`)
|
||||
- `entity_id TEXT NOT NULL`
|
||||
- `payload_json TEXT NOT NULL`
|
||||
- `created_at TEXT NOT NULL`
|
||||
|
||||
4. `metadata`
|
||||
- `key TEXT PRIMARY KEY`
|
||||
- `value_json TEXT NOT NULL`
|
||||
- for one-time migrations/import markers
|
||||
|
||||
### Envelope indexes
|
||||
- `documents(kind)`
|
||||
- `documents(project_id, kind)`
|
||||
- `documents(thread_id, kind, sort_key)`
|
||||
- `documents(kind, updated_at DESC)`
|
||||
- `provider_events(session_id, seq)`
|
||||
- `provider_events(thread_id, seq)`
|
||||
- `state_events(seq)`
|
||||
|
||||
### Document conventions
|
||||
1. Validate each `kind` with Zod before writes and after reads.
|
||||
2. Keep envelope fields stable (`kind`, `project_id`, `thread_id`, `sort_key`) for fast list/filter queries.
|
||||
3. Put fast-changing/evolving structure in `data_json`:
|
||||
- project: name/cwd/model/expanded/scripts
|
||||
- thread: title/model/codex thread id/terminal layout/branch/worktree
|
||||
- message: role/text/attachments/streaming/provider ids
|
||||
- turn_summary: completed/status/checkpoint turn count/file +/- summary
|
||||
4. Use `schema_version` per document to support incremental document migrations without global table churn.
|
||||
|
||||
### Normalization runway (later, optional)
|
||||
When model shapes stabilize, we can materialize normalized tables from `documents` without changing the external protocol:
|
||||
1. Add typed read models (`projects_v2`, `messages_v2`, etc.).
|
||||
2. Backfill from `documents`.
|
||||
3. Switch read paths gradually.
|
||||
|
||||
## Streaming Protocol and Synchronization
|
||||
Keep current WS request/response envelope and push model. Extend with state snapshot + patch stream.
|
||||
|
||||
### New/extended WS methods
|
||||
1. `state.bootstrap`
|
||||
- returns complete durable snapshot for initial render:
|
||||
- projects (+scripts)
|
||||
- threads (+terminal metadata + turn summaries)
|
||||
- messages (+attachments), optionally capped per thread then paged
|
||||
- `lastStateSeq`
|
||||
|
||||
2. `state.listMessages` (paged)
|
||||
- for large threads and virtualized history
|
||||
|
||||
3. `threads.create`
|
||||
4. `threads.update`
|
||||
5. `threads.delete`
|
||||
6. `threads.markVisited`
|
||||
7. `threads.updateTerminalState`
|
||||
8. `threads.updateModel`
|
||||
9. `threads.updateTitle`
|
||||
|
||||
10. `state.catchUp`
|
||||
- input: `afterSeq`
|
||||
- returns ordered `state_events` for reconnect recovery
|
||||
|
||||
Existing `projects.*`, `providers.*`, `terminal.*`, `git.*`, `server.*` remain; they route through persistence-aware services.
|
||||
|
||||
### Push channels
|
||||
1. Keep `providers.event` for raw runtime/provider telemetry.
|
||||
2. Add `state.event` for canonical persisted mutations (`seq` ordered).
|
||||
3. Keep `terminal.event` and `server.welcome`.
|
||||
|
||||
### Ordering guarantees
|
||||
- Every durable mutation writes `state_events` in the same DB transaction as row changes.
|
||||
- Server broadcasts `state.event` after commit.
|
||||
- Clients apply events strictly by `seq`.
|
||||
- Reconnect uses `state.catchUp(afterSeq)` to fill gaps.
|
||||
|
||||
## Core App Flows
|
||||
### 1) Startup + hydration
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Web Client
|
||||
participant WS as wsServer
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
|
||||
UI->>WS: connect websocket
|
||||
WS-->>UI: push server.welcome
|
||||
UI->>WS: state.bootstrap()
|
||||
WS->>PS: loadSnapshot()
|
||||
PS->>DB: SELECT projects/threads/messages/metadata
|
||||
DB-->>PS: snapshot + lastStateSeq
|
||||
PS-->>WS: bootstrap payload
|
||||
WS-->>UI: response(snapshot)
|
||||
UI->>WS: subscribe state.event/providers.event
|
||||
```
|
||||
|
||||
### 2) Create thread
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI
|
||||
participant WS
|
||||
participant PS
|
||||
participant DB
|
||||
|
||||
UI->>WS: threads.create(projectId, model, title, branch,...)
|
||||
WS->>PS: createThread(...)
|
||||
PS->>DB: INSERT thread + terminal defaults + state_event
|
||||
DB-->>PS: committed row + seq
|
||||
PS-->>WS: thread
|
||||
WS-->>UI: response(thread)
|
||||
WS-->>UI: push state.event(thread.upsert, seq)
|
||||
```
|
||||
|
||||
### 3) Send turn + stream + persist
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI
|
||||
participant WS
|
||||
participant PM as ProviderManager
|
||||
participant CASM as CodexAppServerManager
|
||||
participant Codex as codex app-server
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
|
||||
UI->>WS: providers.startSession(threadId, resumeThreadId?)
|
||||
WS->>PM: startSession(...)
|
||||
PM->>CASM: thread/start or thread/resume
|
||||
CASM->>Codex: JSON-RPC
|
||||
Codex-->>CASM: notifications/events
|
||||
CASM-->>PM: ProviderEvent
|
||||
PM-->>PS: ingestProviderEvent(event)
|
||||
PS->>DB: INSERT provider_events + projection updates + state_event
|
||||
DB-->>PS: seq
|
||||
PM-->>WS: provider event
|
||||
WS-->>UI: push providers.event
|
||||
WS-->>UI: push state.event
|
||||
|
||||
UI->>WS: providers.sendTurn(sessionId, input, attachments)
|
||||
WS->>PM: sendTurn(...)
|
||||
PM->>CASM: turn/start
|
||||
CASM->>Codex: JSON-RPC
|
||||
```
|
||||
|
||||
### 4) Checkpoint capture + diff summary
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant PM as ProviderManager
|
||||
participant FCS as FilesystemCheckpointStore
|
||||
participant G as Git refs/t3/checkpoints
|
||||
participant PS as PersistenceService
|
||||
participant DB as SQLite
|
||||
participant WS as wsServer
|
||||
participant UI as Web Client
|
||||
|
||||
PM->>FCS: captureCheckpoint(threadId, turnCount)
|
||||
FCS->>G: update-ref refs/t3/checkpoints/...
|
||||
PM->>FCS: diffCheckpoints(turnCount-1, turnCount)
|
||||
FCS-->>PM: unified patch
|
||||
PM->>PS: persistTurnDiffSummary(turnId, patch)
|
||||
PS->>PS: parse patch with @pierre/diffs
|
||||
PS->>DB: upsert thread_turn_summaries + thread_turn_diff_files + state_event
|
||||
DB-->>PS: seq
|
||||
PS-->>WS: state.event(turn summary upsert)
|
||||
WS-->>UI: push state.event
|
||||
```
|
||||
|
||||
## Provider Role in the New Model
|
||||
Provider components are unchanged in purpose, but persistence boundaries become explicit:
|
||||
|
||||
1. `CodexAppServerManager`
|
||||
- runtime bridge to `codex app-server`
|
||||
- emits provider events
|
||||
- no direct durability ownership
|
||||
|
||||
2. `ProviderManager`
|
||||
- session lifecycle + checkpoint orchestration
|
||||
- forwards provider events to:
|
||||
- websocket push (`providers.event`)
|
||||
- persistence projection (`PersistenceService`)
|
||||
|
||||
3. `PersistenceService` (new)
|
||||
- canonicalizes thread/message state
|
||||
- stores provider event log
|
||||
- stores turn summary metadata
|
||||
- emits `state.event` patches
|
||||
|
||||
This cleanly separates runtime execution concerns from durable conversation state.
|
||||
|
||||
## Client Data Flow (Server -> Client)
|
||||
### Current issue
|
||||
- Web client computes and persists canonical messages/thread state locally (`reducer`, `applyEventToMessages`, `deriveTurnDiffSummaries`), so reconnect and multi-window consistency rely on localStorage.
|
||||
|
||||
### New flow
|
||||
1. Client bootstraps from server (`state.bootstrap`) instead of localStorage hydration.
|
||||
2. Client uses `state.event` as authoritative mutation stream.
|
||||
3. Client may still use optimistic UI for latency, but server-issued canonical IDs/rows win.
|
||||
4. `providers.event` remains for live UX details (in-progress deltas, approvals, lifecycle).
|
||||
|
||||
## Migration Plan
|
||||
### A) Server-side source migrations
|
||||
1. Introduce DB migration runner.
|
||||
2. On startup, import `projects.json` into SQLite if present and not yet imported.
|
||||
3. Preserve `projects.json` as backup:
|
||||
- rename to `projects.json.bak.<timestamp>`
|
||||
4. Keep keybindings migration path untouched (`~/.t3/keybindings.json` remains canonical).
|
||||
|
||||
### B) Client-side legacy state migration
|
||||
1. Detect legacy localStorage keys:
|
||||
- `t3code:renderer-state:v7` and legacy list in `apps/web/src/store.ts`
|
||||
2. Add one-time method `state.importLegacyRendererState(payload)`.
|
||||
3. Server validates and sanitizes payload with shared schema (port from `apps/web/src/persistenceSchema.ts` to contracts/server module).
|
||||
4. Server upserts projects/threads/messages/terminal metadata into SQLite.
|
||||
5. Server writes `metadata` marker to prevent duplicate imports.
|
||||
6. Client clears legacy localStorage keys after successful import.
|
||||
|
||||
### C) Browser UX preference boundary
|
||||
Default behavior: keep these browser-scoped and do not move them into SQLite or `~/.t3/*.json`:
|
||||
- `t3code:theme`
|
||||
- `t3code:last-editor`
|
||||
- `t3code:last-invoked-script-by-project`
|
||||
|
||||
Optional future mode (not required for this revamp):
|
||||
- Add server-backed preferences storage for users who want zero browser persistence.
|
||||
|
||||
## Implementation Phases
|
||||
### Phase 0: Foundation
|
||||
1. Add SQLite dependency and persistence modules:
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- `apps/server/src/stateMigrations.ts`
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
2. Add migration boot in `apps/server/src/index.ts`.
|
||||
3. Update default state path to `~/.t3/state.sqlite` (with env override).
|
||||
|
||||
### Phase 1: Document store cut-in (projects + threads first)
|
||||
1. Replace `ProjectRegistry` JSON backend with DB-backed document repository.
|
||||
2. Add `threads.*` methods to server routes.
|
||||
3. Keep web reducer but stop writing to localStorage for these entities.
|
||||
|
||||
### Phase 2: Message + turn document persistence
|
||||
1. Ingest provider events into DB (`provider_events`).
|
||||
2. Project events into `documents` rows for `message` and `turn_summary` kinds.
|
||||
3. Add `state.event` push and `state.catchUp`.
|
||||
|
||||
### Phase 3: Web client cutover
|
||||
1. Replace `readPersistedState()` boot path with `state.bootstrap`.
|
||||
2. Remove `persistState()` localStorage writes for core state.
|
||||
3. Keep only in-memory reducer/cache for volatile UI fields.
|
||||
|
||||
### Phase 4: Preference boundary hardening
|
||||
1. Keep `~/.t3/keybindings.json` as the only required JSON config in this revamp.
|
||||
2. Keep `theme` / `last-editor` / `last-invoked-script-by-project` browser-scoped (explicitly non-canonical).
|
||||
3. Ensure no core entity (`projects`, `threads`, `messages`, turn summaries) is read from or written to browser storage.
|
||||
|
||||
### Phase 5: Cleanup + compatibility
|
||||
1. Remove deprecated localStorage/persistence schema paths once migration is stable.
|
||||
2. Keep temporary migration fallback for one release window.
|
||||
3. (Optional) add a follow-up normalization milestone when schemas settle.
|
||||
|
||||
## Streaming/Projection Design Notes
|
||||
1. Durable append:
|
||||
- always append raw provider events first.
|
||||
2. Projection:
|
||||
- update message/thread projections in the same transaction when practical.
|
||||
- if expensive, queue projection jobs but keep deterministic ordering by provider event `seq`.
|
||||
3. Backpressure:
|
||||
- avoid heavyweight diff parsing on hot delta path.
|
||||
- compute checkpoint diff summaries only on checkpoint/turn completion.
|
||||
|
||||
## Reliability and Performance Settings
|
||||
1. SQLite pragmas:
|
||||
- `journal_mode=WAL`
|
||||
- `synchronous=FULL` (or `NORMAL` only if validated under load)
|
||||
- `busy_timeout=5000`
|
||||
- `foreign_keys=ON`
|
||||
2. Prepared statements for hot paths.
|
||||
3. Batch/paginate message retrieval for large threads.
|
||||
4. Add caps/retention for `provider_events` if DB growth becomes material.
|
||||
|
||||
## Testing Plan
|
||||
Backend changes require new tests and runtime validation.
|
||||
|
||||
### Unit tests
|
||||
1. DB schema + migrations
|
||||
2. Document repository CRUD (`project`/`thread`/`message`/`turn_summary`)
|
||||
3. Provider event projection logic
|
||||
4. Checkpoint summary parser (`@pierre/diffs` integration and malformed diff fallback)
|
||||
5. Keybindings JSON behavior remains unchanged (read/write + malformed-file handling)
|
||||
|
||||
### Integration tests (`wsServer`)
|
||||
1. `state.bootstrap` returns canonical snapshot
|
||||
2. `state.event` emits ordered `seq`
|
||||
3. reconnect + `state.catchUp` replays missing events
|
||||
4. `providers.event` + `state.event` coherence on a streamed turn
|
||||
5. localStorage import endpoint idempotence
|
||||
|
||||
### Migration tests
|
||||
1. `projects.json` import -> DB rows
|
||||
2. localStorage v7 import -> DB rows
|
||||
3. legacy payload rejection safety
|
||||
|
||||
### Frontend tests
|
||||
1. store boot without localStorage core snapshot
|
||||
2. reducer handling of `state.event` patches
|
||||
3. fallback behavior when server unavailable
|
||||
|
||||
## Risks and Mitigations
|
||||
1. Risk: Split writes between provider stream and DB create race conditions.
|
||||
- Mitigation: single persistence ingestion queue per session/thread, transactional writes, monotonic `seq`.
|
||||
2. Risk: Message duplication with optimistic UI.
|
||||
- Mitigation: client-supplied message IDs echoed by server; idempotent upserts.
|
||||
3. Risk: DB write amplification on text deltas.
|
||||
- Mitigation: append-only provider event log + projection throttling/finalization.
|
||||
4. Risk: migration corruption from malformed local data.
|
||||
- Mitigation: strict schema validation + partial-row rejection + migration markers + backups.
|
||||
5. Risk: checkpoint summary parsing overhead.
|
||||
- Mitigation: parse only finalized checkpoint ranges and fallback to lightweight stat extraction.
|
||||
6. Risk: JSON shape drift across fast iterations.
|
||||
- Mitigation: per-kind Zod schemas + `schema_version` in documents + migration tests for older payloads.
|
||||
|
||||
## Done Criteria
|
||||
1. No core durable app data depends on renderer localStorage.
|
||||
2. Projects/threads/messages/turn summaries persist in `~/.t3/state.sqlite` via JSON-first documents.
|
||||
3. Checkpoint patch content remains Git-backed; optional summaries are in DB.
|
||||
4. Keybindings remain JSON-backed at `~/.t3/keybindings.json`.
|
||||
5. Theme/editor/last-invoked-script remain browser-scoped (or explicitly migrated in a separate opt-in feature).
|
||||
6. App reload/reconnect reconstructs state from server snapshot + event catch-up.
|
||||
7. Lint/typecheck/tests pass across server/web/contracts.
|
||||
|
||||
## Concrete File Impact (Expected)
|
||||
### Server
|
||||
- `apps/server/src/index.ts` (state db path + bootstrap)
|
||||
- `apps/server/src/wsServer.ts` (new state/thread routes + push channel)
|
||||
- `apps/server/src/providerManager.ts` (persist event hooks + checkpoint summary writes)
|
||||
- `apps/server/src/projectRegistry.ts` (replace or wrap with document-backed repo)
|
||||
- new persistence modules (`stateDb`, migrations, document repository, persistence service)
|
||||
|
||||
### Web
|
||||
- `apps/web/src/store.ts` (remove localStorage core persistence)
|
||||
- `apps/web/src/persistenceSchema.ts` (migration-only use then eventual removal)
|
||||
- `apps/web/src/routes/__root.tsx` (state bootstrap and catch-up wiring)
|
||||
- `apps/web/src/wsNativeApi.ts` / contracts (new methods/channels)
|
||||
- preference callsites remain browser-scoped by default (`useTheme`, editor/script preference keys)
|
||||
|
||||
### Contracts
|
||||
- `packages/contracts/src/ws.ts` (new methods/channels)
|
||||
- `packages/contracts/src/ipc.ts` (new NativeApi sections for state/threads)
|
||||
- new schemas for thread/message/state-event payloads
|
||||
|
||||
## Open Questions
|
||||
1. Should runtime mode (`full-access` vs `approval-required`) remain browser-scoped UX state, or be elevated to machine policy?
|
||||
2. Should terminal panel layout/state be in SQLite (shared) or stay browser-scoped UX state?
|
||||
3. Do we need provider event retention limits from day one?
|
||||
4. Do we keep `.logs/threads/*.events.ndjson` as debug mirror after DB event log is live?
|
||||
5. For non-desktop/browser mode, should state still centralize to `~/.t3/state.sqlite` or support workspace-local override by default?
|
||||
@@ -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.
|
||||
@@ -0,0 +1,179 @@
|
||||
# Plan: Remove Legacy localStorage Migration Paths and Resolve CR Feedback Cohesively
|
||||
|
||||
## Summary
|
||||
Delete all runtime migration pathways that ingest legacy browser localStorage state into the new SQLite-backed model, then resolve the remaining code review (CR) findings in grouped workstreams.
|
||||
|
||||
This plan intentionally removes migration code instead of improving it. The target is a single canonical state flow: server-backed bootstrap + state events only, with no legacy data import bridge.
|
||||
|
||||
## Goals
|
||||
1. Remove legacy localStorage migration for renderer state completely.
|
||||
2. Remove dead contracts, RPC methods, server handlers, client callers, and tests tied to that migration.
|
||||
3. Resolve valid CR findings on the retained architecture.
|
||||
4. Close review threads with explicit outcomes: fixed, superseded by deletion, or declined with rationale.
|
||||
|
||||
## Non-Goals
|
||||
1. Preserving one-time automatic import of old renderer localStorage data.
|
||||
2. Refactoring unrelated UX persistence (theme/editor preferences) unless directly required by CR items.
|
||||
3. Large behavior changes outside correctness/reliability fixes raised in CR.
|
||||
|
||||
## Architecture Decision
|
||||
- Canonical state source remains SQLite + `state.bootstrap` + `state.catchUp` + streamed `stateEvent` updates.
|
||||
- Legacy renderer-state migration is removed entirely.
|
||||
- Existing server-side `projects.json` import path is kept unless explicitly removed in a follow-up (it is not localStorage-based).
|
||||
|
||||
## Workstream 1: Delete Legacy localStorage Migration End-to-End [COMPLETE]
|
||||
|
||||
### 1.1 Contracts and WS protocol cleanup
|
||||
- Remove `stateImportLegacyRendererState` from `packages/contracts/src/ws.ts`.
|
||||
- Remove state import input/result schemas and exported types from `packages/contracts/src/state.ts`.
|
||||
- Remove IPC surface for `state.importLegacyRendererState` in `packages/contracts/src/ipc.ts`.
|
||||
- Update and prune contracts tests in `packages/contracts/src/state.test.ts` and any IPC/WS tests that reference removed symbols.
|
||||
|
||||
### 1.2 Server cleanup
|
||||
- Remove `PersistenceService.importLegacyRendererState(...)` and associated metadata key/constants used only for this import path.
|
||||
- Remove WS routing case for `WS_METHODS.stateImportLegacyRendererState` in `apps/server/src/wsServer.ts`.
|
||||
- Remove server tests that exercise legacy renderer import via RPC and service unit tests.
|
||||
- Ensure no dead helpers remain (payload mapping, metadata flags, schema imports, etc.).
|
||||
|
||||
### 1.3 Web client cleanup
|
||||
- Remove legacy key constants and helper functions from `apps/web/src/routes/__root.tsx`:
|
||||
- `CURRENT_RENDERER_STATE_KEY`
|
||||
- `LEGACY_RENDERER_STATE_KEYS`
|
||||
- `readLegacyRendererImportPayload`
|
||||
- `clearLegacyRendererState`
|
||||
- import-and-refresh bootstrap branch invoking `api.state.importLegacyRendererState(...)`
|
||||
- Remove `hydratePersistedState` dependency from root route.
|
||||
- Delete or narrow `apps/web/src/persistenceSchema.ts` to only what is still used. If unused after migration removal, delete file and tests.
|
||||
- Remove `state.importLegacyRendererState` call path from `apps/web/src/wsNativeApi.ts`.
|
||||
|
||||
### 1.4 Dead-code verification pass
|
||||
- `rg` for: `importLegacyRendererState`, `stateImportLegacyRendererState`, `renderer-state:v`, `hydratePersistedState`, legacy metadata keys.
|
||||
- Ensure zero references remain in app code, contracts, and tests.
|
||||
|
||||
## Workstream 2: Resolve CR Findings in Surviving Code (Grouped by Relevance) [COMPLETE]
|
||||
|
||||
### Group A: Data integrity and transactional correctness (highest priority)
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
- Fix `listMessages` pagination progress: use fetched row count for `nextOffset`.
|
||||
- Guard `withTransaction` post-commit event emission so listener exceptions do not surface as transaction failures.
|
||||
- Preserve `checkpointTurnCount = 0` in turn-summary merge logic.
|
||||
- Prevent `item/started` from clobbering previously accumulated assistant text when events arrive out of order.
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- Wrap/contain `applyCheckpointRevert` persistence update so provider revert success is not falsely returned as failure.
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- Close DB when migration initialization fails in constructor.
|
||||
- Preserve original transaction error if rollback also throws.
|
||||
|
||||
### Group B: API/contract clarity and ownership boundaries
|
||||
- `apps/server/src/wsServer.ts` + `packages/contracts/src/ipc.ts` + `apps/web/src/wsNativeApi.ts`
|
||||
- Remove ambiguous generic `threads.update` or make it explicit/unsupported (single canonical terminal-state update route).
|
||||
- Align method names/types with actual handlers.
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- Track ownership of injected `persistenceService`; only close internally owned instance in `stop()`.
|
||||
- `apps/server/src/sqliteAdapter.ts`
|
||||
- Add explicit guard/error message when `node:sqlite` is unavailable.
|
||||
|
||||
### Group C: Client consistency and race prevention
|
||||
- `apps/web/src/appSettings.ts`
|
||||
- Add hydration/update sequence guard so hydration cannot overwrite optimistic writes.
|
||||
- `apps/web/src/store.ts`
|
||||
- Harden `thread.upsert` normalization to avoid crashes on missing terminal arrays (safe defaults before terminal normalization).
|
||||
- `apps/web/src/components/Sidebar.tsx`
|
||||
- Fix no-API thread creation path (do not call API-gated `handleNewThread` in browser-only fallback).
|
||||
- `apps/web/src/components/BranchToolbar.tsx` + `apps/web/src/components/ChatView.tsx`
|
||||
- Remove duplicate `updateBranch` network write path.
|
||||
|
||||
### Group D: Test reliability and cleanup
|
||||
- `apps/server/src/persistenceService.test.ts`
|
||||
- Make timestamp helper deterministic.
|
||||
- Ensure service instances are always closed via `try/finally`.
|
||||
- Replace always-true catch-up sequence assertion with monotonic/defined sequence checks.
|
||||
- Update/add tests for Group A/B/C behavior changes.
|
||||
|
||||
## Workstream 3: Review Thread Triage/Closure Strategy [COMPLETE]
|
||||
|
||||
### Threads closed by deletion (Workstream 1)
|
||||
- Legacy renderer import flow/race concerns in root route.
|
||||
- Legacy import schemas, WS method concerns, and related service import concerns.
|
||||
- Any CR comments rooted in the removed migration path.
|
||||
|
||||
### Threads closed by fixes (Workstream 2)
|
||||
- Transaction semantics, pagination correctness, branch update duplication, no-API thread creation, etc.
|
||||
|
||||
### Threads closed with rationale (no change)
|
||||
- Keep concise “not adopted” notes only where behavior is intentional and safe.
|
||||
|
||||
### Disposition Matrix (Ready for PR Thread Closure)
|
||||
- `superseded-by-deletion`
|
||||
- Legacy renderer-state import path comments (root-route import race, legacy import RPC/schema/service concerns).
|
||||
- Rationale: Workstream 1 deleted the entire runtime migration pathway and removed related contracts/callers/handlers.
|
||||
- `fixed`
|
||||
- `listMessages` pagination progress now advances by fetched row count.
|
||||
- `withTransaction` post-commit event emission no longer surfaces listener exceptions as write failures.
|
||||
- `checkpointTurnCount = 0` is preserved in summary merge logic.
|
||||
- Out-of-order `item/started` no longer clobbers accumulated assistant text.
|
||||
- Provider checkpoint revert no longer returns failure when persistence follow-up write fails.
|
||||
- Generic `threads.update` is explicitly unsupported; canonical path is `threads.updateTerminalState`.
|
||||
- `wsServer.stop()` now closes persistence only when internally owned.
|
||||
- `StateDb` closes DB on migration failure and preserves original transaction error if rollback also fails.
|
||||
- `sqliteAdapter` now emits explicit guidance when `node:sqlite` is unavailable.
|
||||
- `appSettings` hydration now guards against overwriting optimistic writes.
|
||||
- `thread.upsert` reducer path now safely defaults missing terminal arrays.
|
||||
- Sidebar no-API fallback now creates a local thread.
|
||||
- Duplicate `updateBranch` write path removed from `BranchToolbar`; canonical write remains in `ChatView` effect.
|
||||
- `declined-with-rationale`
|
||||
- None in this workstream. No remaining high/medium CR findings required intentional non-adoption.
|
||||
|
||||
### Evidence Anchors for Thread Replies
|
||||
- Server behavior fixes:
|
||||
- `apps/server/src/persistenceService.ts`
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- `apps/server/src/stateDb.ts`
|
||||
- `apps/server/src/sqliteAdapter.ts`
|
||||
- Web/contracts fixes:
|
||||
- `packages/contracts/src/ws.ts`
|
||||
- `packages/contracts/src/ipc.ts`
|
||||
- `apps/web/src/wsNativeApi.ts`
|
||||
- `apps/web/src/appSettings.ts`
|
||||
- `apps/web/src/store.ts`
|
||||
- `apps/web/src/components/Sidebar.tsx`
|
||||
- `apps/web/src/components/BranchToolbar.tsx`
|
||||
- Regression coverage:
|
||||
- `apps/server/src/persistenceService.test.ts`
|
||||
- `apps/server/src/wsServer.test.ts`
|
||||
- `apps/server/src/stateDb.test.ts`
|
||||
- `apps/server/src/sqliteAdapter.test.ts`
|
||||
- `apps/web/src/appSettings.test.ts`
|
||||
- `apps/web/src/store.test.ts`
|
||||
- `apps/web/src/components/Sidebar.logic.test.ts`
|
||||
- `packages/contracts/src/ws.test.ts`
|
||||
|
||||
### Suggested Reply Templates
|
||||
- `superseded-by-deletion`: "Superseded by Workstream 1 removal of legacy renderer-state migration path; related RPC/schema/client callsites were deleted."
|
||||
- `fixed`: "Fixed in Workstream 2 with tests added; see referenced file(s) and regression coverage."
|
||||
- `declined-with-rationale`: "Intentional behavior retained; safe by design and documented here with rationale and test coverage."
|
||||
|
||||
## Execution Order
|
||||
1. Contracts + protocol deletions (Workstream 1.1).
|
||||
2. Server deletion and compilation fixes (Workstream 1.2).
|
||||
3. Web deletion and compilation fixes (Workstream 1.3).
|
||||
4. Dead-code sweep and test pruning (Workstream 1.4).
|
||||
5. Group A fixes + tests.
|
||||
6. Group B fixes + tests.
|
||||
7. Group C fixes + tests.
|
||||
8. Group D test hardening.
|
||||
9. Final lint/test pass; prepare review-thread response mapping.
|
||||
|
||||
## Validation Matrix
|
||||
- Lint: `bun run lint`.
|
||||
- Contracts tests: `bun --cwd packages/contracts test` (or workspace equivalent).
|
||||
- Server tests (required for backend changes): `bun --cwd apps/server test`.
|
||||
- Web tests: `bun --cwd apps/web test`.
|
||||
- Grep-based dead-code validation for removed migration symbols.
|
||||
|
||||
## Done Criteria
|
||||
1. No runtime path exists to import legacy renderer localStorage into server state.
|
||||
2. No dead symbols remain for removed migration APIs.
|
||||
3. CR high/medium validity issues in retained code are fixed or explicitly dispositioned.
|
||||
4. Backend tests and project lint pass.
|
||||
5. PR discussion can be answered thread-by-thread with: fixed / superseded / intentionally declined.
|
||||
@@ -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,327 +0,0 @@
|
||||
# Plan: Cursor ACP (`agent acp`) Provider Integration
|
||||
|
||||
## Goal
|
||||
|
||||
Add Cursor as a first-class provider in T3 Code using ACP (`agent acp`) over JSON-RPC 2.0 stdio, with robust session lifecycle handling and canonical `ProviderRuntimeEvent` projection.
|
||||
|
||||
---
|
||||
|
||||
## 1) Exploration Findings (from live ACP probes)
|
||||
|
||||
### 1.1 Core invocation and transport
|
||||
|
||||
1. Binary is `agent` on PATH (`2026.02.27-e7d2ef6` observed).
|
||||
2. ACP server command is `agent acp`.
|
||||
3. Transport is newline-delimited JSON-RPC 2.0 over stdio.
|
||||
4. Messages:
|
||||
- client -> server: requests and responses to server-initiated requests
|
||||
- server -> client: responses, notifications (`session/update`), and server requests (`session/request_permission`)
|
||||
|
||||
### 1.2 Handshake and session calls observed
|
||||
|
||||
1. `initialize` returns:
|
||||
- `protocolVersion`
|
||||
- `agentCapabilities` (`loadSession`, `mcpCapabilities`, `promptCapabilities`)
|
||||
- `authMethods` (includes `cursor_login`)
|
||||
2. `authenticate { methodId: "cursor_login" }` returns `{}` when logged in.
|
||||
3. `session/new` returns:
|
||||
- `sessionId`
|
||||
- `modes` (`agent`, `plan`, `ask`)
|
||||
4. `session/load` works and requires `sessionId`, `cwd`, `mcpServers`.
|
||||
5. `session/prompt` returns terminal response `{ stopReason: "end_turn" | "cancelled" }`.
|
||||
|
||||
Important sequence note:
|
||||
1. ACP currently allows `session/new` even without explicit `initialize`/`authenticate` when local auth already exists.
|
||||
2. For adapter consistency and forward compatibility, we should still send `initialize` and `authenticate` during startup.
|
||||
|
||||
### 1.3 `session/update` event families observed
|
||||
|
||||
Observed `params.update.sessionUpdate` values:
|
||||
|
||||
1. `available_commands_update`
|
||||
2. `agent_thought_chunk`
|
||||
3. `agent_message_chunk`
|
||||
4. `tool_call`
|
||||
5. `tool_call_update`
|
||||
|
||||
Observed payload behavior:
|
||||
|
||||
1. `agent_*_chunk` provides `content: { type: "text", text: string }`.
|
||||
2. `tool_call` may be emitted multiple times for same `toolCallId`:
|
||||
- initial generic form (`title: "Terminal"`, `rawInput: {}`)
|
||||
- enriched form (`title: "\`pwd\`"`, `rawInput: { command: "pwd" }`)
|
||||
3. `tool_call_update` statuses observed:
|
||||
- `in_progress`
|
||||
- `completed`
|
||||
4. `tool_call_update` on completion may include `rawOutput`:
|
||||
- terminal: `{ exitCode, stdout, stderr }`
|
||||
- search/find: `{ totalFiles, truncated }`
|
||||
|
||||
### 1.4 Permission flow observed
|
||||
|
||||
1. ACP server sends `session/request_permission` (JSON-RPC request with `id`).
|
||||
2. Request shape includes:
|
||||
- `params.sessionId`
|
||||
- `params.toolCall`
|
||||
- `params.options` (`allow-once`, `allow-always`, `reject-once`)
|
||||
3. Client must respond on same `id` with:
|
||||
- `{ outcome: { outcome: "selected", optionId: "<one-option-id>" } }`
|
||||
4. Reject path still results in tool lifecycle completion events (`tool_call_update status: completed`), typically without `rawOutput`.
|
||||
|
||||
### 1.5 Error and capability quirks
|
||||
|
||||
1. `session/cancel` currently returns:
|
||||
- JSON-RPC error `-32601` Method not found
|
||||
2. Error shape examples:
|
||||
- unknown auth method: `-32602`
|
||||
- `session/load` missing/invalid params: `-32602`
|
||||
- `session/prompt` unknown session: `-32603` with details
|
||||
3. Parallel prompts on same session are effectively single-flight:
|
||||
- second prompt can cause first to complete with `stopReason: "cancelled"`.
|
||||
4. `session/new` accepts a `model` field (no explicit echo in response).
|
||||
|
||||
Probe artifacts:
|
||||
1. `.tmp/acp-probe/*/transcript.ndjson`
|
||||
2. `.tmp/acp-probe/*/summary.json`
|
||||
3. `scripts/cursor-acp-probe.mjs`
|
||||
|
||||
---
|
||||
|
||||
## 2) Integration Constraints for T3
|
||||
|
||||
1. T3 adapter contract still requires:
|
||||
- `startSession`, `sendTurn`, `interruptTurn`, `respondToRequest`, `readThread`, `rollbackThread`, `stopSession`, `listSessions`, `hasSession`, `stopAll`, `streamEvents`.
|
||||
2. Orchestration consumes canonical `ProviderRuntimeEvent` only.
|
||||
3. `ProviderCommandReactor` provider precedence fix remains required (respect explicit provider on turn start).
|
||||
4. ACP now supports external permission decisions, so Cursor can participate in T3 approval UX via adapter-managed request/response plumbing.
|
||||
|
||||
---
|
||||
|
||||
## 3) Proposed Architecture
|
||||
|
||||
### 3.1 New server components
|
||||
|
||||
1. `apps/server/src/provider/Services/CursorAdapter.ts` (service contract/tag + ACP event schemas).
|
||||
2. `apps/server/src/provider/Layers/CursorAdapter.ts` (single implementation unit; owns ACP process lifecycle, JSON-RPC routing, runtime projection).
|
||||
3. No manager indirection; keep logic in layer implementation.
|
||||
|
||||
### 3.2 Session model
|
||||
|
||||
1. One long-lived ACP child process per T3 Cursor provider session.
|
||||
2. Track:
|
||||
- `providerSessionId` (T3 synthetic ID)
|
||||
- `acpSessionId` (from `session/new` or restored via `session/load`)
|
||||
- `cwd`, `model`, in-flight turn state
|
||||
- pending permission requests by JSON-RPC request id
|
||||
3. Resume support:
|
||||
- persist `acpSessionId` in provider resume metadata and call `session/load` on reattach.
|
||||
|
||||
### 3.3 Command strategy
|
||||
|
||||
1. `startSession`:
|
||||
- spawn `agent acp`
|
||||
- `initialize`
|
||||
- `authenticate(cursor_login)` (best-effort, typed failure handling)
|
||||
- `session/new` or `session/load`
|
||||
2. `sendTurn`:
|
||||
- send `session/prompt { sessionId, prompt: [...] }`
|
||||
- consume streaming `session/update` notifications until terminal prompt response
|
||||
3. `interruptTurn`:
|
||||
- no native `session/cancel` today; implement fallback:
|
||||
- terminate ACP process + restart + `session/load` for subsequent turns
|
||||
- mark in-flight turn as interrupted/failed in canonical events
|
||||
4. `respondToRequest`:
|
||||
- map T3 approval decision -> ACP `optionId`
|
||||
- reply to exact JSON-RPC request id from `session/request_permission`
|
||||
|
||||
### 3.4 Effect-first implementation style (required)
|
||||
|
||||
1. Keep logic inside `CursorAdapterLive`.
|
||||
2. Use Effect primitives:
|
||||
- `Queue` + `Stream.fromQueue` for event fan-out
|
||||
- `Ref` / `Ref.Synchronized` for session/process/request state
|
||||
- scoped fibers for stdout/stderr read loops
|
||||
3. Typed JSON decode at boundary:
|
||||
- request/response envelopes
|
||||
- `session/update` union schema
|
||||
- permission-request schema
|
||||
4. Keep adapter errors in typed error algebra with explicit mapping at process/protocol boundaries.
|
||||
|
||||
---
|
||||
|
||||
## 4) Canonical Event Mapping Plan (ACP -> ProviderRuntimeEvent)
|
||||
|
||||
1. `session/update: agent_message_chunk`
|
||||
- emit `message.delta` for assistant stream
|
||||
2. prompt terminal response (`session/prompt` result `stopReason: end_turn`)
|
||||
- emit `message.completed` + `turn.completed`
|
||||
3. `session/update: agent_thought_chunk`
|
||||
- initial mapping: emit thinking activity (or ignore if we keep current canonical surface minimal)
|
||||
4. `session/update: tool_call`
|
||||
- first-seen `toolCallId` emits `tool.started`
|
||||
- subsequent `tool_call` for same ID treated as metadata update (no duplicate started event)
|
||||
5. `session/update: tool_call_update`
|
||||
- `in_progress`: optional progress activity
|
||||
- `completed`: emit `tool.completed` with summarized `rawOutput` when present
|
||||
6. `session/request_permission`
|
||||
- emit `approval.requested` with mapped options
|
||||
- when client decision sent, emit `approval.resolved`
|
||||
7. protocol/process error
|
||||
- emit `runtime.error`
|
||||
- fail active turn/session as appropriate
|
||||
|
||||
Synthetic IDs:
|
||||
1. `turnId`: T3-generated UUID per `sendTurn`.
|
||||
2. `itemId`:
|
||||
- assistant stream: `${turnId}:assistant`
|
||||
- tools: `${turnId}:${toolCallId}`
|
||||
|
||||
---
|
||||
|
||||
## 5) Approval, Resume, and Rollback Behavior
|
||||
|
||||
### 5.1 Approvals
|
||||
|
||||
1. Cursor ACP permission requests are externally controllable; implement full `respondToRequest` path in v1.
|
||||
2. Decision mapping:
|
||||
- allow once -> `allow-once`
|
||||
- allow always -> `allow-always`
|
||||
- reject -> `reject-once`
|
||||
|
||||
### 5.2 Resume
|
||||
|
||||
1. `session/load` is available and should be first-class for adapter restart/reconnect.
|
||||
2. Must send required params: `sessionId`, `cwd`, `mcpServers`.
|
||||
|
||||
### 5.3 Rollback / thread read
|
||||
|
||||
1. ACP currently has no observed rollback API.
|
||||
2. Plan for v1:
|
||||
- `readThread`: adapter-maintained snapshot projection
|
||||
- `rollbackThread`: explicit unsupported error
|
||||
3. Product guard:
|
||||
- disable checkpoint revert for Cursor threads in UI until rollback exists.
|
||||
|
||||
---
|
||||
|
||||
## 6) Required Contract and Runtime Changes
|
||||
|
||||
### 6.1 Contracts
|
||||
|
||||
1. Add `cursor` to `ProviderKind`.
|
||||
2. Add Cursor provider start options (`providerOptions.cursor`), ACP-oriented:
|
||||
- optional `binaryPath`
|
||||
- optional auth/mode knobs if needed later
|
||||
3. Extend model options for Cursor list and traits mapping.
|
||||
4. Add schemas for ACP-native event union in Cursor adapter service file.
|
||||
|
||||
### 6.2 Server orchestration and registry
|
||||
|
||||
1. Register `CursorAdapter` in provider registry and server layer wiring.
|
||||
2. Update provider-kind persistence decoding for `cursor`.
|
||||
3. Fix `ProviderCommandReactor` precedence to honor explicit provider in turn-start command.
|
||||
|
||||
### 6.3 Web
|
||||
|
||||
1. Cursor in provider picker and model picker (already partially done).
|
||||
2. Trait controls map to concrete Cursor model identifiers.
|
||||
3. Surface unsupported rollback behavior in UX.
|
||||
|
||||
---
|
||||
|
||||
## 7) Implementation Phases
|
||||
|
||||
### Phase A: ACP process and protocol skeleton
|
||||
|
||||
1. Implement ACP process lifecycle in `CursorAdapterLive`.
|
||||
2. Implement JSON-RPC request/response multiplexer.
|
||||
3. Implement `initialize`/`authenticate`/`session/new|load` flow.
|
||||
4. Wire `streamEvents` from ACP notifications.
|
||||
|
||||
### Phase B: Runtime projection and approvals
|
||||
|
||||
1. Map `session/update` variants to canonical runtime events.
|
||||
2. Implement permission-request bridging to `respondToRequest`.
|
||||
3. Implement dedupe for repeated `tool_call` on same `toolCallId`.
|
||||
|
||||
### Phase C: Turn control and interruption
|
||||
|
||||
1. Implement single in-flight prompt protection per session.
|
||||
2. Implement interruption fallback (process restart + reload) because `session/cancel` unavailable.
|
||||
3. Ensure clean state recovery on ACP process crash.
|
||||
|
||||
### Phase D: Orchestration + UX polish
|
||||
|
||||
1. Provider routing precedence fix.
|
||||
2. Cursor-specific UX notes for unsupported rollback.
|
||||
3. End-to-end smoke and event log validation.
|
||||
|
||||
---
|
||||
|
||||
## 8) Test Plan
|
||||
|
||||
Follow project rule: backend external-service integrations tested via layered fakes, not by mocking core business logic.
|
||||
|
||||
### 8.1 Unit tests (`CursorAdapter`)
|
||||
|
||||
1. JSON-RPC envelope parsing:
|
||||
- response matching by id
|
||||
- server request handling (`session/request_permission`)
|
||||
- notification decode (`session/update`)
|
||||
2. Event projection:
|
||||
- `agent_message_chunk` / `agent_thought_chunk`
|
||||
- `tool_call` + `tool_call_update` dedupe/lifecycle
|
||||
- permission request -> approval events
|
||||
3. Error mapping:
|
||||
- unknown session
|
||||
- method-not-found (`session/cancel`)
|
||||
- invalid params
|
||||
|
||||
### 8.2 Provider service/routing tests
|
||||
|
||||
1. Registry resolves `cursor`.
|
||||
2. Session directory persistence reads/writes `cursor`.
|
||||
3. ProviderService fan-out ordering with Cursor ACP events.
|
||||
|
||||
### 8.3 Orchestration tests
|
||||
|
||||
1. `thread.turn.start` with `provider: cursor` routes to Cursor adapter.
|
||||
2. approval response command maps to ACP permission response.
|
||||
3. checkpoint revert on Cursor thread returns controlled unsupported failure.
|
||||
|
||||
### 8.4 Optional live smoke
|
||||
|
||||
1. Env-gated ACP smoke:
|
||||
- start session
|
||||
- run prompt
|
||||
- observe deltas + completion
|
||||
- exercise permission request path with one tool call
|
||||
|
||||
---
|
||||
|
||||
## 9) Operational Notes
|
||||
|
||||
1. Keep one in-flight turn per ACP session.
|
||||
2. Keep per-session ACP process logs/NDJSON artifacts for debugging.
|
||||
3. Treat `session/cancel` as unsupported until Cursor ships it; avoid relying on it.
|
||||
4. Preserve resume metadata (`acpSessionId`) for crash recovery.
|
||||
|
||||
---
|
||||
|
||||
## 10) Open Questions
|
||||
|
||||
1. Should we call `authenticate` always, or only after auth-required errors?
|
||||
2. Should model selection be passed at `session/new` only, or can/should we support model switching mid-session if ACP adds API?
|
||||
3. For interruption UX, do we expose “hard interrupt” semantics (process restart) explicitly?
|
||||
|
||||
---
|
||||
|
||||
## 11) Delivery Checklist
|
||||
|
||||
1. Plan/documentation switched from headless `agent -p` to ACP `agent acp`.
|
||||
2. Contracts updated (`ProviderKind`, Cursor options, model/trait mapping).
|
||||
3. Cursor ACP adapter layer implemented and registered.
|
||||
4. Provider precedence fixed in orchestration router.
|
||||
5. Approval response path wired through ACP permission requests.
|
||||
6. Tests added for protocol decode, projection, approval flow, and routing.
|
||||
7. Lint + tests green.
|
||||
@@ -10,3 +10,5 @@
|
||||
8. `08-precommit-format-and-lint.md`
|
||||
9. `09-event-state-test-expansion.md`
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
11. `11-centralized-sqlite-persistence-revamp.md`
|
||||
12. `12-remove-legacy-localstorage-migrations-and-cr-hardening.md`
|
||||
@@ -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"
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
|
||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
|
||||
# CLAUDE.md
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
@@ -19,16 +14,11 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
@@ -39,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:
|
||||
|
||||
|
||||
@@ -63,23 +63,30 @@ bun run dist:desktop:dmg
|
||||
npx t3
|
||||
```
|
||||
|
||||
## Remote usage (phone/tablet/laptop)
|
||||
|
||||
To run the server on one device and control it from another (for example over Tailscale), use:
|
||||
|
||||
- `docs/remote-access.md`
|
||||
|
||||
This includes:
|
||||
|
||||
- architecture and security model
|
||||
- production setup for remote control
|
||||
- remote dev setup with hot reload
|
||||
- troubleshooting for cross-device connectivity
|
||||
|
||||
## Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
||||
- `bun run start` — Runs the production server (serves built web app as static files).
|
||||
- `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:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
@@ -89,18 +96,12 @@ npx t3
|
||||
- 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`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
- Default ports: server `3773`, web `5733`
|
||||
- Default ports: server `3773`, web `5173`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
|
||||
@@ -118,12 +119,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.
|
||||
@@ -131,6 +132,3 @@ Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI
|
||||
## CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -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.
|
||||
@@ -15,11 +15,11 @@
|
||||
- [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
|
||||
- [x] Disable "streaming" (wait until whole paragraph/step finishes before showing it
|
||||
- [ ] 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)
|
||||
|
||||
## Bigger things
|
||||
|
||||
- [ ] Queueing messages
|
||||
- [x] External runners (i.e. running the cli on a mac mini)
|
||||
- [ ] External runners (i.e. running the cli on a mac mini)
|
||||
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"productName": "T3 Code (Alpha)",
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
@@ -14,18 +15,14 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
"electron": "40.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"@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)"
|
||||
}
|
||||
}
|
||||
@@ -1,171 +1,43 @@
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { watch } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { spawnSync } 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 ?? 5733);
|
||||
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
|
||||
const devServerUrl = `http://localhost:${port}`;
|
||||
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
let restartTimer = null;
|
||||
let currentApp = null;
|
||||
let restartQueue = Promise.resolve();
|
||||
const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
if (shuttingDown || currentApp !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
currentApp = app;
|
||||
|
||||
app.once("error", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
|
||||
app.once("exit", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown && !expectedExits.has(app)) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopApp() {
|
||||
const app = currentApp;
|
||||
if (!app) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentApp = null;
|
||||
expectedExits.add(app);
|
||||
|
||||
await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
const finish = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
resolve();
|
||||
};
|
||||
|
||||
app.once("exit", finish);
|
||||
app.kill("SIGTERM");
|
||||
killChildTreeByPid(app.pid, "TERM");
|
||||
|
||||
setTimeout(() => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
app.kill("SIGKILL");
|
||||
killChildTreeByPid(app.pid, "KILL");
|
||||
finish();
|
||||
}, forcedShutdownTimeoutMs).unref();
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleRestart() {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
}
|
||||
|
||||
restartTimer = setTimeout(() => {
|
||||
restartTimer = null;
|
||||
restartQueue = restartQueue
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await stopApp();
|
||||
if (!shuttingDown) {
|
||||
startApp();
|
||||
}
|
||||
});
|
||||
}, restartDebounceMs);
|
||||
}
|
||||
|
||||
function startWatchers() {
|
||||
for (const { directory, files } of watchedDirectories) {
|
||||
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
|
||||
if (typeof filename !== "string" || !files.has(filename)) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleRestart();
|
||||
});
|
||||
|
||||
watchers.push(watcher);
|
||||
}
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
@@ -173,29 +45,23 @@ async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
try {
|
||||
await Promise.race([
|
||||
monitor.destroy(),
|
||||
new Promise((resolve) => setTimeout(resolve, 1_500)),
|
||||
]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
}
|
||||
|
||||
for (const watcher of watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
await stopApp();
|
||||
killChildTree("TERM");
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, childTreeGracePeriodMs);
|
||||
});
|
||||
killChildTree("KILL");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
startWatchers();
|
||||
cleanupStaleDevApps();
|
||||
startApp();
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
|
||||
@@ -25,22 +25,34 @@ 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",
|
||||
});
|
||||
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",
|
||||
});
|
||||
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());
|
||||
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) {
|
||||
@@ -69,16 +81,28 @@ function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
|
||||
const helperPlistPath = join(
|
||||
frameworksDir,
|
||||
entry.name,
|
||||
"Contents",
|
||||
"Info.plist",
|
||||
);
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
|
||||
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 helperIdSuffix = suffix
|
||||
.replace(/[()]/g, "")
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
@@ -101,7 +125,12 @@ 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 targetBinaryPath = join(
|
||||
targetAppBundlePath,
|
||||
"Contents",
|
||||
"MacOS",
|
||||
"Electron",
|
||||
);
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as ChildProcess from "node:child_process";
|
||||
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 = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
+127
-761
File diff suppressed because it is too large.
Load diff
@@ -1,24 +1,20 @@
|
||||
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 UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
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, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
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>,
|
||||
onMenuAction: (listener: (action: string) => void) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
listener(action);
|
||||
@@ -29,18 +25,4 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (typeof state !== "object" || state === null) return;
|
||||
listener(state as Parameters<typeof listener>[0]);
|
||||
};
|
||||
|
||||
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
});
|
||||
@@ -1,74 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
|
||||
tempRoots.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempRoots.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("RotatingFileSink", () => {
|
||||
it("rotates when writes exceed max bytes", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 10,
|
||||
maxFiles: 3,
|
||||
});
|
||||
|
||||
sink.write("12345");
|
||||
sink.write("67890");
|
||||
sink.write("abc");
|
||||
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
|
||||
});
|
||||
|
||||
it("retains only maxFiles backups", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "server-child.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 4,
|
||||
maxFiles: 2,
|
||||
});
|
||||
|
||||
sink.write("aaaa");
|
||||
sink.write("bbbb");
|
||||
sink.write("cccc");
|
||||
sink.write("dddd");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
|
||||
});
|
||||
|
||||
it("prunes stale backups above maxFiles on startup", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
|
||||
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 16,
|
||||
maxFiles: 2,
|
||||
});
|
||||
sink.write("hello");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,130 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
reduceDesktopUpdateStateOnCheckStart,
|
||||
reduceDesktopUpdateStateOnDownloadComplete,
|
||||
reduceDesktopUpdateStateOnDownloadFailure,
|
||||
reduceDesktopUpdateStateOnDownloadProgress,
|
||||
reduceDesktopUpdateStateOnDownloadStart,
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
|
||||
describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("checking");
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
expect(state.canRetry).toBe(false);
|
||||
});
|
||||
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"network unavailable",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("error");
|
||||
expect(state.errorContext).toBe("check");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
downloadPercent: 43,
|
||||
},
|
||||
"checksum mismatch",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("available");
|
||||
expect(state.availableVersion).toBe("1.1.0");
|
||||
expect(state.errorContext).toBe("download");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
},
|
||||
"1.1.0",
|
||||
);
|
||||
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
|
||||
|
||||
expect(downloaded.status).toBe("downloaded");
|
||||
expect(downloaded.downloadedVersion).toBe("1.1.0");
|
||||
expect(failedInstall.status).toBe("downloaded");
|
||||
expect(failedInstall.errorContext).toBe("install");
|
||||
expect(failedInstall.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
downloadedVersion: "1.1.0",
|
||||
message: "old failure",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("up-to-date");
|
||||
expect(state.availableVersion).toBeNull();
|
||||
expect(state.downloadedVersion).toBeNull();
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
|
||||
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
|
||||
return {
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
currentVersion,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckStart(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "error",
|
||||
message,
|
||||
checkedAt,
|
||||
downloadPercent: null,
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadStart(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: 0,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: nextStatusAfterDownloadFailure(state),
|
||||
message,
|
||||
downloadPercent: null,
|
||||
errorContext: "download",
|
||||
canRetry: getCanRetryAfterDownloadFailure(state),
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadProgress(
|
||||
state: DesktopUpdateState,
|
||||
percent: number,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: percent,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadComplete(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
availableVersion: version,
|
||||
downloadedVersion: version,
|
||||
downloadPercent: 100,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnInstallFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
message,
|
||||
errorContext: "install",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getCanRetryAfterDownloadFailure,
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
currentVersion: "1.0.0",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
|
||||
describe("shouldBroadcastDownloadProgress", () => {
|
||||
it("broadcasts the first downloading progress update", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: null },
|
||||
1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("skips progress updates within the same 10% bucket", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
|
||||
18.7,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a new 10% bucket is reached", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
|
||||
20.1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a retry resets the download percentage", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
|
||||
0.2,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAutoUpdateDisabledReason", () => {
|
||||
it("reports development builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: true,
|
||||
isPackaged: false,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
|
||||
it("reports linux non-AppImage builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextStatusAfterDownloadFailure", () => {
|
||||
it("returns available when an update version is still known", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe("available");
|
||||
});
|
||||
|
||||
it("returns error when no update version can be retried", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCanRetryAfterDownloadFailure", () => {
|
||||
it("returns true when an available version is still present", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when no version is available to retry", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
export function shouldBroadcastDownloadProgress(
|
||||
currentState: DesktopUpdateState,
|
||||
nextPercent: number,
|
||||
): boolean {
|
||||
if (currentState.status !== "downloading") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentPercent = currentState.downloadPercent;
|
||||
if (currentPercent === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const previousStep = Math.floor(currentPercent / 10);
|
||||
const nextStep = Math.floor(nextPercent / 10);
|
||||
return nextStep !== previousStep || nextPercent === 100;
|
||||
}
|
||||
|
||||
export function nextStatusAfterDownloadFailure(
|
||||
currentState: DesktopUpdateState,
|
||||
): DesktopUpdateState["status"] {
|
||||
return currentState.availableVersion ? "available" : "error";
|
||||
}
|
||||
|
||||
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
|
||||
return currentState.availableVersion !== null;
|
||||
}
|
||||
|
||||
export function getAutoUpdateDisabledReason(args: {
|
||||
isDevelopment: boolean;
|
||||
isPackaged: boolean;
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
}): string | null {
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
if (args.disabledByEnv) {
|
||||
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
|
||||
}
|
||||
if (args.platform === "linux" && !args.appImage) {
|
||||
return "Automatic updates on Linux require running the AppImage build.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -1,450 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Option,
|
||||
Schedule,
|
||||
Schema,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.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 { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.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";
|
||||
import { ServerConfig } from "../src/config.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}`]);
|
||||
}
|
||||
|
||||
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
|
||||
"WaitForTimeoutError",
|
||||
{
|
||||
description: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<A, never>;
|
||||
function waitFor<A, B extends A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => value is B,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<B, never>;
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
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 WaitForTimeoutError({ description }) : error,
|
||||
),
|
||||
Effect.orDie,
|
||||
);
|
||||
}
|
||||
|
||||
class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
|
||||
"OrchestrationHarnessRuntimeError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
|
||||
Effect.tryPromise({
|
||||
try: run,
|
||||
catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
|
||||
});
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
export const makeOrchestrationIntegrationHarness = (
|
||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const provider = options?.provider ?? "codex";
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
? null
|
||||
: yield* makeTestProviderAdapterHarness({
|
||||
provider,
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === adapterHarness.provider
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
: null;
|
||||
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 persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexAdapter = yield* CodexAdapter;
|
||||
return {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === "codex"
|
||||
? Effect.succeed(codexAdapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed(["codex"] as const),
|
||||
} as typeof ProviderAdapterRegistry.Service;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerLayer = useRealCodex
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
)
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
);
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
} as unknown as GitCoreShape);
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: null }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
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(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
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;
|
||||
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const stopAllExit = yield* Effect.exit(
|
||||
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
|
||||
);
|
||||
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
|
||||
const failureCause = Exit.isFailure(stopAllExit)
|
||||
? stopAllExit.cause
|
||||
: Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness: adapterHarness as TestProviderAdapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -1,561 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderRuntimeEvent,
|
||||
RuntimeSessionId,
|
||||
ProviderSession,
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} 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<FixtureProviderRuntimeEvent>;
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode" | "cursor";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
// Temporary alias while fixtures migrate to the new name.
|
||||
export type LegacyProviderRuntimeEvent = FixtureProviderRuntimeEvent;
|
||||
|
||||
interface SessionState {
|
||||
readonly session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
turnCount: number;
|
||||
readonly queuedResponses: Array<TestTurnResponse>;
|
||||
readonly rollbackCalls: Array<number>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
if (
|
||||
value === "completed" ||
|
||||
value === "failed" ||
|
||||
value === "interrupted" ||
|
||||
value === "cancelled"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return "completed";
|
||||
}
|
||||
|
||||
function mapRequestType(requestKind: unknown):
|
||||
| "command_execution_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown" {
|
||||
if (requestKind === "command") {
|
||||
return "command_execution_approval";
|
||||
}
|
||||
if (requestKind === "file-change") {
|
||||
return "file_change_approval";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function mapItemType(toolKind: unknown): "command_execution" | "file_change" | "unknown" {
|
||||
if (toolKind === "command") {
|
||||
return "command_execution";
|
||||
}
|
||||
if (toolKind === "file-change") {
|
||||
return "file_change";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRuntimeEvent {
|
||||
const type = typeof rawEvent.type === "string" ? rawEvent.type : "";
|
||||
switch (type) {
|
||||
case "turn.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.started",
|
||||
payload: isRecord(rawEvent.payload) ? rawEvent.payload : {},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "turn.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.completed",
|
||||
payload: isRecord(rawEvent.payload)
|
||||
? rawEvent.payload
|
||||
: {
|
||||
state: normalizeTurnState(rawEvent.status),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.delta":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: typeof rawEvent.delta === "string" ? rawEvent.delta : "",
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.started",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
status: "completed",
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.requested":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.resolved":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.decision === "string" ? { decision: rawEvent.decision } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
default:
|
||||
return rawEvent as ProviderRuntimeEvent;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly getStartCount: () => number;
|
||||
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
|
||||
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
|
||||
readonly listActiveSessionIds: () => ReadonlyArray<ThreadId>;
|
||||
readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: "codex" | "claudeCode",
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: "codex" | "claudeCode",
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? "codex";
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
|
||||
const approvalResponsesBySession = new Map<
|
||||
ThreadId,
|
||||
Array<{
|
||||
readonly threadId: ThreadId;
|
||||
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,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
sessionCount += 1;
|
||||
const threadId = input.threadId;
|
||||
const createdAt = nowIso();
|
||||
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId,
|
||||
cwd: input.cwd,
|
||||
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(threadId, {
|
||||
session,
|
||||
snapshot: {
|
||||
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.threadId);
|
||||
if (!state) {
|
||||
return yield* missingSessionEffect(provider, input.threadId);
|
||||
}
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "sendTurn",
|
||||
issue: `No queued turn response for thread ${input.threadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const assistantDeltas: string[] = [];
|
||||
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
}
|
||||
|
||||
const runtimeEvent = normalizeFixtureEvent(rawEvent);
|
||||
const runtimeType = (runtimeEvent as { type: string }).type;
|
||||
if (runtimeType === "content.delta") {
|
||||
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
|
||||
if (typeof payload?.delta === "string") {
|
||||
assistantDeltas.push(payload.delta);
|
||||
}
|
||||
} else if (runtimeType === "message.delta") {
|
||||
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
|
||||
if (typeof legacyDelta === "string") {
|
||||
assistantDeltas.push(legacyDelta);
|
||||
}
|
||||
}
|
||||
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,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
yield* emit(completedEvent);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
threadId,
|
||||
turnId,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = interruptCallsBySession.get(threadId) ?? [];
|
||||
existing.push(turnId);
|
||||
interruptCallsBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = approvalResponsesBySession.get(threadId) ?? [];
|
||||
existing.push({
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
approvalResponsesBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
_requestId,
|
||||
_answers,
|
||||
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
sessions.delete(threadId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
return Effect.succeed(state.snapshot);
|
||||
};
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and current turn count.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.sync(() => {
|
||||
state.rollbackCalls.push(numTurns);
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
|
||||
};
|
||||
state.turnCount = state.snapshot.turns.length;
|
||||
return state.snapshot;
|
||||
});
|
||||
};
|
||||
|
||||
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
|
||||
Effect.sync(() => sessions.get(threadId)).pipe(
|
||||
Effect.flatMap((state) =>
|
||||
state
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(sessionNotFound(provider, threadId)),
|
||||
),
|
||||
);
|
||||
|
||||
const queueTurnResponseForNextSession = (
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, never> =>
|
||||
Effect.sync(() => {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return [...state.rollbackCalls];
|
||||
};
|
||||
|
||||
const getStartCount = (): number => sessionCount;
|
||||
|
||||
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
|
||||
const calls = interruptCallsBySession.get(threadId);
|
||||
if (!calls) {
|
||||
return [];
|
||||
}
|
||||
return [...calls];
|
||||
};
|
||||
|
||||
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
|
||||
Array.from(sessions.values(), (state) => state.session.threadId);
|
||||
|
||||
const getApprovalResponses = (
|
||||
threadId: ThreadId,
|
||||
): ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}> => {
|
||||
const responses = approvalResponsesBySession.get(threadId);
|
||||
if (!responses) {
|
||||
return [];
|
||||
}
|
||||
return [...responses];
|
||||
};
|
||||
|
||||
return {
|
||||
adapter,
|
||||
provider,
|
||||
queueTurnResponse,
|
||||
queueTurnResponseForNextSession,
|
||||
getStartCount,
|
||||
getRollbackCalls,
|
||||
getInterruptCalls,
|
||||
listActiveSessionIds,
|
||||
getApprovalResponses,
|
||||
} satisfies TestProviderAdapterHarness;
|
||||
});
|
||||
@@ -1,162 +0,0 @@
|
||||
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "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,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Done.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "item.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "request.opened",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "request.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
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,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,295 +0,0 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
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 threadId: ThreadId;
|
||||
readonly userText: string;
|
||||
readonly response: TestTurnResponse;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
input.provider.sendTurn({
|
||||
threadId: input.threadId,
|
||||
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"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
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"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
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"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
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,
|
||||
threadId: session.threadId,
|
||||
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"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
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,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
threadId: session.threadId,
|
||||
numTurns: 1,
|
||||
});
|
||||
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
|
||||
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)),
|
||||
);
|
||||
@@ -1,11 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.20",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"version": "0.1.0",
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
@@ -13,37 +8,26 @@
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "bun run src/index.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5173} bun run src/index.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": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13 || ^23.4 || >=24.10"
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* 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 fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
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(
|
||||
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.cpSync(webDist, target, { recursive: true });
|
||||
console.log("✓ Bundled web app into dist/client");
|
||||
@@ -1,172 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new CliError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// build subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const buildCmd = Command.make(
|
||||
"build",
|
||||
{
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
const clientTarget = path.join(serverDir, "dist/client");
|
||||
|
||||
if (yield* fs.exists(webDist)) {
|
||||
yield* fs.copy(webDist, clientTarget);
|
||||
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||
} else {
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publish subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const publishCmd = Command.make(
|
||||
"publish",
|
||||
{
|
||||
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
|
||||
access: Flag.string("access").pipe(Flag.withDefault("public")),
|
||||
appVersion: Flag.string("app-version").pipe(Flag.optional),
|
||||
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
|
||||
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
|
||||
// Build package.json for publish
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
};
|
||||
|
||||
// Resolve catalog: entries in production dependencies
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
}),
|
||||
// Use: npm publish
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// root command
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const cli = Command.make("cli").pipe(
|
||||
Command.withDescription("T3 server build & publish CLI."),
|
||||
Command.withSubcommands([buildCmd, publishCmd]),
|
||||
);
|
||||
|
||||
Command.run(cli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,66 +0,0 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import path from "node:path";
|
||||
|
||||
import { Effect, FileSystem, Layer, Logger, ServiceMap } from "effect";
|
||||
|
||||
import { makeEventNdjsonLogger } from "../src/provider/Layers/EventNdjsonLogger.ts";
|
||||
|
||||
class LogDir extends ServiceMap.Service<LogDir, string>()("t3/scripts/logger-scope-repro/LogDir") {}
|
||||
|
||||
const main = Effect.gen(function* () {
|
||||
const logdir = yield* LogDir;
|
||||
const providerLogPath = path.join(logdir, "provider");
|
||||
|
||||
yield* Effect.logInfo(`providerLogPath=${providerLogPath}`);
|
||||
|
||||
const providerLogger = yield* makeEventNdjsonLogger(providerLogPath, {
|
||||
stream: "native",
|
||||
batchWindowMs: 10,
|
||||
});
|
||||
|
||||
yield* Effect.logInfo("before provider write");
|
||||
|
||||
if (providerLogger) {
|
||||
yield* providerLogger.write(
|
||||
{
|
||||
kind: "probe",
|
||||
message: "provider-only event",
|
||||
},
|
||||
"thread-123" as never,
|
||||
);
|
||||
}
|
||||
|
||||
yield* Effect.logInfo("after provider write");
|
||||
yield* Effect.sleep("50 millis");
|
||||
|
||||
if (providerLogger) {
|
||||
yield* providerLogger.close();
|
||||
}
|
||||
yield* Effect.logInfo("after provider close");
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const logContents = yield* fs
|
||||
.readDirectory(logdir, { recursive: true })
|
||||
.pipe(
|
||||
Effect.flatMap((entries) =>
|
||||
Effect.all(entries.map((entry) => fs.readFileString(path.join(logdir, entry)))),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo(`logContents=${logContents}`);
|
||||
});
|
||||
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const logdir = path.join(process.cwd(), "logtest");
|
||||
yield* fs.makeDirectory(logdir);
|
||||
|
||||
const fileLogger = yield* Logger.formatSimple.pipe(
|
||||
Logger.toFile(path.join(logdir, "global.log")),
|
||||
);
|
||||
const dualLogger = Logger.layer([fileLogger, Logger.consolePretty()]);
|
||||
|
||||
const mainLayer = Layer.mergeAll(dualLogger, Layer.succeed(LogDir, logdir));
|
||||
|
||||
yield* main.pipe(Effect.provide(mainLayer));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
|
||||
@@ -1,28 +0,0 @@
|
||||
import path from "node:path";
|
||||
|
||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||
|
||||
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
|
||||
const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
|
||||
return null;
|
||||
}
|
||||
return normalized.replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
export function resolveAttachmentRelativePath(input: {
|
||||
readonly stateDir: string;
|
||||
readonly relativePath: string;
|
||||
}): string | null {
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
|
||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||
return null;
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createAttachmentId,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
resolveAttachmentPathById,
|
||||
} from "./attachmentStore.ts";
|
||||
|
||||
describe("attachmentStore", () => {
|
||||
it("sanitizes thread ids when creating attachment ids", () => {
|
||||
const attachmentId = createAttachmentId("thread.folder/unsafe space");
|
||||
expect(attachmentId).toBeTruthy();
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const threadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
expect(threadSegment).toBeTruthy();
|
||||
expect(threadSegment).toMatch(/^[a-z0-9_-]+$/i);
|
||||
expect(threadSegment).not.toContain(".");
|
||||
expect(threadSegment).not.toContain("%");
|
||||
expect(threadSegment).not.toContain("/");
|
||||
});
|
||||
|
||||
it("parses exact thread segments from attachment ids without prefix collisions", () => {
|
||||
const fooId = "foo-00000000-0000-4000-8000-000000000001";
|
||||
const fooBarId = "foo-bar-00000000-0000-4000-8000-000000000002";
|
||||
|
||||
expect(parseThreadSegmentFromAttachmentId(fooId)).toBe("foo");
|
||||
expect(parseThreadSegmentFromAttachmentId(fooBarId)).toBe("foo-bar");
|
||||
});
|
||||
|
||||
it("normalizes created thread segments to lowercase", () => {
|
||||
const attachmentId = createAttachmentId("Thread.Foo");
|
||||
expect(attachmentId).toBeTruthy();
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
expect(parseThreadSegmentFromAttachmentId(attachmentId)).toBe("thread-foo");
|
||||
});
|
||||
|
||||
it("resolves attachment path by id using the extension that exists on disk", () => {
|
||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
try {
|
||||
const attachmentId = "thread-1-attachment";
|
||||
const attachmentsDir = path.join(stateDir, "attachments");
|
||||
fs.mkdirSync(attachmentsDir, { recursive: true });
|
||||
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
fs.writeFileSync(pngPath, Buffer.from("hello"));
|
||||
|
||||
const resolved = resolveAttachmentPathById({
|
||||
stateDir,
|
||||
attachmentId,
|
||||
});
|
||||
expect(resolved).toBe(pngPath);
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns null when no attachment file exists for the id", () => {
|
||||
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
|
||||
try {
|
||||
const resolved = resolveAttachmentPathById({
|
||||
stateDir,
|
||||
attachmentId: "thread-1-missing",
|
||||
});
|
||||
expect(resolved).toBeNull();
|
||||
} finally {
|
||||
fs.rmSync(stateDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,110 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths.ts";
|
||||
import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts";
|
||||
|
||||
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||
const ATTACHMENT_ID_UUID_PATTERN =
|
||||
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
const ATTACHMENT_ID_PATTERN = new RegExp(
|
||||
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
|
||||
"i",
|
||||
);
|
||||
|
||||
export function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
const segment = threadId
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_-]+/gi, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[-_]+|[-_]+$/g, "")
|
||||
.slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)
|
||||
.replace(/[-_]+$/g, "");
|
||||
if (segment.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return segment;
|
||||
}
|
||||
|
||||
export function createAttachmentId(threadId: string): string | null {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
if (!threadSegment) {
|
||||
return null;
|
||||
}
|
||||
return `${threadSegment}-${randomUUID()}`;
|
||||
}
|
||||
|
||||
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
return null;
|
||||
}
|
||||
const match = normalizedId.match(ATTACHMENT_ID_PATTERN);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return match[1]?.toLowerCase() ?? null;
|
||||
}
|
||||
|
||||
export function attachmentRelativePath(attachment: ChatAttachment): string {
|
||||
switch (attachment.type) {
|
||||
case "image": {
|
||||
const extension = inferImageExtension({
|
||||
mimeType: attachment.mimeType,
|
||||
fileName: attachment.name,
|
||||
});
|
||||
return `${attachment.id}${extension}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveAttachmentPath(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachment: ChatAttachment;
|
||||
}): string | null {
|
||||
return resolveAttachmentRelativePath({
|
||||
stateDir: input.stateDir,
|
||||
relativePath: attachmentRelativePath(input.attachment),
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveAttachmentPathById(input: {
|
||||
readonly stateDir: string;
|
||||
readonly attachmentId: string;
|
||||
}): string | null {
|
||||
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
|
||||
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
|
||||
return null;
|
||||
}
|
||||
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
|
||||
const maybePath = resolveAttachmentRelativePath({
|
||||
stateDir: input.stateDir,
|
||||
relativePath: `${normalizedId}${extension}`,
|
||||
});
|
||||
if (maybePath && existsSync(maybePath)) {
|
||||
return maybePath;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseAttachmentIdFromRelativePath(relativePath: string): string | null {
|
||||
const normalized = normalizeAttachmentRelativePath(relativePath);
|
||||
if (!normalized || normalized.includes("/")) {
|
||||
return null;
|
||||
}
|
||||
const extensionIndex = normalized.lastIndexOf(".");
|
||||
if (extensionIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
const id = normalized.slice(0, extensionIndex);
|
||||
return id.length > 0 && !id.includes(".") ? id : null;
|
||||
}
|
||||
@@ -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,197 +0,0 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-01-01T00:00:00.000Z",
|
||||
startedAt: "2026-01-01T00:00:00.000Z",
|
||||
completedAt: "2026-01-01T00:00:00.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
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
|
||||
>()("t3/checkpointing/Services/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>()(
|
||||
"t3/checkpointing/Services/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,21 +1,12 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildCodexInitializeParams,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CodexAppServerManager,
|
||||
classifyCodexStderrLine,
|
||||
isRecoverableThreadResumeError,
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
@@ -24,7 +15,6 @@ function createSendTurnHarness() {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
@@ -61,7 +51,6 @@ function createThreadControlHarness() {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
@@ -84,46 +73,6 @@ function createThreadControlHarness() {
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
function createPendingUserInputHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
pendingUserInputs: new Map([
|
||||
[
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
jsonRpcId: 42,
|
||||
threadId: asThreadId("thread_1"),
|
||||
},
|
||||
],
|
||||
]),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
||||
"requireSession",
|
||||
)
|
||||
.mockReturnValue(context);
|
||||
const writeMessage = vi
|
||||
.spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
|
||||
.mockImplementation(() => {});
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, writeMessage, emitEvent };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -195,19 +144,6 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("enables Codex experimental api capabilities during initialize", () => {
|
||||
expect(buildCodexInitializeParams()).toEqual({
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
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 }> = [];
|
||||
@@ -225,9 +161,7 @@ describe("startSession", () => {
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
expect(events).toHaveLength(1);
|
||||
@@ -249,25 +183,26 @@ describe("sendTurn", () => {
|
||||
createSendTurnHarness();
|
||||
|
||||
const result = await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
sessionId: "sess_1",
|
||||
input: "Inspect this image",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
url: "data:image/png;base64,AAAA",
|
||||
name: "error.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
dataUrl: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turnId: "turn_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
});
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
@@ -283,12 +218,10 @@ describe("sendTurn", () => {
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "running",
|
||||
activeTurnId: "turn_1",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -296,11 +229,14 @@ describe("sendTurn", () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
sessionId: "sess_1",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
url: "data:image/png;base64,BBBB",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 256,
|
||||
dataUrl: "data:image/png;base64,BBBB",
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -316,42 +252,12 @@ describe("sendTurn", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
input: "Plan the work",
|
||||
interactionMode: "plan",
|
||||
});
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Plan the work",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
collaborationMode: {
|
||||
mode: "plan",
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty turn input", async () => {
|
||||
const { manager } = createSendTurnHarness();
|
||||
|
||||
await expect(
|
||||
manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
sessionId: "sess_1",
|
||||
}),
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
@@ -372,9 +278,9 @@ describe("thread checkpoint control", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asThreadId("thread_1"));
|
||||
const result = await manager.readThread("sess_1");
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
@@ -402,7 +308,7 @@ describe("thread checkpoint control", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asThreadId("thread_1"));
|
||||
const result = await manager.readThread("sess_1");
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
@@ -428,7 +334,7 @@ describe("thread checkpoint control", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
|
||||
const result = await manager.rollbackThread("sess_1", 2);
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
||||
threadId: "thread_1",
|
||||
@@ -444,129 +350,3 @@ describe("thread checkpoint control", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("respondToUserInput", () => {
|
||||
it("serializes canonical answers to Codex native answer objects", async () => {
|
||||
const { manager, context, requireSession, writeMessage, emitEvent } =
|
||||
createPendingUserInputHarness();
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
},
|
||||
);
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(writeMessage).toHaveBeenCalledWith(context, {
|
||||
id: 42,
|
||||
result: {
|
||||
answers: {
|
||||
scope: { answers: ["All request methods"] },
|
||||
compat: { answers: ["Keep current envelope"] },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "item/tool/requestUserInput/answered",
|
||||
payload: {
|
||||
requestId: "req-user-input-1",
|
||||
answers: {
|
||||
scope: { answers: ["All request methods"] },
|
||||
compat: { answers: ["Keep current envelope"] },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
||||
it(
|
||||
"keeps prior thread history when resuming with a changed runtime mode",
|
||||
async () => {
|
||||
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
||||
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
|
||||
|
||||
const manager = new CodexAppServerManager();
|
||||
|
||||
try {
|
||||
const firstSession = await manager.startSession({
|
||||
threadId: asThreadId("thread-live"),
|
||||
provider: "codex",
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH
|
||||
? { binaryPath: process.env.CODEX_BINARY_PATH }
|
||||
: {}),
|
||||
...(process.env.CODEX_HOME_PATH
|
||||
? { homePath: process.env.CODEX_HOME_PATH }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const firstTurn = await manager.sendTurn({
|
||||
threadId: firstSession.threadId,
|
||||
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
|
||||
});
|
||||
|
||||
expect(firstTurn.threadId).toBe(firstSession.threadId);
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const snapshot = await manager.readThread(firstSession.threadId);
|
||||
expect(snapshot.turns.length).toBeGreaterThan(0);
|
||||
}, { timeout: 120_000, interval: 1_000 });
|
||||
|
||||
const firstSnapshot = await manager.readThread(firstSession.threadId);
|
||||
const originalThreadId = firstSnapshot.threadId;
|
||||
const originalTurnCount = firstSnapshot.turns.length;
|
||||
|
||||
manager.stopSession(firstSession.threadId);
|
||||
|
||||
const resumedSession = await manager.startSession({
|
||||
threadId: firstSession.threadId,
|
||||
provider: "codex",
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "approval-required",
|
||||
resumeCursor: firstSession.resumeCursor,
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH
|
||||
? { binaryPath: process.env.CODEX_BINARY_PATH }
|
||||
: {}),
|
||||
...(process.env.CODEX_HOME_PATH
|
||||
? { homePath: process.env.CODEX_HOME_PATH }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||
|
||||
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
|
||||
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
|
||||
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: resumedSession.threadId,
|
||||
input: `Reply with exactly the word BETA ${randomUUID()}`,
|
||||
});
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const snapshot = await manager.readThread(resumedSession.threadId);
|
||||
expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
|
||||
}, { timeout: 120_000, interval: 1_000 });
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
rmSync(workspaceDir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
180_000,
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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,81 +0,0 @@
|
||||
/**
|
||||
* ServerConfig - Runtime configuration services.
|
||||
*
|
||||
* Defines process-level server configuration and networking helpers used by
|
||||
* startup and runtime layers.
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { 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>()(
|
||||
"t3/config/ServerConfig",
|
||||
) {
|
||||
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
return {
|
||||
cwd,
|
||||
stateDir: statedir,
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const resolveStaticDir = Effect.fn(function* () {
|
||||
const { join, resolve } = yield* Path.Path;
|
||||
const { exists } = yield* FileSystem.FileSystem;
|
||||
const bundledClient = resolve(join(import.meta.dirname, "client"));
|
||||
const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
if (bundledStat) {
|
||||
return bundledClient;
|
||||
}
|
||||
|
||||
const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
|
||||
const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
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,243 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn, FilesystemCheckpointStore } from "./filesystemCheckpointStore";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
async function runGit(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await runProcess("git", args, {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
function exists(filePath: string): boolean {
|
||||
return fs.existsSync(filePath);
|
||||
}
|
||||
|
||||
async function createRepo(): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-test-"));
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
await runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
await runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
await writeFile(path.join(cwd, "README.md"), "v1\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-v1\n");
|
||||
await runGit(cwd, ["add", "."]);
|
||||
await runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
async function createRepoWithoutHead(): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-empty-test-"));
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
describe("FilesystemCheckpointStore", () => {
|
||||
it("captures refs without mutating branch history and restores workspace state", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_1";
|
||||
|
||||
try {
|
||||
const headBefore = await runGit(cwd, ["rev-parse", "HEAD"]);
|
||||
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const rootCommit = await runGit(cwd, ["rev-parse", "--verify", `${rootRef}^{commit}`]);
|
||||
expect(rootCommit.length).toBeGreaterThan(0);
|
||||
expect(await runGit(cwd, ["rev-parse", "HEAD"])).toBe(headBefore);
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await rm(path.join(cwd, "tracked.txt"));
|
||||
await writeFile(path.join(cwd, "notes.md"), "notes\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-new\n");
|
||||
|
||||
const restoredRoot = await store.restoreCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
expect(restoredRoot).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
||||
expect(await readFile(path.join(cwd, "tracked.txt"), "utf8")).toBe("tracked-v1\n");
|
||||
expect(exists(path.join(cwd, "notes.md"))).toBe(false);
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
|
||||
const restoredTurn1 = await store.restoreCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
expect(restoredTurn1).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
expect(exists(path.join(cwd, "tracked.txt"))).toBe(false);
|
||||
expect(await readFile(path.join(cwd, "notes.md"), "utf8")).toBe("notes\n");
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns false when restoring a missing checkpoint", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId: "thr_2",
|
||||
turnCount: 999,
|
||||
});
|
||||
expect(restored).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to HEAD when restoring turn 0 and root checkpoint ref is missing", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_2b";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
||||
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId,
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(restored).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("prunes refs newer than the retained turn", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_3";
|
||||
|
||||
try {
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn1\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn2\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 2 });
|
||||
|
||||
await store.pruneAfterTurn({
|
||||
cwd,
|
||||
threadId,
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 0 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 1 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 2 })).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns a unified patch between checkpoint turns", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_4";
|
||||
|
||||
try {
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
const diff = await store.diffCheckpoints({
|
||||
cwd,
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to HEAD as diff base when turn 0 checkpoint is missing", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_5";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await writeFile(path.join(cwd, "new.txt"), "new file\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
const diff = await store.diffCheckpoints({
|
||||
cwd,
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git a/README.md b/README.md");
|
||||
expect(diff).toContain("diff --git a/new.txt b/new.txt");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("detects non-repo folders", async () => {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-nonrepo-"));
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns false when repository path does not exist", async () => {
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const cwd = path.join(os.tmpdir(), `t3-fs-checkpoints-missing-${Date.now()}`);
|
||||
|
||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
||||
});
|
||||
|
||||
it("restores checkpoint without reset when repository has no HEAD commit", async () => {
|
||||
const cwd = await createRepoWithoutHead();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr-no-head";
|
||||
|
||||
try {
|
||||
await writeFile(path.join(cwd, "README.md"), "first\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "second\n");
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId,
|
||||
turnCount: 0,
|
||||
});
|
||||
|
||||
expect(restored).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("first\n");
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
function quoteGitCommand(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function checkpointRefThreadSegment(threadId: string): string {
|
||||
return Buffer.from(threadId, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: string, turnCount: number): string {
|
||||
if (!Number.isInteger(turnCount) || turnCount < 0) {
|
||||
throw new Error(`Invalid checkpoint turn count: ${turnCount}`);
|
||||
}
|
||||
return `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/${turnCount}`;
|
||||
}
|
||||
|
||||
interface GitOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
stdin?: string;
|
||||
allowNonZeroExit?: boolean;
|
||||
}
|
||||
|
||||
export class FilesystemCheckpointStore {
|
||||
async isGitRepository(cwd: string): Promise<boolean> {
|
||||
try {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0 && result.stdout.trim() === "true";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async captureCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<void> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoint-"));
|
||||
|
||||
try {
|
||||
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 hasHead = await this.hasHeadCommit(cwd);
|
||||
if (hasHead) {
|
||||
await this.runGit(cwd, ["read-tree", "HEAD"], { env: commitEnv });
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["add", "-A", "--", "."], { env: commitEnv });
|
||||
const writeTreeResult = await this.runGit(cwd, ["write-tree"], { env: commitEnv });
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (!treeOid) {
|
||||
throw new Error("git write-tree returned an empty tree oid.");
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint thread=${threadId} turn=${turnCount}`;
|
||||
const commitTreeResult = await this.runGit(cwd, ["commit-tree", treeOid], {
|
||||
env: commitEnv,
|
||||
stdin: `${message}\n`,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (!commitOid) {
|
||||
throw new Error("git commit-tree returned an empty commit oid.");
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["update-ref", ref, commitOid]);
|
||||
} finally {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async hasCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
const commit = await this.resolveCheckpointCommit(cwd, ref);
|
||||
return commit !== null;
|
||||
}
|
||||
|
||||
async ensureRootCheckpoint(input: { cwd: string; threadId: string }): Promise<boolean> {
|
||||
const { cwd, threadId } = input;
|
||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const existing = await this.resolveCheckpointCommit(cwd, rootRef);
|
||||
if (existing) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const headCommit = await this.resolveHeadCommit(cwd);
|
||||
if (!headCommit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["update-ref", rootRef, headCommit]);
|
||||
return true;
|
||||
}
|
||||
|
||||
async restoreCheckpoint(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
let commitOid = await this.resolveCheckpointCommit(cwd, ref);
|
||||
if (!commitOid && turnCount === 0) {
|
||||
commitOid = await this.resolveHeadCommit(cwd);
|
||||
}
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
|
||||
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
|
||||
if (await this.hasHeadCommit(cwd)) {
|
||||
await this.runGit(cwd, ["reset", "--quiet", "--", "."]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async diffCheckpoints(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
fromTurnCount: number;
|
||||
toTurnCount: number;
|
||||
}): Promise<string> {
|
||||
const { cwd, threadId, fromTurnCount, toTurnCount } = input;
|
||||
if (!Number.isInteger(fromTurnCount) || fromTurnCount < 0) {
|
||||
throw new Error(`Invalid from turn count: ${fromTurnCount}`);
|
||||
}
|
||||
if (!Number.isInteger(toTurnCount) || toTurnCount < 0) {
|
||||
throw new Error(`Invalid to turn count: ${toTurnCount}`);
|
||||
}
|
||||
if (fromTurnCount > toTurnCount) {
|
||||
throw new Error(`Invalid checkpoint range: ${fromTurnCount}..${toTurnCount}`);
|
||||
}
|
||||
|
||||
const fromRef = checkpointRefForThreadTurn(threadId, fromTurnCount);
|
||||
const toRef = checkpointRefForThreadTurn(threadId, toTurnCount);
|
||||
let fromCommitOid = await this.resolveCheckpointCommit(cwd, fromRef);
|
||||
const toCommitOid = await this.resolveCheckpointCommit(cwd, toRef);
|
||||
if (!fromCommitOid && fromTurnCount === 0) {
|
||||
const headCommit = await this.resolveHeadCommit(cwd);
|
||||
if (headCommit) {
|
||||
fromCommitOid = headCommit;
|
||||
}
|
||||
}
|
||||
if (!fromCommitOid) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${fromTurnCount} in thread ${threadId}.`,
|
||||
);
|
||||
}
|
||||
if (!toCommitOid) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${toTurnCount} in thread ${threadId}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await this.runGit(cwd, [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
]);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
private async resolveHeadCommit(cwd: string): Promise<string | null> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}
|
||||
|
||||
async pruneAfterTurn(input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
maxTurnCount: number;
|
||||
}): Promise<void> {
|
||||
const { cwd, threadId, maxTurnCount } = input;
|
||||
if (!Number.isInteger(maxTurnCount) || maxTurnCount < 0) {
|
||||
throw new Error(`Invalid max turn count: ${maxTurnCount}`);
|
||||
}
|
||||
|
||||
const threadRefPrefix = `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/`;
|
||||
const result = await this.runGit(
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname)", threadRefPrefix],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
if (result.code !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refsToDelete = result.stdout
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.filter((refName) => {
|
||||
const turn = this.readRefTurnCount(refName);
|
||||
return turn !== null && turn > maxTurnCount;
|
||||
});
|
||||
|
||||
const batchSize = 32;
|
||||
const batches = Array.from(
|
||||
{ length: Math.ceil(refsToDelete.length / batchSize) },
|
||||
(_, index) => refsToDelete.slice(index * batchSize, (index + 1) * batchSize),
|
||||
);
|
||||
await batches.reduce<Promise<void>>((pending, batch) => {
|
||||
return pending.then(async () => {
|
||||
await Promise.all(
|
||||
batch.map((refName) =>
|
||||
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
|
||||
),
|
||||
);
|
||||
});
|
||||
}, Promise.resolve());
|
||||
}
|
||||
|
||||
private async hasHeadCommit(cwd: string): Promise<boolean> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "HEAD"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0;
|
||||
}
|
||||
|
||||
private async resolveCheckpointCommit(cwd: string, ref: string): Promise<string | null> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}
|
||||
|
||||
private readRefTurnCount(ref: string): number | null {
|
||||
const segments = ref.split("/");
|
||||
const rawTurn = segments.at(-1);
|
||||
if (!rawTurn) {
|
||||
return null;
|
||||
}
|
||||
const turn = Number.parseInt(rawTurn, 10);
|
||||
return Number.isInteger(turn) && turn >= 0 ? turn : null;
|
||||
}
|
||||
|
||||
private async runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: GitOptions = {},
|
||||
): Promise<Awaited<ReturnType<typeof runProcess>>> {
|
||||
let result: Awaited<ReturnType<typeof runProcess>>;
|
||||
try {
|
||||
result = await runProcess("git", args, {
|
||||
cwd,
|
||||
env: options.env,
|
||||
stdin: options.stdin,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to run ${quoteGitCommand(args)}: ${message}`, { cause: error });
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new Error(`${quoteGitCommand(args)} timed out.`);
|
||||
}
|
||||
|
||||
if (result.stdoutTruncated || result.stderrTruncated) {
|
||||
throw new Error(
|
||||
`${quoteGitCommand(args)} output exceeded ${DEFAULT_MAX_OUTPUT_BYTES} bytes and was truncated.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!options.allowNonZeroExit && result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
throw new Error(
|
||||
stderr.length > 0
|
||||
? `${quoteGitCommand(args)} failed: ${stderr}`
|
||||
: `${quoteGitCommand(args)} failed with code ${result.code ?? "null"}.`,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -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,930 @@
|
||||
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("refreshes upstream behind count after checkout when remote branch advanced", 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 defaultBranch = (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 ${defaultBranch}`);
|
||||
|
||||
const featureBranch = "feature-behind";
|
||||
await createGitBranch({ cwd: source.path, branch: featureBranch });
|
||||
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
|
||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
||||
await git(source.path, "add feature.txt");
|
||||
await git(source.path, "commit -m 'feature base'");
|
||||
await git(source.path, `push -u origin ${featureBranch}`);
|
||||
await checkoutGitBranch({ cwd: source.path, branch: defaultBranch });
|
||||
|
||||
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 git(clone.path, `checkout -b ${featureBranch} --track origin/${featureBranch}`);
|
||||
await writeFile(path.join(clone.path, "feature.txt"), "feature from remote\n");
|
||||
await git(clone.path, "add feature.txt");
|
||||
await git(clone.path, "commit -m 'remote feature update'");
|
||||
await git(clone.path, `push origin ${featureBranch}`);
|
||||
|
||||
await checkoutGitBranch({ cwd: source.path, branch: featureBranch });
|
||||
const core = new GitCoreService();
|
||||
await vi.waitFor(async () => {
|
||||
const details = await core.statusDetails(source.path);
|
||||
expect(details.branch).toBe(featureBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps checkout successful when upstream refresh fails", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const defaultBranch = (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 ${defaultBranch}`);
|
||||
|
||||
const featureBranch = "feature-refresh-failure";
|
||||
await git(source.path, `branch ${featureBranch}`);
|
||||
await git(source.path, `checkout ${featureBranch}`);
|
||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
||||
await git(source.path, "add feature.txt");
|
||||
await git(source.path, "commit -m 'feature base'");
|
||||
await git(source.path, `push -u origin ${featureBranch}`);
|
||||
await git(source.path, `checkout ${defaultBranch}`);
|
||||
|
||||
class RefreshFailingGitCoreService extends GitCoreService {
|
||||
refreshFetchAttempts = 0;
|
||||
|
||||
override async git(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Promise<void> {
|
||||
if (args[0] === "fetch") {
|
||||
this.refreshFetchAttempts += 1;
|
||||
throw new Error("simulated fetch timeout");
|
||||
}
|
||||
await super.git(cwd, args, allowNonZeroExit);
|
||||
}
|
||||
}
|
||||
|
||||
const core = new RefreshFailingGitCoreService();
|
||||
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
|
||||
undefined,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(core.refreshFetchAttempts).toBe(1);
|
||||
});
|
||||
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
|
||||
});
|
||||
|
||||
it("refresh fetch is scoped to the checked out branch upstream refspec", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const defaultBranch = (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 ${defaultBranch}`);
|
||||
|
||||
const featureBranch = "feature/scoped-fetch";
|
||||
await git(source.path, `checkout -b ${featureBranch}`);
|
||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
||||
await git(source.path, "add feature.txt");
|
||||
await git(source.path, "commit -m 'feature base'");
|
||||
await git(source.path, `push -u origin ${featureBranch}`);
|
||||
await git(source.path, `checkout ${defaultBranch}`);
|
||||
|
||||
class FetchRecordingGitCoreService extends GitCoreService {
|
||||
fetchArgs: readonly string[] | null = null;
|
||||
|
||||
override async git(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Promise<void> {
|
||||
if (args[0] === "fetch") {
|
||||
this.fetchArgs = args;
|
||||
return;
|
||||
}
|
||||
await super.git(cwd, args, allowNonZeroExit);
|
||||
}
|
||||
}
|
||||
|
||||
const core = new FetchRecordingGitCoreService();
|
||||
await core.checkoutBranch({ cwd: source.path, branch: featureBranch });
|
||||
await vi.waitFor(() => {
|
||||
expect(core.fetchArgs).not.toBeNull();
|
||||
});
|
||||
|
||||
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
|
||||
expect(core.fetchArgs).toEqual([
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns checkout result before background upstream refresh completes", async () => {
|
||||
await using remote = await makeTmpDir();
|
||||
await using source = await makeTmpDir();
|
||||
await git(remote.path, "init --bare");
|
||||
|
||||
await initRepoWithCommit(source.path);
|
||||
const defaultBranch = (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 ${defaultBranch}`);
|
||||
|
||||
const featureBranch = "feature/background-refresh";
|
||||
await git(source.path, `checkout -b ${featureBranch}`);
|
||||
await writeFile(path.join(source.path, "feature.txt"), "feature base\n");
|
||||
await git(source.path, "add feature.txt");
|
||||
await git(source.path, "commit -m 'feature base'");
|
||||
await git(source.path, `push -u origin ${featureBranch}`);
|
||||
await git(source.path, `checkout ${defaultBranch}`);
|
||||
|
||||
class SlowRefreshGitCoreService extends GitCoreService {
|
||||
fetchStarted = false;
|
||||
private readonly waitForReleasePromise: Promise<void>;
|
||||
private releaseWait: () => void = () => undefined;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.waitForReleasePromise = new Promise<void>((resolve) => {
|
||||
this.releaseWait = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
releaseFetch(): void {
|
||||
this.releaseWait();
|
||||
}
|
||||
|
||||
override async git(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Promise<void> {
|
||||
if (args[0] === "fetch") {
|
||||
this.fetchStarted = true;
|
||||
await this.waitForReleasePromise;
|
||||
return;
|
||||
}
|
||||
await super.git(cwd, args, allowNonZeroExit);
|
||||
}
|
||||
}
|
||||
|
||||
const core = new SlowRefreshGitCoreService();
|
||||
await expect(core.checkoutBranch({ cwd: source.path, branch: featureBranch })).resolves.toBe(
|
||||
undefined,
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(core.fetchStarted).toBe(true);
|
||||
});
|
||||
expect(await git(source.path, "branch --show-current")).toBe(featureBranch);
|
||||
core.releaseFetch();
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it("removeGitWorktree force removes a dirty worktree", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
|
||||
const wtPath = path.join(tmp.path, "wt-dirty-dir");
|
||||
const currentBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(b) => b.current,
|
||||
)!.name;
|
||||
|
||||
await createGitWorktree({
|
||||
cwd: tmp.path,
|
||||
branch: currentBranch,
|
||||
newBranch: "wt-dirty",
|
||||
path: wtPath,
|
||||
});
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
|
||||
await writeFile(path.join(wtPath, "README.md"), "dirty change\n");
|
||||
|
||||
await expect(removeGitWorktree({ cwd: tmp.path, path: wtPath })).rejects.toThrow();
|
||||
expect(existsSync(wtPath)).toBe(true);
|
||||
|
||||
await removeGitWorktree({ cwd: tmp.path, path: wtPath, force: true });
|
||||
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("includes command context when worktree removal fails", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
const missingWorktreePath = path.join(tmp.path, "missing-worktree");
|
||||
|
||||
const error = await core
|
||||
.removeWorktree({ cwd: tmp.path, path: missingWorktreePath })
|
||||
.then(() => null)
|
||||
.catch((err: unknown) => err);
|
||||
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
const message = (error as Error).message;
|
||||
expect(message).toContain("git worktree remove");
|
||||
expect(message).toContain(`cwd: ${tmp.path}`);
|
||||
expect(message).toContain(missingWorktreePath);
|
||||
});
|
||||
|
||||
it("refreshes upstream before statusDetails so behind count reflects remote updates", 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 git(clone.path, `checkout -B ${initialBranch} --track origin/${initialBranch}`);
|
||||
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 details = await core.statusDetails(source.path);
|
||||
expect(details.branch).toBe(initialBranch);
|
||||
expect(details.aheadCount).toBe(0);
|
||||
expect(details.behindCount).toBe(1);
|
||||
});
|
||||
|
||||
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,740 @@
|
||||
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;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL_MS = 15_000;
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT_MS = 5_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 {
|
||||
private readonly lastUpstreamRefreshAt = new Map<string, number>();
|
||||
|
||||
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> {
|
||||
await this.refreshStatusUpstreamIfStale(cwd).catch(() => undefined);
|
||||
|
||||
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> {
|
||||
const args = ["worktree", "remove"];
|
||||
if (input.force) {
|
||||
args.push("--force");
|
||||
}
|
||||
args.push(input.path);
|
||||
try {
|
||||
await executeGit(input.cwd, args, {
|
||||
timeoutMs: 15_000,
|
||||
fallbackErrorMessage: "git worktree remove failed",
|
||||
});
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`${commandLabel(args)} failed (cwd: ${input.cwd}): ${detail}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async createBranch(input: GitCreateBranchInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
});
|
||||
}
|
||||
|
||||
private async resolveCurrentUpstream(
|
||||
cwd: string,
|
||||
): Promise<{ upstreamRef: string; remoteName: string; upstreamBranch: string } | null> {
|
||||
const upstreamRef = trimStdout(
|
||||
await this.gitStdout(
|
||||
cwd,
|
||||
["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
|
||||
true,
|
||||
),
|
||||
);
|
||||
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) {
|
||||
return null;
|
||||
}
|
||||
if (upstreamBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
upstreamRef,
|
||||
remoteName,
|
||||
upstreamBranch,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchUpstreamRef(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await this.git(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], true);
|
||||
}
|
||||
|
||||
private async fetchUpstreamRefForStatus(
|
||||
cwd: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Promise<void> {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
await executeGit(cwd, ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], {
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: STATUS_UPSTREAM_REFRESH_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
private async refreshStatusUpstreamIfStale(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheKey = `${cwd}\u0000${upstream.upstreamRef}`;
|
||||
const now = Date.now();
|
||||
const lastRefreshAt = this.lastUpstreamRefreshAt.get(cacheKey) ?? 0;
|
||||
if (now - lastRefreshAt < STATUS_UPSTREAM_REFRESH_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Record attempt time first to avoid repeated fetch spikes when status is polled often.
|
||||
this.lastUpstreamRefreshAt.set(cacheKey, now);
|
||||
await this.fetchUpstreamRefForStatus(cwd, upstream);
|
||||
}
|
||||
|
||||
private async refreshCheckedOutBranchUpstream(cwd: string): Promise<void> {
|
||||
const upstream = await this.resolveCurrentUpstream(cwd);
|
||||
if (!upstream) {
|
||||
return;
|
||||
}
|
||||
await this.fetchUpstreamRef(cwd, upstream);
|
||||
}
|
||||
|
||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["checkout", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
void this.refreshCheckedOutBranchUpstream(input.cwd).catch(() => undefined);
|
||||
}
|
||||
|
||||
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,516 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
|
||||
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
|
||||
CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
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" = "--image" ]; then',
|
||||
" shift",
|
||||
' if [ -n "$1" ]; then',
|
||||
' seen_image="1"',
|
||||
" fi",
|
||||
" continue",
|
||||
" fi",
|
||||
' if [ "$1" = "--output-last-message" ]; then',
|
||||
" shift",
|
||||
' output_path="$1"',
|
||||
" fi",
|
||||
" shift",
|
||||
"done",
|
||||
'stdin_content="$(cat)"',
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||
' printf "%s\\n" "missing --image input" >&2',
|
||||
" exit 2",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
" exit 3",
|
||||
" }",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
|
||||
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||
' printf "%s\\n" "stdin contained forbidden content" >&2',
|
||||
" exit 4",
|
||||
" fi",
|
||||
"fi",
|
||||
'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;
|
||||
requireImage?: boolean;
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: 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;
|
||||
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (input.requireImage) {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
}
|
||||
|
||||
if (input.stdinMustContain !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
}
|
||||
|
||||
if (input.stdinMustNotContain !== undefined) {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousRequireImage,
|
||||
previousStdinMustContain,
|
||||
previousStdinMustNotContain,
|
||||
};
|
||||
}),
|
||||
() => 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;
|
||||
}
|
||||
|
||||
if (previous.previousRequireImage === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustContain === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustNotContain === undefined) {
|
||||
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||
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",
|
||||
}),
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
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");
|
||||
expect(generated.branch).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
branch: "fix/important-system-change",
|
||||
}),
|
||||
stdinMustContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
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",
|
||||
includeBranch: true,
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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("generates branch names and normalizes branch fragments", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: " Feat/Session ",
|
||||
}),
|
||||
stdinMustNotContain: "Image attachments supplied to the model",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Please update session handling.",
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("feat/session");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/session-timeout",
|
||||
}),
|
||||
stdinMustNotContain: "Attachment metadata:",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix timeout behavior.",
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/session-timeout");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("passes image attachments through as codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
stdinMustContain: "Attachment metadata:",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const attachmentId =
|
||||
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() =>
|
||||
fs.stat(imagePath).pipe(
|
||||
Effect.map((fileInfo) => {
|
||||
expect(fileInfo.type).toBe("File");
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(
|
||||
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
);
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores missing attachment ids for codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: missingAttachmentId,
|
||||
name: "outside.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.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("missing --image input");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"fails with typed TextGenerationError when codex returns wrong branch payload shape",
|
||||
() =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: "This is not a branch payload",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix websocket reconnect flake",
|
||||
})
|
||||
.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 returned invalid structured output");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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,467 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type BranchNameGenerationResult,
|
||||
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;
|
||||
|
||||
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
|
||||
const document = Schema.toJsonSchemaDocument(schema);
|
||||
if (document.definitions && Object.keys(document.definitions).length > 0) {
|
||||
return {
|
||||
...document.schema,
|
||||
$defs: document.definitions,
|
||||
};
|
||||
}
|
||||
return document.schema;
|
||||
}
|
||||
|
||||
function normalizeCodexError(
|
||||
operation: string,
|
||||
error: unknown,
|
||||
fallback: string,
|
||||
): TextGenerationError {
|
||||
if (Schema.is(TextGenerationError)(error)) {
|
||||
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 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 serverConfig = yield* Effect.service(ServerConfig);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): 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 materializeImageAttachments = (
|
||||
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
imagePaths.push(resolvedPath);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
|
||||
const runCodexJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toCodexOutputJsonSchema(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,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
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(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
{
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
wantsBranch
|
||||
? "Return a JSON object with keys: subject, body, branch."
|
||||
: "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",
|
||||
...(wantsBranch
|
||||
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||
: []),
|
||||
"- 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 outputSchemaJson = wantsBranch
|
||||
? Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
branch: Schema.String,
|
||||
})
|
||||
: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
});
|
||||
|
||||
return runCodexJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
({
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
}) 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: Schema.Struct({
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
({
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
}) satisfies PrContentGenerationResult,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||
return Effect.gen(function* () {
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateBranchName",
|
||||
input.attachments,
|
||||
);
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) =>
|
||||
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
);
|
||||
|
||||
const promptSections = [
|
||||
"You generate concise git branch names.",
|
||||
"Return a JSON object with key: branch.",
|
||||
"Rules:",
|
||||
"- Branch should describe the requested work from the user message.",
|
||||
"- Keep it short and specific (2-6 words).",
|
||||
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||
"",
|
||||
"User message:",
|
||||
limitSection(input.message, 8_000),
|
||||
];
|
||||
if (attachmentLines.length > 0) {
|
||||
promptSections.push(
|
||||
"",
|
||||
"Attachment metadata:",
|
||||
limitSection(attachmentLines.join("\n"), 4_000),
|
||||
);
|
||||
}
|
||||
const prompt = promptSections.join("\n");
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
branch: Schema.String,
|
||||
}),
|
||||
imagePaths,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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,927 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { GitCommandError, 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?: GitHubCliError;
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||
generateBranchName: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||
}
|
||||
|
||||
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 },
|
||||
GitCommandError,
|
||||
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, PlatformError.PlatformError | GitCommandError, 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,
|
||||
PlatformError.PlatformError | GitCommandError,
|
||||
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: (input) =>
|
||||
Effect.succeed({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
}),
|
||||
generatePrContent: () =>
|
||||
Effect.succeed({
|
||||
title: "Add stacked git actions",
|
||||
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
||||
}),
|
||||
generateBranchName: () =>
|
||||
Effect.succeed({
|
||||
branch: "update-workflow",
|
||||
}),
|
||||
...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 } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
generateBranchName: (input) =>
|
||||
implementation.generateBranchName(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "fake text generation failed",
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
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(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;
|
||||
featureBranch?: boolean;
|
||||
},
|
||||
) {
|
||||
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 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.pr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns merged PR state when latest PR was merged", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-merged-pr",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-30T10:00:00Z",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-merged-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-merged-pr",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 45,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-31T10:00:00Z",
|
||||
updatedAt: "2026-02-01T10:00:00Z",
|
||||
},
|
||||
{
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||
expect(status.pr).toEqual({
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-over-merged",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns pr 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 GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.pr).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.branch.status).toBe("skipped_not_requested");
|
||||
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: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
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("creates feature branch, commits, and pushes with featureBranch option", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
featureBranch: true,
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("feature/implement-stacked-git-actions");
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
expect(generatedCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("featureBranch uses custom commit message and derives branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "unused",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/feat-custom-summary-line");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
}),
|
||||
);
|
||||
|
||||
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.branch.status).toBe("skipped_not_requested");
|
||||
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("featureBranch returns error when worktree is clean", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
|
||||
expect(errorMessage).toContain("no changes to commit");
|
||||
}),
|
||||
);
|
||||
|
||||
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.branch.status).toBe("skipped_not_requested");
|
||||
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(
|
||||
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 77,
|
||||
title: "Add no-upstream PR flow",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/no-upstream-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("origin/feature/no-upstream-pr");
|
||||
expect(
|
||||
ghCalls.some((call) =>
|
||||
call.includes("pr create --base main --head feature/no-upstream-pr"),
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
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.branch.status).toBe("skipped_not_requested");
|
||||
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.branch.status).toBe("skipped_not_requested");
|
||||
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.branch.status).toBe("skipped_not_requested");
|
||||
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.message),
|
||||
);
|
||||
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 GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
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 GitHubCliError({
|
||||
operation: "execute",
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
expect(errorMessage).toContain("gh auth login");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,543 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
interface PullRequestInfo extends OpenPrInfo {
|
||||
state: "open" | "closed" | "merged";
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
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;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
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;
|
||||
branch?: string | undefined;
|
||||
}): {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
} {
|
||||
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(),
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
interface CommitAndBranchSuggestion {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
commitMessage: string;
|
||||
}
|
||||
|
||||
function formatCommitMessage(subject: string, body: string): string {
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length === 0) {
|
||||
return subject;
|
||||
}
|
||||
return `${subject}\n\n${trimmedBody}`;
|
||||
}
|
||||
|
||||
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 toStatusPr(pr: PullRequestInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
state: "open" | "closed" | "merged";
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
state: pr.state,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
state: "open",
|
||||
updatedAt: null,
|
||||
} satisfies PullRequestInfo;
|
||||
}),
|
||||
);
|
||||
|
||||
const findLatestPr = (cwd: string, branch: string) =>
|
||||
Effect.gen(function* () {
|
||||
const stdout = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"20",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.map((result) => result.stdout));
|
||||
|
||||
const raw = stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
|
||||
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
|
||||
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||
return right - left;
|
||||
});
|
||||
|
||||
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||
if (latestOpenPr) {
|
||||
return latestOpenPr;
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
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 resolveCommitAndBranchSuggestion = (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
commitMessage?: string;
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd);
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
|
||||
if (customCommit) {
|
||||
return {
|
||||
subject: customCommit.subject,
|
||||
body: customCommit.body,
|
||||
...(input.includeBranch
|
||||
? { branch: sanitizeFeatureBranchName(customCommit.subject) }
|
||||
: {}),
|
||||
commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
|
||||
};
|
||||
}
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: input.cwd,
|
||||
branch: input.branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
return {
|
||||
subject: generated.subject,
|
||||
body: generated.body,
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
commitMessage: formatCommitMessage(generated.subject, generated.body),
|
||||
};
|
||||
});
|
||||
|
||||
const runCommitStep = (
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
preResolvedSuggestion ??
|
||||
(yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
subject: suggestion.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 pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((latest) => (latest ? toStatusPr(latest) : 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,
|
||||
pr,
|
||||
};
|
||||
});
|
||||
|
||||
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
includeBranch: true,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
"runFeatureBranchStep",
|
||||
"Cannot create a feature branch because there are no changes to commit.",
|
||||
);
|
||||
}
|
||||
|
||||
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
|
||||
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||
|
||||
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||
|
||||
return {
|
||||
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||
resolvedCommitMessage: suggestion.commitMessage,
|
||||
resolvedCommitSuggestion: suggestion,
|
||||
};
|
||||
});
|
||||
|
||||
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 (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
if (input.featureBranch) {
|
||||
const result = yield* runFeatureBranchStep(
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
status,
|
||||
runStackedAction,
|
||||
} satisfies GitManagerShape;
|
||||
});
|
||||
|
||||
export const GitManagerLive = Layer.effect(GitManager, makeGitManager);
|
||||
@@ -1,59 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, Layer, Schema } 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(Schema.is(GitCommandError)(result.failure));
|
||||
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, Schema, 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) =>
|
||||
Schema.is(GitCommandError)(cause)
|
||||
? 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* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
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,172 +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, Scope } 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, "pr"> {
|
||||
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;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchInput {
|
||||
cwd: string;
|
||||
oldBranch: string;
|
||||
newBranch: string;
|
||||
}
|
||||
|
||||
export interface GitRenameBranchResult {
|
||||
branch: 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 + remote 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>;
|
||||
|
||||
/**
|
||||
* Rename an existing local branch.
|
||||
*/
|
||||
readonly renameBranch: (
|
||||
input: GitRenameBranchInput,
|
||||
) => Effect.Effect<GitRenameBranchResult, 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, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Initialize a repository in the provided directory.
|
||||
*/
|
||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branch names (short format).
|
||||
*/
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitCore - Service tag for low-level Git repository operations.
|
||||
*/
|
||||
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(
|
||||
"t3/git/Services/GitCore",
|
||||
) {}
|
||||
@@ -1,68 +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>()(
|
||||
"t3/git/Services/GitHubCli",
|
||||
) {}
|
||||
@@ -1,44 +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`).
|
||||
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||
*/
|
||||
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/Services/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>()(
|
||||
"t3/git/Services/GitService",
|
||||
) {}
|
||||
@@ -1,94 +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 { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import type { TextGenerationError } from "../Errors.ts";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
subject: string;
|
||||
body: string;
|
||||
/** Only present when `includeBranch` was set on the input. */
|
||||
branch?: string | undefined;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationInput {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface BranchNameGenerationInput {
|
||||
cwd: string;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
export interface BranchNameGenerationResult {
|
||||
branch: string;
|
||||
}
|
||||
|
||||
export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult>;
|
||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>;
|
||||
|
||||
/**
|
||||
* Generate a concise branch name from a user message.
|
||||
*/
|
||||
readonly generateBranchName: (
|
||||
input: BranchNameGenerationInput,
|
||||
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
*/
|
||||
export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
|
||||
"t3/git/Services/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."))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
describe("imageMime", () => {
|
||||
it("parses base64 data URL with mime type", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses base64 data URL with mime parameters", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-base64 data URL", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing mime type", () => {
|
||||
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
|
||||
});
|
||||
|
||||
it("parses base64 data URL with spaces in payload", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not read inherited keys from mime extension map", () => {
|
||||
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
|
||||
});
|
||||
});
|
||||
@@ -1,79 +0,0 @@
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
|
||||
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
||||
"image/avif": ".avif",
|
||||
"image/bmp": ".bmp",
|
||||
"image/gif": ".gif",
|
||||
"image/heic": ".heic",
|
||||
"image/heif": ".heif",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/svg+xml": ".svg",
|
||||
"image/tiff": ".tiff",
|
||||
"image/webp": ".webp",
|
||||
};
|
||||
|
||||
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||
".avif",
|
||||
".bmp",
|
||||
".gif",
|
||||
".heic",
|
||||
".heif",
|
||||
".ico",
|
||||
".jpeg",
|
||||
".jpg",
|
||||
".png",
|
||||
".svg",
|
||||
".tiff",
|
||||
".webp",
|
||||
]);
|
||||
|
||||
export function parseBase64DataUrl(
|
||||
dataUrl: string,
|
||||
): { readonly mimeType: string; readonly base64: string } | null {
|
||||
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const headerParts = (match[1] ?? "")
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
if (headerParts.length < 2) {
|
||||
return null;
|
||||
}
|
||||
const trailingToken = headerParts.at(-1)?.toLowerCase();
|
||||
if (trailingToken !== "base64") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mimeType = headerParts[0]?.toLowerCase();
|
||||
const base64 = match[2]?.replace(/\s+/g, "");
|
||||
if (!mimeType || !base64) return null;
|
||||
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
|
||||
const key = input.mimeType.toLowerCase();
|
||||
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
|
||||
? IMAGE_EXTENSION_BY_MIME_TYPE[key]
|
||||
: undefined;
|
||||
if (fromMime) {
|
||||
return fromMime;
|
||||
}
|
||||
|
||||
const fromMimeExtension = Mime.getExtension(input.mimeType);
|
||||
if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
|
||||
return fromMimeExtension;
|
||||
}
|
||||
|
||||
const fileName = input.fileName?.trim() ?? "";
|
||||
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
|
||||
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
|
||||
if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
|
||||
return fileNameExtension;
|
||||
}
|
||||
|
||||
return ".bin";
|
||||
}
|
||||
+185
-18
@@ -1,21 +1,188 @@
|
||||
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 "@t3tools/shared/Net";
|
||||
import { fixPath } from "./fixPath";
|
||||
import { createLogger } from "./logger";
|
||||
import { PersistenceService } from "./persistenceService";
|
||||
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()));
|
||||
}
|
||||
|
||||
function resolveStateDbPath(raw: string | undefined): string {
|
||||
if (!raw || raw.trim().length === 0) {
|
||||
return path.join(os.homedir(), ".t3", "state.sqlite");
|
||||
}
|
||||
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 legacyStateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const stateDbPath = resolveStateDbPath(process.env.T3CODE_STATE_DB_PATH);
|
||||
const persistenceService = new PersistenceService({
|
||||
dbPath: stateDbPath,
|
||||
legacyProjectsJsonPath: path.join(legacyStateDir, "projects.json"),
|
||||
});
|
||||
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,
|
||||
persistenceService,
|
||||
authToken,
|
||||
});
|
||||
await server.start();
|
||||
|
||||
const url = `http://localhost:${port}`;
|
||||
logger.info("T3 Code running", {
|
||||
url,
|
||||
cwd,
|
||||
mode,
|
||||
stateDbPath,
|
||||
legacyStateDir,
|
||||
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);
|
||||
});
|
||||
+190
-455
@@ -1,490 +1,225 @@
|
||||
import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
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 fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { assert, afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
Keybindings,
|
||||
KeybindingsConfigError,
|
||||
KeybindingsLive,
|
||||
ResolvedKeybindingFromConfig,
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
upsertKeybindingRule,
|
||||
} 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;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
describe("server keybindings", () => {
|
||||
const tempDirs: string[] = [];
|
||||
const logger = {
|
||||
warn: vi.fn(),
|
||||
};
|
||||
|
||||
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
|
||||
effect.pipe(
|
||||
Effect.mapError((error) => error.detail),
|
||||
Effect.result,
|
||||
);
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
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);
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
logger.warn.mockReset();
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
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("parses shortcuts including plus key", () => {
|
||||
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.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) => String(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));
|
||||
it("compiles valid rule with parsed when AST", () => {
|
||||
const compiled = compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalOpen && !terminalFocus",
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+j", command: "script.custom-action.run" },
|
||||
]);
|
||||
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" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
yield* keybindings.syncDefaultKeybindingsOnStartup;
|
||||
});
|
||||
it("rejects invalid rules", () => {
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+shift+d+o",
|
||||
command: "terminal.new",
|
||||
}),
|
||||
);
|
||||
|
||||
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.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: "terminalFocus && (",
|
||||
}),
|
||||
);
|
||||
|
||||
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 }),
|
||||
),
|
||||
),
|
||||
assert.isNull(
|
||||
compileResolvedKeybindingRule({
|
||||
key: "mod+d",
|
||||
command: "terminal.split",
|
||||
when: `${"!".repeat(300)}terminalFocus`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("upserts custom keybindings to configured path", () =>
|
||||
Effect.gen(function* () {
|
||||
const { keybindingsConfigPath } = yield* ServerConfig;
|
||||
yield* writeKeybindingsConfig(keybindingsConfigPath, [
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
]);
|
||||
it("upserts custom keybindings to ~/.t3/keybindings.json", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
const resolved = yield* Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings;
|
||||
return yield* keybindings.upsertKeybindingRule({
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
});
|
||||
const resolved = upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
});
|
||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
|
||||
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
|
||||
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
|
||||
expect(persisted).toEqual([
|
||||
{ key: "mod+j", command: "terminal.toggle" },
|
||||
{ key: "mod+shift+r", command: "script.run-tests.run" },
|
||||
]);
|
||||
expect(resolved.some((entry) => entry.command === "script.run-tests.run")).toBe(true);
|
||||
});
|
||||
|
||||
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("replaces existing custom keybinding for the same command", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-upsert-replace-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
JSON.stringify([{ key: "mod+r", command: "script.run-tests.run" }]),
|
||||
"utf8",
|
||||
);
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
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",
|
||||
});
|
||||
});
|
||||
upsertKeybindingRule(logger, {
|
||||
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())),
|
||||
);
|
||||
const persisted = JSON.parse(fs.readFileSync(configPath, "utf8")) as Array<{
|
||||
key: string;
|
||||
command: string;
|
||||
}>;
|
||||
expect(persisted).toEqual([{ key: "mod+shift+r", command: "script.run-tests.run" }]);
|
||||
});
|
||||
|
||||
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");
|
||||
it("refuses to overwrite malformed keybindings config", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-malformed-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, "{ not-json", "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
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");
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(/Unable to parse keybindings config/);
|
||||
|
||||
const persistedRaw = yield* fs.readFileString(keybindingsConfigPath);
|
||||
assert.equal(persistedRaw, "{ not-json");
|
||||
}).pipe(Effect.provide(makeKeybindingsLayer())),
|
||||
);
|
||||
expect(fs.readFileSync(configPath, "utf8")).toBe("{ not-json");
|
||||
});
|
||||
|
||||
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"}',
|
||||
);
|
||||
it("reports non-array config parse errors without duplicate prefix", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-non-array-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, JSON.stringify({ key: "mod+j", command: "terminal.toggle" }), "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
|
||||
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");
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(new RegExp(`Unable to parse keybindings config at ${configPath}: 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())),
|
||||
);
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).not.toThrow(
|
||||
new RegExp(`Unable to parse keybindings config at ${configPath}: Unable to parse keybindings config at`),
|
||||
);
|
||||
});
|
||||
|
||||
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);
|
||||
it("cleans up temp files when atomic keybinding write fails", () => {
|
||||
const fakeHome = makeTempDir("t3code-keybindings-atomic-");
|
||||
const configDir = path.join(fakeHome, ".t3");
|
||||
fs.mkdirSync(configDir, { recursive: true });
|
||||
const configPath = path.join(configDir, "keybindings.json");
|
||||
fs.writeFileSync(configPath, JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]), "utf8");
|
||||
vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||
vi.spyOn(fs, "renameSync").mockImplementation(() => {
|
||||
throw new Error("rename failed");
|
||||
});
|
||||
|
||||
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");
|
||||
expect(() =>
|
||||
upsertKeybindingRule(logger, {
|
||||
key: "mod+shift+r",
|
||||
command: "script.run-tests.run",
|
||||
}),
|
||||
).toThrow(/rename failed/);
|
||||
|
||||
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())),
|
||||
);
|
||||
expect(fs.readFileSync(configPath, "utf8")).toBe(
|
||||
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
|
||||
);
|
||||
const tempFiles = fs
|
||||
.readdirSync(configDir)
|
||||
.filter((file) => file.includes("keybindings.json.") && file.endsWith(".tmp"));
|
||||
expect(tempFiles).toEqual([]);
|
||||
});
|
||||
});
|
||||
+154
-550
@@ -1,55 +1,19 @@
|
||||
/**
|
||||
* Keybindings - Keybinding configuration service definitions.
|
||||
*
|
||||
* Owns parsing, validation, merge, and persistence of user keybinding
|
||||
* configuration consumed by the server runtime.
|
||||
*
|
||||
* @module Keybindings
|
||||
*/
|
||||
import {
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
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";
|
||||
import { keybindingRuleSchema } from "@t3tools/contracts";
|
||||
|
||||
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}`;
|
||||
}
|
||||
interface KeybindingsLogger {
|
||||
warn(message: string, context?: Record<string, unknown>): void;
|
||||
}
|
||||
|
||||
type WhenToken =
|
||||
@@ -60,12 +24,13 @@ type WhenToken =
|
||||
| { type: "lparen" }
|
||||
| { type: "rparen" };
|
||||
|
||||
const MAX_WHEN_EXPRESSION_DEPTH = 256;
|
||||
|
||||
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+d", command: "diff.toggle", 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" },
|
||||
@@ -78,7 +43,6 @@ function normalizeKeyToken(token: string): string {
|
||||
return token;
|
||||
}
|
||||
|
||||
/** @internal - Exported for testing */
|
||||
export function parseKeybindingShortcut(value: string): KeybindingShortcut | null {
|
||||
const rawTokens = value
|
||||
.toLowerCase()
|
||||
@@ -192,7 +156,7 @@ function tokenizeWhenExpression(expression: string): WhenToken[] | null {
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
|
||||
export function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {
|
||||
const tokens = tokenizeWhenExpression(expression);
|
||||
if (!tokens || tokens.length === 0) return null;
|
||||
let index = 0;
|
||||
@@ -277,13 +241,15 @@ function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode |
|
||||
return ast;
|
||||
}
|
||||
|
||||
/** @internal - Exported for testing */
|
||||
export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {
|
||||
const shortcut = parseKeybindingShortcut(rule.key);
|
||||
const key = rule.key.trim();
|
||||
if (key.length === 0) return null;
|
||||
const shortcut = parseKeybindingShortcut(key);
|
||||
if (!shortcut) return null;
|
||||
|
||||
if (rule.when !== undefined) {
|
||||
const whenAst = parseKeybindingWhenExpression(rule.when);
|
||||
const when = rule.when?.trim();
|
||||
if (when && when.length > 0) {
|
||||
const whenAst = parseKeybindingWhenExpression(when);
|
||||
if (!whenAst) return null;
|
||||
return {
|
||||
command: rule.command,
|
||||
@@ -301,148 +267,114 @@ export function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKey
|
||||
export function compileResolvedKeybindingsConfig(
|
||||
config: KeybindingsConfig,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const compiled: Mutable<ResolvedKeybindingsConfig> = [];
|
||||
const compiled: ResolvedKeybindingsConfig = [];
|
||||
for (const rule of config) {
|
||||
const result = Schema.decodeExit(ResolvedKeybindingFromConfig)(rule);
|
||||
if (result._tag === "Success") {
|
||||
compiled.push(result.value);
|
||||
}
|
||||
const resolved = compileResolvedKeybindingRule(rule);
|
||||
if (!resolved) continue;
|
||||
compiled.push(resolved);
|
||||
}
|
||||
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 compileDefaultKeybindings(): ResolvedKeybindingsConfig {
|
||||
const resolved: ResolvedKeybindingsConfig = [];
|
||||
for (const rule of DEFAULT_KEYBINDINGS) {
|
||||
const compiled = compileResolvedKeybindingRule(rule);
|
||||
if (!compiled) {
|
||||
throw new Error(`Invalid default keybinding: ${rule.command} (${rule.key})`);
|
||||
}
|
||||
resolved.push(compiled);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
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 ?? ""}`;
|
||||
}
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileDefaultKeybindings();
|
||||
const KEYBINDINGS_CONFIG_PATH = path.join(".t3", "keybindings.json");
|
||||
const MAX_KEYBINDINGS = 256;
|
||||
|
||||
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)})`;
|
||||
class KeybindingsConfigParseError extends Error {
|
||||
constructor(configPath: string, detail: string, options?: { cause?: unknown }) {
|
||||
super(`Unable to parse keybindings config at ${configPath}: ${detail}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
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[];
|
||||
function resolveKeybindingsConfigPath(): string {
|
||||
return path.join(os.homedir(), KEYBINDINGS_CONFIG_PATH);
|
||||
}
|
||||
|
||||
export interface KeybindingsChangeEvent {
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
function loadCustomKeybindingsConfig(
|
||||
logger: KeybindingsLogger,
|
||||
options?: {
|
||||
throwOnUnreadableConfig?: boolean;
|
||||
},
|
||||
): KeybindingsConfig {
|
||||
const configPath = resolveKeybindingsConfigPath();
|
||||
try {
|
||||
const raw = fs.readFileSync(configPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) {
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
throw new KeybindingsConfigParseError(configPath, "expected JSON array");
|
||||
}
|
||||
logger.warn("ignoring keybindings config with unsupported format; expected array", {
|
||||
path: configPath,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
const sanitized: KeybindingsConfig = [];
|
||||
let invalidEntries = 0;
|
||||
for (const entry of parsed) {
|
||||
const result = keybindingRuleSchema.safeParse(entry);
|
||||
if (result.success) {
|
||||
if (!compileResolvedKeybindingRule(result.data)) {
|
||||
invalidEntries += 1;
|
||||
continue;
|
||||
}
|
||||
sanitized.push(result.data);
|
||||
continue;
|
||||
}
|
||||
invalidEntries += 1;
|
||||
}
|
||||
if (invalidEntries > 0) {
|
||||
logger.warn("ignoring invalid keybinding entries", {
|
||||
path: configPath,
|
||||
invalidEntries,
|
||||
totalEntries: parsed.length,
|
||||
});
|
||||
}
|
||||
return sanitized;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
|
||||
return [];
|
||||
}
|
||||
if (options?.throwOnUnreadableConfig) {
|
||||
if (error instanceof KeybindingsConfigParseError) {
|
||||
throw error;
|
||||
}
|
||||
throw new KeybindingsConfigParseError(
|
||||
configPath,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
logger.warn("ignoring malformed keybindings config", {
|
||||
path: configPath,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
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 writeConfigAtomically(configPath: string, config: KeybindingsConfig): void {
|
||||
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
try {
|
||||
fs.writeFileSync(tempPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
|
||||
fs.renameSync(tempPath, configPath);
|
||||
} catch (error) {
|
||||
fs.rmSync(tempPath, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {
|
||||
@@ -456,388 +388,60 @@ function mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): Resolve
|
||||
);
|
||||
const merged = [...retainedDefaults, ...custom];
|
||||
|
||||
if (merged.length <= MAX_KEYBINDINGS_COUNT) {
|
||||
if (merged.length <= MAX_KEYBINDINGS) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// Keep the latest rules when the config exceeds max size; later rules have higher precedence.
|
||||
return merged.slice(-MAX_KEYBINDINGS_COUNT);
|
||||
return merged.slice(-MAX_KEYBINDINGS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>;
|
||||
export function loadResolvedKeybindingsConfig(
|
||||
logger: KeybindingsLogger,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const customConfig = loadCustomKeybindingsConfig(logger);
|
||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(customConfig);
|
||||
const overriddenCommands = new Set(compiledCustomConfig.map((entry) => entry.command));
|
||||
const mergedBeforeCapLength =
|
||||
DEFAULT_RESOLVED_KEYBINDINGS.filter((binding) => !overriddenCommands.has(binding.command))
|
||||
.length + compiledCustomConfig.length;
|
||||
const merged = mergeWithDefaultKeybindings(compiledCustomConfig);
|
||||
if (mergedBeforeCapLength > MAX_KEYBINDINGS) {
|
||||
logger.warn("truncating merged keybindings config to max entries", {
|
||||
path: resolveKeybindingsConfigPath(),
|
||||
maxEntries: MAX_KEYBINDINGS,
|
||||
});
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keybindings - Service tag for keybinding configuration operations.
|
||||
*/
|
||||
export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
|
||||
"t3/keybindings",
|
||||
) {}
|
||||
export function upsertKeybindingRule(
|
||||
logger: KeybindingsLogger,
|
||||
rawRule: unknown,
|
||||
): ResolvedKeybindingsConfig {
|
||||
const rule = keybindingRuleSchema.parse(rawRule);
|
||||
if (!compileResolvedKeybindingRule(rule)) {
|
||||
throw new Error(`Invalid keybinding shortcut: "${rule.key}"`);
|
||||
}
|
||||
|
||||
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 configPath = resolveKeybindingsConfigPath();
|
||||
const customConfig = loadCustomKeybindingsConfig(logger, {
|
||||
throwOnUnreadableConfig: true,
|
||||
});
|
||||
const nextConfig = [...customConfig.filter((entry) => entry.command !== rule.command), rule];
|
||||
const cappedConfig =
|
||||
nextConfig.length > MAX_KEYBINDINGS ? nextConfig.slice(-MAX_KEYBINDINGS) : nextConfig;
|
||||
|
||||
const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<
|
||||
{
|
||||
readonly keybindings: readonly KeybindingRule[];
|
||||
readonly issues: readonly ServerConfigIssue[];
|
||||
},
|
||||
KeybindingsConfigError
|
||||
> {
|
||||
if (!(yield* readConfigExists)) {
|
||||
return { keybindings: [], issues: [] };
|
||||
}
|
||||
if (nextConfig.length > MAX_KEYBINDINGS) {
|
||||
logger.warn("truncating keybindings config to max entries", {
|
||||
path: configPath,
|
||||
maxEntries: MAX_KEYBINDINGS,
|
||||
});
|
||||
}
|
||||
|
||||
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)],
|
||||
};
|
||||
}
|
||||
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
||||
writeConfigAtomically(configPath, cappedConfig);
|
||||
|
||||
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);
|
||||
const compiledCustomConfig = compileResolvedKeybindingsConfig(cappedConfig);
|
||||
return mergeWithDefaultKeybindings(compiledCustomConfig);
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
import * as Http from "node:http";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
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 { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
|
||||
import { 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, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(0),
|
||||
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" },
|
||||
) => {
|
||||
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||
Effect.provide(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_STATE_DIR: uniqueStateDir,
|
||||
...env,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resolvedConfig = null;
|
||||
start.mockImplementation(() => undefined);
|
||||
stop.mockImplementation(() => undefined);
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
it.layer(testLayer)("server CLI command", (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 { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
// Dummy comment.
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
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 { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
|
||||
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>()(
|
||||
"t3/main/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 resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
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 = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
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);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
keybindingsConfigPath,
|
||||
host,
|
||||
stateDir,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
|
||||
return config;
|
||||
}),
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
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;
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(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,222 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
isCommandAvailable,
|
||||
launchDetached,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open";
|
||||
import { Effect } from "effect";
|
||||
import { assertSuccess } from "@effect/vitest/utils";
|
||||
|
||||
describe("resolveEditorLaunch", () => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(cursorLaunch, {
|
||||
command: "cursor",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLaunch, {
|
||||
command: "code",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLaunch, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses --goto when editor supports line/column suffixes", () =>
|
||||
Effect.gen(function* () {
|
||||
const lineOnly = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineOnly, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
|
||||
});
|
||||
|
||||
const lineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(lineAndColumn, {
|
||||
command: "cursor",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeLineAndColumn, {
|
||||
command: "code",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(zedLineAndColumn, {
|
||||
command: "zed",
|
||||
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("isCommandAvailable", () => {
|
||||
function withTempDir(run: (dir: string) => void): void {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
|
||||
try {
|
||||
run(dir);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
it("resolves win32 commands with PATHEXT", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns false when a command is not on PATH", () => {
|
||||
const env = {
|
||||
PATH: "",
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||
});
|
||||
|
||||
it("does not treat bare files without executable extension as available on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||
});
|
||||
});
|
||||
|
||||
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
|
||||
it("uses platform-specific PATH delimiter for platform overrides", () => {
|
||||
withTempDir((firstDir) => {
|
||||
withTempDir((secondDir) => {
|
||||
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||
const env = {
|
||||
PATH: `${firstDir};${secondDir}`,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
} satisfies NodeJS.ProcessEnv;
|
||||
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAvailableEditors", () => {
|
||||
it("returns only editors whose launch commands are available", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,276 +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 { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
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>;
|
||||
}
|
||||
|
||||
interface CommandAvailabilityOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return "open";
|
||||
case "win32":
|
||||
return "explorer";
|
||||
default:
|
||||
return "xdg-open";
|
||||
}
|
||||
}
|
||||
|
||||
function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
|
||||
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||
}
|
||||
|
||||
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||
const rawValue = env.PATHEXT;
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
function resolveCommandCandidates(
|
||||
command: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (platform !== "win32") return [command];
|
||||
const extension = extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.from(
|
||||
new Set([
|
||||
command,
|
||||
`${commandWithoutExtension}${normalizedExtension}`,
|
||||
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
for (const extension of windowsPathExtensions) {
|
||||
candidates.push(`${command}${extension}`);
|
||||
candidates.push(`${command}${extension.toLowerCase()}`);
|
||||
}
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
|
||||
function isExecutableFile(
|
||||
filePath: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
if (!stat.isFile()) return false;
|
||||
if (platform === "win32") {
|
||||
const extension = extname(filePath);
|
||||
if (extension.length === 0) return false;
|
||||
return windowsPathExtensions.includes(extension.toUpperCase());
|
||||
}
|
||||
accessSync(filePath, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
export function isCommandAvailable(
|
||||
command: string,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): boolean {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
return commandCandidates.some((candidate) =>
|
||||
isExecutableFile(candidate, platform, windowsPathExtensions),
|
||||
);
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return false;
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ReadonlyArray<EditorId> {
|
||||
const available: EditorId[] = [];
|
||||
|
||||
for (const editor of EDITORS) {
|
||||
const command = editor.command ?? fileManagerCommandForPlatform(platform);
|
||||
if (isCommandAvailable(command, { platform, env })) {
|
||||
available.push(editor.id);
|
||||
}
|
||||
}
|
||||
|
||||
return available;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>()("t3/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 shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
if (editorDef.id !== "file-manager") {
|
||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||
}
|
||||
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} 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.tryPromise({
|
||||
try: () => import("open"),
|
||||
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,613 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
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(String(value));
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
if (left === null || left === undefined || right === null || right === undefined) {
|
||||
return false;
|
||||
}
|
||||
return left === right;
|
||||
}
|
||||
|
||||
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 threadId: ThreadId;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: input.threadId,
|
||||
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 threadId: ThreadId; readonly cwd: string }>
|
||||
> {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
|
||||
const sessions = yield* providerService.listSessions();
|
||||
|
||||
const findSessionWithCwd = (
|
||||
session: (typeof sessions)[number] | undefined,
|
||||
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
|
||||
if (!session?.cwd) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some({ threadId: session.threadId, cwd: session.cwd });
|
||||
};
|
||||
|
||||
if (thread) {
|
||||
const projectedSession = sessions.find(
|
||||
(session) => session.threadId === thread.id,
|
||||
);
|
||||
const fromProjected = findSessionWithCwd(projectedSession);
|
||||
if (Option.isSome(fromProjected)) {
|
||||
return fromProjected;
|
||||
}
|
||||
}
|
||||
|
||||
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.id === event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
// When a primary turn is active, only that turn may produce completion checkpoints.
|
||||
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
||||
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({
|
||||
threadId: thread.id,
|
||||
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.payload.state),
|
||||
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,
|
||||
status: event.payload.state,
|
||||
},
|
||||
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.id === event.threadId,
|
||||
);
|
||||
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({
|
||||
threadId: sessionRuntime.value.threadId,
|
||||
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({
|
||||
threadId: event.threadId,
|
||||
turnId,
|
||||
detail: error.message,
|
||||
createdAt: new Date().toISOString(),
|
||||
}).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
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") {
|
||||
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,679 +0,0 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
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";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
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),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required" as const,
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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, Schema, 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 (Schema.is(OrchestrationCommandInvariantError)(error)) {
|
||||
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,
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 382 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user