From 0d989c0d0ca477bd11d700f810be4dc19b3d5b08 Mon Sep 17 00:00:00 2001 From: LavonTMCQ Date: Fri, 20 Nov 2026 21:59:22 -0500 Subject: [PATCH 1/3] refactor(server): remove unused desktop and worker routes --- crates/o8d/route-templates.json | 25 - docs/internals/api.md | 23 - src/app/api/agents/conversation/route.ts | 45 -- src/app/api/claude-code/diffs/route.ts | 137 ----- src/app/api/claude-code/send/route.ts | 8 - .../api/claude-code/send/streaming-spawn.ts | 125 ---- src/app/api/cloud/job-status/route.ts | 47 -- src/app/api/codex/diffs/route.ts | 175 ------ src/app/api/codex/send/route.test.ts | 17 - src/app/api/codex/send/route.ts | 316 ---------- .../api/cortex/operator-corrections/route.ts | 55 -- src/app/api/panel/assign-issue/route.ts | 53 -- src/app/api/panel/branches/checkout/route.ts | 101 ---- src/app/api/panel/cloud-workers/route.ts | 95 --- src/app/api/panel/commit-diff/route.ts | 35 -- src/app/api/panel/dev-server/route.ts | 188 ------ src/app/api/panel/file-preview/route.ts | 80 --- src/app/api/panel/ide-surface/route.ts | 31 - src/app/api/panel/mcp-test/route.ts | 103 ---- src/app/api/panel/pr/review/route.ts | 89 --- src/app/api/panel/readme/route.ts | 35 -- src/app/api/panel/report-artifact/route.ts | 32 - src/app/api/panel/terminal-exec/route.ts | 52 -- src/app/api/panel/workers/route.ts | 103 ---- src/app/api/panel/worktree-diff/route.ts | 68 --- src/app/api/review/diff/route.ts | 131 ---- src/app/api/review/file/route.ts | 33 - src/app/api/telemetry/config/route.ts | 51 -- src/app/api/worktrees/merge/handler.ts | 568 ------------------ .../worktrees/merge/route-real-path.test.ts | 457 -------------- src/app/api/worktrees/merge/route.test.ts | 216 ------- src/app/api/worktrees/merge/route.ts | 8 - src/lib/agents/service.ts | 39 -- src/lib/agents/store.ts | 48 -- src/lib/cloud/job-queue.ts | 5 - src/lib/codebase-memory/mcp-client.ts | 2 +- src/lib/cortex/correction-memory.ts | 57 -- src/lib/github-broker/actions.ts | 22 - src/lib/github-broker/index.ts | 2 - src/lib/hooks/claude-code-pretool-hook.ts | 2 +- src/lib/mcp/test-connection.ts | 418 ------------- src/lib/panel/git-commits.ts | 5 - src/lib/runtime/ide-surface-state.ts | 21 +- src/lib/supervisor/spawn-environment-rule.ts | 1 - src/lib/viewers/http-routes.ts | 9 - src/lib/worker/feature-flags.ts | 39 -- src/lib/worker/tokens.ts | 143 ----- src/lib/workspace/exact-discard.ts | 79 --- .../workspace-materialization-retirement.ts | 33 - src/middleware.ts | 3 +- src/ws-server.ts | 52 -- tests/agent-message-bus-real-path.test.ts | 31 +- .../cloud-forgotten-context-real-path.test.ts | 5 - tests/cloud-job-spine-real-path.test.ts | 63 +- tests/cold-start-runtime-spawn-routes.test.ts | 33 - tests/crash-reports-toggle.test.ts | 2 +- tests/e2e/packet-identity.spec.ts | 16 - tests/fixtures/forgotten-correction.ts | 9 + tests/forget-corrections-real-path.test.ts | 69 +-- tests/forget-project-matrix-real-path.test.ts | 28 +- tests/hosting-publication-real-path.test.ts | 90 ++- tests/integration-weights.json | 5 - ...ge-source-direct-writers-real-path.test.ts | 99 +-- ...-source-write-boundaries-real-path.test.ts | 43 +- tests/panel-json-body-real-path.test.ts | 11 - ...nel-raster-image-serving-real-path.test.ts | 18 +- tests/plugin-principal-real-path.test.ts | 2 +- tests/pr-first-publication-real-path.test.ts | 12 +- tests/principal-authz.test.ts | 16 - ...provider-key-chat-routes-real-path.test.ts | 18 +- ...rovider-key-deferred-mcp-real-path.test.ts | 21 - ...voked-packet-worker-gate-real-path.test.ts | 15 +- .../stream-terminal-callers-real-path.test.ts | 24 - tests/terminal-visibility-real-path.test.ts | 1 - tests/test-classification.json | 38 -- tests/viewer-redaction-real-path.test.ts | 14 +- .../viewer-redaction-review-real-path.test.ts | 19 +- ...viewer-session-redaction-real-path.test.ts | 52 -- ...ironment-launch-boundary-real-path.test.ts | 15 - ...environment-npx-registry-real-path.test.ts | 147 +---- ...rkspace-preservation-cli-real-path.test.ts | 27 +- 81 files changed, 119 insertions(+), 5306 deletions(-) delete mode 100644 src/app/api/agents/conversation/route.ts delete mode 100644 src/app/api/claude-code/diffs/route.ts delete mode 100644 src/app/api/claude-code/send/route.ts delete mode 100644 src/app/api/claude-code/send/streaming-spawn.ts delete mode 100644 src/app/api/cloud/job-status/route.ts delete mode 100644 src/app/api/codex/diffs/route.ts delete mode 100644 src/app/api/codex/send/route.test.ts delete mode 100644 src/app/api/codex/send/route.ts delete mode 100644 src/app/api/cortex/operator-corrections/route.ts delete mode 100644 src/app/api/panel/assign-issue/route.ts delete mode 100644 src/app/api/panel/branches/checkout/route.ts delete mode 100644 src/app/api/panel/cloud-workers/route.ts delete mode 100644 src/app/api/panel/commit-diff/route.ts delete mode 100644 src/app/api/panel/dev-server/route.ts delete mode 100644 src/app/api/panel/file-preview/route.ts delete mode 100644 src/app/api/panel/ide-surface/route.ts delete mode 100644 src/app/api/panel/mcp-test/route.ts delete mode 100644 src/app/api/panel/pr/review/route.ts delete mode 100644 src/app/api/panel/readme/route.ts delete mode 100644 src/app/api/panel/report-artifact/route.ts delete mode 100644 src/app/api/panel/terminal-exec/route.ts delete mode 100644 src/app/api/panel/workers/route.ts delete mode 100644 src/app/api/panel/worktree-diff/route.ts delete mode 100644 src/app/api/review/diff/route.ts delete mode 100644 src/app/api/review/file/route.ts delete mode 100644 src/app/api/telemetry/config/route.ts delete mode 100644 src/app/api/worktrees/merge/handler.ts delete mode 100644 src/app/api/worktrees/merge/route-real-path.test.ts delete mode 100644 src/app/api/worktrees/merge/route.test.ts delete mode 100644 src/app/api/worktrees/merge/route.ts delete mode 100644 src/lib/cortex/correction-memory.ts delete mode 100644 src/lib/mcp/test-connection.ts delete mode 100644 src/lib/workspace/exact-discard.ts create mode 100644 tests/fixtures/forgotten-correction.ts delete mode 100644 tests/provider-key-deferred-mcp-real-path.test.ts delete mode 100644 tests/viewer-session-redaction-real-path.test.ts diff --git a/crates/o8d/route-templates.json b/crates/o8d/route-templates.json index 1a56946cc3..483bbb353b 100644 --- a/crates/o8d/route-templates.json +++ b/crates/o8d/route-templates.json @@ -1,6 +1,5 @@ [ "/api/agent-control/action", - "/api/agents/conversation", "/api/agents/inbox", "/api/agents/message", "/api/agents/presence", @@ -26,15 +25,10 @@ "/api/browser/inventory", "/api/browser/proxy", "/api/canvas/intent", - "/api/claude-code/diffs", - "/api/claude-code/send", - "/api/cloud/job-status", "/api/cloud/worker-control", "/api/cloud/worker-poll", "/api/cloud/worker-preview", "/api/cloud/worker-stream", - "/api/codex/diffs", - "/api/codex/send", "/api/command-center/snapshot", "/api/cortex/ask", "/api/cortex/ask/answer", @@ -42,7 +36,6 @@ "/api/cortex/cross-repo-proposals", "/api/cortex/diagnostics", "/api/cortex/directives", - "/api/cortex/operator-corrections", "/api/cortex/proposals", "/api/cortex/recent-outcomes", "/api/cortex/reingest", @@ -155,7 +148,6 @@ "/api/panel/approvals", "/api/panel/artifacts", "/api/panel/artifacts/mirror", - "/api/panel/assign-issue", "/api/panel/auth/clerk-provision", "/api/panel/auth/device/enroll", "/api/panel/auth/device/link", @@ -164,20 +156,16 @@ "/api/panel/auth/device/status", "/api/panel/auth/handoff", "/api/panel/branches", - "/api/panel/branches/checkout", "/api/panel/browse-folder", "/api/panel/ci", "/api/panel/ci/[id]", "/api/panel/cli-usage", "/api/panel/cloud-jobs/drain", - "/api/panel/cloud-workers", - "/api/panel/commit-diff", "/api/panel/commits", "/api/panel/commits/[hash]", "/api/panel/commits/[hash]/file", "/api/panel/connect", "/api/panel/connect/attach", - "/api/panel/dev-server", "/api/panel/devices", "/api/panel/entitlement", "/api/panel/entitlement/sync", @@ -185,12 +173,10 @@ "/api/panel/file-content", "/api/panel/file-diff", "/api/panel/file-io", - "/api/panel/file-preview", "/api/panel/files", "/api/panel/git-log", "/api/panel/git/log", "/api/panel/github-status", - "/api/panel/ide-surface", "/api/panel/inbox/decisions", "/api/panel/issues", "/api/panel/issues/[number]", @@ -198,7 +184,6 @@ "/api/panel/issues/enhance", "/api/panel/link-preview", "/api/panel/managed-runs", - "/api/panel/mcp-test", "/api/panel/mobile-network", "/api/panel/mobile-pairing", "/api/panel/models/chatgpt", @@ -209,7 +194,6 @@ "/api/panel/ports", "/api/panel/pr", "/api/panel/pr-stack", - "/api/panel/pr/review", "/api/panel/problem-dossiers", "/api/panel/projects", "/api/panel/projects/[id]", @@ -220,10 +204,8 @@ "/api/panel/prs/[number]/checks", "/api/panel/prs/[number]/comments", "/api/panel/prs/[number]/timeline", - "/api/panel/readme", "/api/panel/release-health", "/api/panel/repo-icon", - "/api/panel/report-artifact", "/api/panel/repos", "/api/panel/repos/init", "/api/panel/repos/scaffold", @@ -236,15 +218,12 @@ "/api/panel/supervisor-inbox", "/api/panel/targets", "/api/panel/telemetry", - "/api/panel/terminal-exec", "/api/panel/terminal-sessions", "/api/panel/terminal-state", "/api/panel/threads", "/api/panel/threads/artifact", "/api/panel/update/apply", - "/api/panel/workers", "/api/panel/workspaces", - "/api/panel/worktree-diff", "/api/panel/ws-info", "/api/plugins/audit", "/api/plugins/mcp", @@ -266,9 +245,7 @@ "/api/review/architecture-delta", "/api/review/auto-review", "/api/review/commit", - "/api/review/diff", "/api/review/discard", - "/api/review/file", "/api/review/last-turn", "/api/review/push", "/api/review/workspace", @@ -319,7 +296,6 @@ "/api/team/messages", "/api/team/presence", "/api/team/tell", - "/api/telemetry/config", "/api/v2/chat", "/api/v2/chat-history", "/api/v2/chat-history/list", @@ -338,6 +314,5 @@ "/api/worktrees/conflicts", "/api/worktrees/diff", "/api/worktrees/diff-summary", - "/api/worktrees/merge", "/api/worktrees/retention-usage" ] diff --git a/docs/internals/api.md b/docs/internals/api.md index 2f054f9116..a7346dad68 100644 --- a/docs/internals/api.md +++ b/docs/internals/api.md @@ -181,8 +181,6 @@ is refused by the global middleware even when it originates on loopback. | Method | Path | Purpose | |---|---|---| -| GET | `/api/claude-code/diffs?sessionKey=...&limit=...` | Extract file edit/write operations from Claude Code JSONL for live rendering. | -| POST | `/api/claude-code/send` | Send a message to a Claude Code session (delegates to `handleClaudeCodeSend`). | ### `/api/cloud/*` — Cloud worker scaffolding (self-authenticating) @@ -197,8 +195,6 @@ Workers authenticate via `Authorization: Bearer cwk_*` per-request, not the pane | Method | Path | Purpose | |---|---|---| -| GET | `/api/codex/diffs` | Parse Codex `apply_patch` format into structured file edits. | -| POST | `/api/codex/send` | Stream a message through `codex exec --json`; resumes if `threadId` provided. | ### `/api/command-center/*` — Fleet snapshot for the desktop dashboard (gated) @@ -349,39 +345,27 @@ device flow and every stateful panel route require the operator bearer. | GET | `/api/panel/analytics?hours=24` | Aggregate cost/usage across Codex, Claude Code, and IDE LLM chat. | | GET | `/api/panel/approvals` | List pending approvals from the shared queue. | | POST | `/api/panel/approvals` | Resolve a pending approval. | -| POST | `/api/panel/assign-issue` | Assign a GitHub issue to an agent (adds comment + label). | | GET | `/api/panel/branches?repo=...` | List branches with diff stats. | | POST | `/api/panel/branches` | Create a branch. | | DELETE | `/api/panel/branches` | Delete a branch. | -| POST | `/api/panel/branches/checkout` | Checkout a branch; checks for uncommitted changes first. | | POST | `/api/panel/browse-folder` | Open native folder picker (macOS osascript). | | GET | `/api/panel/ci?repo=...` | Latest CI workflow runs (60s cache). | | GET | `/api/panel/ci/[id]?repo=...` | Detail for a single CI workflow run. | | GET | `/api/panel/cli-usage` | Snapshot of CLI usage across all runtimes. | -| GET | `/api/panel/cloud-workers` | Panel-side surface for cloud workers (#514). | -| POST | `/api/panel/cloud-workers` | Mutate cloud worker registrations. | -| GET | `/api/panel/commit-diff?sha=...&workspace=...` | Files changed in a single commit. | | GET | `/api/panel/commits?repo=...\|workspace=...&limit=...` | Recent commits (GitHub-side or local workspace). | | GET | `/api/panel/commits/[hash]?workspace=...` | Detail for a single commit. | | GET | `/api/panel/commits/[hash]/file?workspace=...&path=...` | File contents at a specific commit. | -| GET | `/api/panel/dev-server` | List active dev server processes. | -| POST | `/api/panel/dev-server` | Start a dev server process. | -| DELETE | `/api/panel/dev-server` | Stop a dev server process. | | GET | `/api/panel/file-asset?workspace=...&path=...` | Serve registered repo file as asset (image/PDF), 50MB cap. | | GET | `/api/panel/file-content?path=...` | Read raw file content with path-traversal protection. | | GET | `/api/panel/file-diff?path=...&hideWhitespace=1` | Per-file diff (`git diff -w` when `hideWhitespace`). | -| GET | `/api/panel/file-preview?path=...&workspace=...` | File preview (image MIME or text). | | GET | `/api/panel/files?workspace=...` | List files in a workspace. | | GET | `/api/panel/git-log?workspace=...` | Parsed git log with structured ref data. | | GET | `/api/panel/git/log?workspace=...&limit=...` | Compact git log for Loop Status widget (#796). | | GET | `/api/panel/github-status` | Parsed `gh auth status` output. | -| GET | `/api/panel/ide-surface` | Read persisted IDE surface state (terminal repos, active repo). | -| POST | `/api/panel/ide-surface` | Persist IDE surface state. | | GET | `/api/panel/issues?repo=...` | List GitHub issues for a repo. | | GET | `/api/panel/issues/[number]?repo=...` | Detail for a single issue. | | POST | `/api/panel/issues/create` | Create a GitHub issue. | | POST | `/api/panel/issues/enhance` | Enhance issue body via LLM, parallel-fetching repo context. | -| POST | `/api/panel/mcp-test` | "Test connection" probe for a registered MCP server (stdio or HTTP). | | GET | `/api/panel/mobile-pairing` | Mobile pairing payload (Tailscale URL, ws-token, fingerprints) for QR. | | GET | `/api/panel/o8-update-summary` | Summarize an o8 GitHub release (release notes + recent commits) via OpenRouter free models for the UpdateCard. | | POST | `/api/panel/o8-mission-summary` | Summarize a completed mission's merged packets (hydrated from the session_outcomes ledger) into plain-language prose via OpenRouter free models, for the Mission-complete detail modal. | @@ -391,7 +375,6 @@ device flow and every stateful panel route require the operator bearer. | POST | `/api/panel/operator-defaults` | Update operator defaults. | | GET | `/api/panel/ports?fresh=1` | Discover ports in use on the local machine (cached). | | GET | `/api/panel/pr?repo=...&number=...` | PR detail + computed checks rollup status. | -| POST | `/api/panel/pr/review` | Submit a PR review (approve / comment / request_changes / merge / close). | | GET | `/api/panel/projects` | List projects ledger (reconciled with repo registry). | | POST | `/api/panel/projects` | Create a project. | | PATCH | `/api/panel/projects/[id]` | Update project name / repos / color. | @@ -402,7 +385,6 @@ device flow and every stateful panel route require the operator bearer. | GET | `/api/panel/prs/[number]?repo=...` | Detail for a single PR. | | POST | `/api/panel/prs/[number]` | PR mutation (close / merge / review / comment). | | GET | `/api/panel/prs/[number]/comments?repo=...` | List PR comments + reviews. | -| GET | `/api/panel/readme?workspace=...` | First matching README file in a workspace. | | GET | `/api/panel/repos` | List registered repos. | | POST | `/api/panel/repos` | Add / touch / update a registered repo. | | DELETE | `/api/panel/repos` | Remove a registered repo (with runtime cleanup). | @@ -414,12 +396,9 @@ device flow and every stateful panel route require the operator bearer. | GET | `/api/panel/status` | Stable status read for CLI / agents (allowlisted — read-only). | | GET | `/api/panel/supervisor-inbox?includeDismissed=1&scope=all&projectId=...` | Supervisor inbox items + summary. | | POST | `/api/panel/supervisor-inbox` | Dismiss / clear inbox items. | -| POST | `/api/panel/terminal-exec` | Send a command to a dashboard terminal session (WS bridge). | | GET | `/api/panel/terminal-sessions` | List alive dashboard terminal sessions. | | GET | `/api/panel/terminal-state?scope=...` | Read persisted terminal state for a scope (per-tile JSON file). | | POST | `/api/panel/terminal-state` | Persist terminal state for a scope. | -| GET | `/api/panel/workers` | Worker tokens + fleet status + remote-runtime registration. | -| POST | `/api/panel/workers` | Mutate worker tokens. | | GET | `/api/panel/workspaces` | List workspaces with cached PR / branch / diff data per repo. | | POST | `/api/panel/workspaces` | Mutate workspace lifecycle records. | @@ -457,7 +436,6 @@ device flow and every stateful panel route require the operator bearer. | POST | `/api/review/auto-review` | Start the review drain or enqueue a lane for auto-review. | | POST | `/api/review/commit` | Commit staged changes with a message (500 char cap). | | POST | `/api/review/discard` | Discard unstaged changes (path-traversal protected). | -| GET | `/api/review/file?path=...` | File detail for the live review surface. | | POST | `/api/review/push` | `git push` the current branch. | | GET | `/api/review/workspace?workspace=...&repo=...&strictBranch=1` | Full review snapshot (ahead/behind, changed files, recent commits, worktrees, PRs, issues). | @@ -568,7 +546,6 @@ Workers authenticate with `Authorization: Bearer cwk_*` per-request. | GET | `/api/worktrees/conflicts?repo=...&deep=true` | Conflict report (fast file-level or deep line-level). | | GET | `/api/worktrees/diff?sessionKey=...&worktreePath=...&baseBranch=...` | Full unified diff for an agent's worktree vs base. | | GET | `/api/worktrees/diff-summary?sessionKey=...&worktreePath=...&baseBranch=...` | `{ additions, deletions, fileCount }` for a worktree. | -| POST | `/api/worktrees/merge` | Create PR, merge to main, or discard a worktree. | ### Shared pull-request check evidence diff --git a/src/app/api/agents/conversation/route.ts b/src/app/api/agents/conversation/route.ts deleted file mode 100644 index 4d6db32ca5..0000000000 --- a/src/app/api/agents/conversation/route.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { NextRequest } from 'next/server'; - -import { resolveRequestPrincipalContext } from '@/lib/auth/principal'; -import { AgentBusError, changeAgentConversation, readAgentConversations } from '@/lib/agents/service'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -function errorResponse(error: unknown): Response { - if (error instanceof AgentBusError) { - return Response.json({ ok: false, error: { code: error.code, message: error.message } }, { status: error.status }); - } - console.error('[agent-conversation] Request failed:', error); - return Response.json({ - ok: false, - error: { code: 'agent_conversation_failed', message: 'Agent conversations are temporarily unavailable.' }, - }, { status: 503 }); -} - -export async function GET(request: NextRequest): Promise { - try { - const value = request.nextUrl.searchParams.get('limit'); - const limit = value === null ? 50 : Number(value); - if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) { - throw new AgentBusError('limit must be an integer from 1 through 100.', 'invalid_agent_conversation_limit', 400); - } - return Response.json({ - schema: 'o8/agents.conversations/v1', - ...readAgentConversations({ repo: request.nextUrl.searchParams.get('repo'), limit }, resolveRequestPrincipalContext(request)), - }, { headers: { 'Cache-Control': 'no-store, max-age=0' } }); - } catch (error) { - return errorResponse(error); - } -} - -export async function POST(request: Request): Promise { - try { - const conversation = changeAgentConversation(await request.json().catch(() => null), resolveRequestPrincipalContext(request)); - return Response.json({ schema: 'o8/agents.conversation/v1', ok: true, conversation }, { - headers: { 'Cache-Control': 'no-store, max-age=0' }, - }); - } catch (error) { - return errorResponse(error); - } -} diff --git a/src/app/api/claude-code/diffs/route.ts b/src/app/api/claude-code/diffs/route.ts deleted file mode 100644 index 254ac61bd1..0000000000 --- a/src/app/api/claude-code/diffs/route.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { viewerJson } from '@/lib/viewers/response'; -import { NextRequest } from 'next/server'; -import { readdir, readFile, stat } from 'fs/promises'; -import path from 'path'; -import os from 'os'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -const CLAUDE_PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects'); - -interface DiffEntry { - id: string; - file: string; // relative file path - shortFile: string; // just filename - tool: 'Edit' | 'Write' | 'Read' | 'MultiEdit'; - oldText?: string; - newText?: string; - content?: string; // for Write operations - timestamp: number; -} - -/** - * GET /api/claude-code/diffs?sessionKey=claude-code:live-PID&limit=20 - * - * Extracts file edit/write operations from Claude Code JSONL, - * returning structured diff entries for live rendering. - */ -export async function GET(req: NextRequest) { - const limit = parseInt(req.nextUrl.searchParams.get('limit') ?? '20', 10); - - try { - // Find all JSONL files across project dirs, sorted by mtime desc - const projectDirs = await readdir(CLAUDE_PROJECTS_DIR).catch(() => []); - const allFiles: { path: string; mtime: number }[] = []; - - for (const dir of projectDirs) { - const dirPath = path.join(CLAUDE_PROJECTS_DIR, dir); - try { - const files = await readdir(dirPath); - for (const file of files) { - if (!file.endsWith('.jsonl')) continue; - const filePath = path.join(dirPath, file); - const fileStat = await stat(filePath); - allFiles.push({ path: filePath, mtime: fileStat.mtimeMs }); - } - } catch { /* skip */ } - } - - if (allFiles.length === 0) { - return viewerJson({ diffs: [] }); - } - - // Sort by most recent first, read all (but cap total lines) - allFiles.sort((a, b) => b.mtime - a.mtime); - - const lines: string[] = []; - for (const f of allFiles.slice(0, 5)) { // Read up to 5 most recent session files - const raw = await readFile(f.path, 'utf-8'); - lines.push(...raw.trim().split('\n').filter(Boolean)); - } - - const diffs: DiffEntry[] = []; - const homeDir = os.homedir(); - - for (const line of lines) { - try { - const entry = JSON.parse(line); - const msg = entry.message; - if (!msg?.content || !Array.isArray(msg.content)) continue; - - const timestamp = entry.timestamp ? new Date(entry.timestamp).getTime() : Date.now(); - - for (const block of msg.content) { - if (block.type !== 'tool_use') continue; - const name = block.name; - const input = block.input ?? {}; - - if (name === 'Edit' && input.file_path) { - const filePath = (input.file_path as string).replace(homeDir, '~'); - const shortFile = path.basename(input.file_path as string); - diffs.push({ - id: `${entry.uuid ?? diffs.length}-edit-${shortFile}`, - file: filePath, - shortFile, - tool: 'Edit', - oldText: input.old_string as string | undefined, - newText: input.new_string as string | undefined, - timestamp, - }); - } - - if (name === 'Write' && input.file_path) { - const filePath = (input.file_path as string).replace(homeDir, '~'); - const shortFile = path.basename(input.file_path as string); - diffs.push({ - id: `${entry.uuid ?? diffs.length}-write-${shortFile}`, - file: filePath, - shortFile, - tool: 'Write', - content: (input.content as string | undefined)?.slice(0, 2000), - timestamp, - }); - } - - if (name === 'MultiEdit' && input.file_path) { - const filePath = (input.file_path as string).replace(homeDir, '~'); - const shortFile = path.basename(input.file_path as string); - const edits = input.edits as { old_string?: string; new_string?: string }[] | undefined; - if (edits) { - for (const edit of edits) { - diffs.push({ - id: `${entry.uuid ?? diffs.length}-multi-${shortFile}-${diffs.length}`, - file: filePath, - shortFile, - tool: 'MultiEdit', - oldText: edit.old_string, - newText: edit.new_string, - timestamp, - }); - } - } - } - } - } catch { /* skip malformed */ } - } - - return viewerJson({ diffs: diffs.slice(-limit) }, { - headers: { 'Cache-Control': 'no-store, max-age=0' }, - }); - } catch (err) { - return viewerJson( - { diffs: [], error: err instanceof Error ? err.message : 'unknown' }, - { status: 500 }, - ); - } -} diff --git a/src/app/api/claude-code/send/route.ts b/src/app/api/claude-code/send/route.ts deleted file mode 100644 index 2f75eac8c3..0000000000 --- a/src/app/api/claude-code/send/route.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { handleClaudeCodeSend } from './streaming-spawn'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -export async function POST(req: Request) { - return handleClaudeCodeSend(req); -} diff --git a/src/app/api/claude-code/send/streaming-spawn.ts b/src/app/api/claude-code/send/streaming-spawn.ts deleted file mode 100644 index 065cd8607c..0000000000 --- a/src/app/api/claude-code/send/streaming-spawn.ts +++ /dev/null @@ -1,125 +0,0 @@ -import os from 'os'; -import { knowledgeSourceWriteRefusal, normalizeKnowledgeWritePath } from '@/lib/cortex/knowledge/sources'; -import { ensureSession, sendMessage } from '@/lib/claude-code/interactive-session'; -import type { ClaudeCodePermissionMode } from '@/lib/claude-code/interactive-session'; - -interface SendRequest { - message: string; - cwd?: string; - sessionId?: string; - tabId?: string; - model?: string; - resumeSessionId?: string; - planMode?: boolean; - bypassPermissions?: boolean; -} - -function jsonError(error: string, status: number) { - return new Response(JSON.stringify({ error }), { - status, - headers: { 'Content-Type': 'application/json' }, - }); -} - -function errorText(error: unknown) { - return error instanceof Error ? error.message : String(error); -} - -export async function handleClaudeCodeSend(req: Request) { - let body: SendRequest; - try { - body = (await req.json()) as SendRequest; - } catch { - return jsonError('Invalid JSON request body', 400); - } - const { message, cwd, sessionId, tabId, model, resumeSessionId, planMode, bypassPermissions } = body; - - if (!message?.trim()) { - return jsonError('Message is required', 400); - } - - const sessionKey = (tabId || sessionId || '').trim(); - if (!sessionKey) { - return jsonError('A stable tabId or sessionId is required', 400); - } - - const sourceRefusal = knowledgeSourceWriteRefusal(cwd); - if (sourceRefusal) return sourceRefusal; - const expandedCwd = cwd ? normalizeKnowledgeWritePath(cwd.replace(/^~(?=\/|$)/, os.homedir())) : undefined; - const workingDir = expandedCwd || process.cwd(); - const resolvedRefusal = knowledgeSourceWriteRefusal(workingDir); - if (resolvedRefusal) return resolvedRefusal; - const permissionMode: ClaudeCodePermissionMode = bypassPermissions - ? 'bypassPermissions' - : planMode - ? 'plan' - : 'acceptEdits'; - let session: ReturnType; - // Only resume from an actual captured Claude session_id — never from - // sessionId, which is a tab/transport routing key, not a Claude session. - const resumeId = resumeSessionId?.trim() || undefined; - try { - session = ensureSession(sessionKey, workingDir, model, permissionMode, resumeId); - } catch (error) { - return jsonError(errorText(error), 500); - } - - const encoder = new TextEncoder(); - let abortController: AbortController | null = null; - let streamClosed = false; - - const stream = new ReadableStream({ - start(controller) { - abortController = new AbortController(); - const markClientGone = () => { - streamClosed = true; - }; - if (req.signal.aborted) markClientGone(); - else req.signal.addEventListener('abort', markClientGone, { once: true }); - let closeText = ''; - let closeSessionId = session.sessionId ?? null; - const enqueueEvent = (event: unknown) => { - if (streamClosed) return; - controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); - }; - const closeStream = () => { - if (streamClosed) return; - streamClosed = true; - req.signal.removeEventListener('abort', markClientGone); - controller.close(); - }; - void sendMessage(session, message, (event) => { - if (event.type === 'delta') closeText += event.text; - if (event.type === 'done') { - closeText = event.text; - closeSessionId = event.sessionId ?? closeSessionId; - } - enqueueEvent(event); - }, { planMode, signal: abortController.signal }).then(() => { - const settledSessionId = closeSessionId || session.sessionId || undefined; - enqueueEvent({ - type: 'close', - exitCode: 0, - text: closeText, - sessionId: settledSessionId, - }); - closeStream(); - }).catch((error: unknown) => { - enqueueEvent({ type: 'error', text: errorText(error) }); - closeStream(); - }); - }, - cancel() { - streamClosed = true; - }, - }); - - return new Response(stream, { - headers: { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-store', - 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no', - }, - }); -} diff --git a/src/app/api/cloud/job-status/route.ts b/src/app/api/cloud/job-status/route.ts deleted file mode 100644 index 3ebb70975d..0000000000 --- a/src/app/api/cloud/job-status/route.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { NextResponse } from 'next/server'; - -import { verifyCloudWorkerKey } from '@/lib/cloud/worker-auth'; -import { ForgottenCloudContextError, workerLaunchPayload } from '@/lib/cloud/worker-payload'; -import { getJob, getJobMetrics, listJobControls, readJobEvents } from '@/lib/cloud/job-queue'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -const NO_STORE_HEADERS = { 'Cache-Control': 'no-store' }; - -export async function GET(request: Request) { - const auth = verifyCloudWorkerKey(request.headers.get('authorization')); - if (!auth.ok) { - return NextResponse.json( - { error: auth.status === 401 ? 'Unauthorized' : 'Forbidden', reason: auth.reason }, - { status: auth.status, headers: NO_STORE_HEADERS }, - ); - } - const url = new URL(request.url); - const jobId = url.searchParams.get('jobId')?.trim(); - const sinceId = Number.parseInt(url.searchParams.get('sinceId') ?? '0', 10); - if (!jobId || !Number.isFinite(sinceId) || sinceId < 0) { - return NextResponse.json( - { error: 'A valid jobId and non-negative sinceId are required' }, - { status: 400, headers: NO_STORE_HEADERS }, - ); - } - const job = getJob(auth.teamId, jobId); - if (!job) { - return NextResponse.json( - { error: 'Cloud job not found' }, - { status: 404, headers: NO_STORE_HEADERS }, - ); - } - let launch: ReturnType; - try { launch = workerLaunchPayload(job.launch); } catch (error) { - if (error instanceof ForgottenCloudContextError) return NextResponse.json({ error: error.message, reason: 'memory_changed' }, { status: 409, headers: NO_STORE_HEADERS }); - return NextResponse.json({ error: 'Could not read cloud worker context.' }, { status: 500, headers: NO_STORE_HEADERS }); - } - return NextResponse.json({ - job: { ...job, launch }, - metrics: getJobMetrics(auth.teamId, jobId), - controls: listJobControls(auth.teamId, jobId), - events: readJobEvents(auth.teamId, jobId, sinceId), - }, { headers: NO_STORE_HEADERS }); -} diff --git a/src/app/api/codex/diffs/route.ts b/src/app/api/codex/diffs/route.ts deleted file mode 100644 index fbd1661a7b..0000000000 --- a/src/app/api/codex/diffs/route.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { viewerJson } from '@/lib/viewers/response'; -import { NextRequest } from 'next/server'; -import { readdir, readFile, stat } from 'fs/promises'; -import path from 'path'; -import os from 'os'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -const CODEX_SESSIONS_DIR = path.join(os.homedir(), '.codex', 'sessions'); - -interface DiffEntry { - id: string; - file: string; - shortFile: string; - tool: 'Edit' | 'Write' | 'Read' | 'MultiEdit'; - oldText?: string; - newText?: string; - content?: string; - timestamp: number; -} - -/** - * Parse Codex apply_patch format into file edits. - * Format: "*** Begin Patch\n*** Update File: /path/to/file.ts\n@@ ... @@\n-old\n+new" - */ -function parsePatch(patchText: string): DiffEntry[] { - const entries: DiffEntry[] = []; - const homeDir = os.homedir(); - - // Split by "*** Update File:" or "*** Add File:" markers - const fileBlocks = patchText.split(/\*\*\*\s+(Update|Add)\s+File:\s+/); - - for (let i = 1; i < fileBlocks.length; i += 2) { - const operation = fileBlocks[i]; // "Update" or "Add" - const block = fileBlocks[i + 1]; - if (!block) continue; - - const lines = block.split('\n'); - const filePath = lines[0].trim().replace(homeDir, '~'); - const shortFile = path.basename(filePath); - - if (operation === 'Add') { - const content = lines.slice(1).filter(l => l.startsWith('+')).map(l => l.slice(1)).join('\n'); - entries.push({ - id: `codex-add-${shortFile}-${entries.length}`, - file: filePath, - shortFile, - tool: 'Write', - content: content.slice(0, 2000), - timestamp: Date.now(), - }); - } else { - // Parse @@ hunks for old/new - const oldLines: string[] = []; - const newLines: string[] = []; - - for (const line of lines.slice(1)) { - if (line.startsWith('@@')) continue; - if (line.startsWith('-')) oldLines.push(line.slice(1)); - else if (line.startsWith('+')) newLines.push(line.slice(1)); - else if (line.startsWith(' ')) { - oldLines.push(line.slice(1)); - newLines.push(line.slice(1)); - } - } - - if (oldLines.length > 0 || newLines.length > 0) { - entries.push({ - id: `codex-edit-${shortFile}-${entries.length}`, - file: filePath, - shortFile, - tool: 'Edit', - oldText: oldLines.join('\n'), - newText: newLines.join('\n'), - timestamp: Date.now(), - }); - } - } - } - - return entries; -} - -/** - * GET /api/codex/diffs?limit=20 - * - * Reads recent Codex session JSONLs and extracts apply_patch + exec_command tool calls. - */ -export async function GET(req: NextRequest) { - const limit = parseInt(req.nextUrl.searchParams.get('limit') ?? '20', 10); - - try { - // Find recent session files (walk year/month/day dirs) - const allFiles: { path: string; mtime: number }[] = []; - - const years = await readdir(CODEX_SESSIONS_DIR).catch(() => []); - for (const year of years.slice(-1)) { // Latest year - const months = await readdir(path.join(CODEX_SESSIONS_DIR, year)).catch(() => []); - for (const month of months.slice(-1)) { // Latest month - const days = await readdir(path.join(CODEX_SESSIONS_DIR, year, month)).catch(() => []); - for (const day of days.slice(-2)) { // Last 2 days - const dayDir = path.join(CODEX_SESSIONS_DIR, year, month, day); - try { - const files = await readdir(dayDir); - for (const file of files) { - if (!file.endsWith('.jsonl')) continue; - const filePath = path.join(dayDir, file); - const fileStat = await stat(filePath); - allFiles.push({ path: filePath, mtime: fileStat.mtimeMs }); - } - } catch { /* skip */ } - } - } - } - - if (allFiles.length === 0) { - return viewerJson({ diffs: [] }); - } - - // Sort by most recent, read top 5 - allFiles.sort((a, b) => b.mtime - a.mtime); - - const diffs: DiffEntry[] = []; - - for (const f of allFiles.slice(0, 5)) { - const raw = await readFile(f.path, 'utf-8'); - const lines = raw.trim().split('\n').filter(Boolean); - - for (const line of lines) { - try { - const entry = JSON.parse(line); - const payload = entry.payload ?? {}; - const timestamp = entry.timestamp ? new Date(entry.timestamp).getTime() : Date.now(); - - // apply_patch tool calls - if (payload.type === 'custom_tool_call' && payload.name === 'apply_patch' && payload.input) { - const patchEntries = parsePatch(payload.input); - for (const pe of patchEntries) { - pe.timestamp = timestamp; - pe.id = `${f.path}-${diffs.length}-${pe.shortFile}`; - diffs.push(pe); - } - } - - // exec_command (show as terminal events) - if (payload.type === 'function_call' && payload.name === 'exec_command') { - try { - const args = JSON.parse(payload.arguments ?? '{}'); - if (args.cmd) { - diffs.push({ - id: `${f.path}-exec-${diffs.length}`, - file: args.cmd.slice(0, 80), - shortFile: '$ ' + args.cmd.split(' ')[0], - tool: 'Read', // Using Read as "terminal" indicator - content: args.cmd, - timestamp, - }); - } - } catch { /* skip */ } - } - } catch { /* skip malformed */ } - } - } - - return viewerJson({ diffs: diffs.slice(-limit) }, { - headers: { 'Cache-Control': 'no-store, max-age=0' }, - }); - } catch (err) { - return viewerJson( - { diffs: [], error: err instanceof Error ? err.message : 'unknown' }, - { status: 500 }, - ); - } -} diff --git a/src/app/api/codex/send/route.test.ts b/src/app/api/codex/send/route.test.ts deleted file mode 100644 index 66144f627e..0000000000 --- a/src/app/api/codex/send/route.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { EventEmitter } from 'node:events'; -import { NextRequest } from 'next/server'; -import { expect, it, vi } from 'vitest'; -const fixture = vi.hoisted(() => ({ spawn: vi.fn() })); -vi.mock('child_process', () => ({ spawn: fixture.spawn })); -vi.mock('@/lib/lane/repo-preflight', () => ({ assertOrchestratorRepoPath: () => undefined })); -vi.mock('@/lib/runtimes/shared/cli-resolver', () => ({ resolveCli: async () => ({ path: '/fixture/codex' }), CliNotFoundError: class extends Error {} })); -vi.mock('@/lib/runtimes/shared/cli-spawn', () => ({ cliInvocation: (command: string, args: string[]) => ({ command, args }) })); -import { POST } from './route'; -it('emits a proven rejected delivery when the CLI process cannot spawn', async () => { - const child = Object.assign(new EventEmitter(), { stdout: new EventEmitter(), stderr: new EventEmitter(), stdin: { end: () => queueMicrotask(() => child.emit('error', new Error('fixture spawn failed'))) } }); - fixture.spawn.mockReturnValue(child); - const response = await POST(new NextRequest('http://localhost/api/codex/send', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ message: 'fixture' }) })); - expect(response.status).toBe(200); - expect(await response.text()).toContain('"delivery":"rejected"'); - expect(fixture.spawn).toHaveBeenCalledTimes(1); -}); diff --git a/src/app/api/codex/send/route.ts b/src/app/api/codex/send/route.ts deleted file mode 100644 index 65c3ff1bab..0000000000 --- a/src/app/api/codex/send/route.ts +++ /dev/null @@ -1,316 +0,0 @@ -import { childEnvironment } from '@/lib/providers/spawn-environment'; -import { NextRequest } from 'next/server'; -import { spawn } from '@/lib/providers/child-process'; - -import { assertOrchestratorRepoPath } from '@/lib/lane/repo-preflight'; -import { formatMissingCliError } from '@/lib/runtimes/shared/cli-unavailable'; -import { CliNotFoundError, resolveCli } from '@/lib/runtimes/shared/cli-resolver'; -import { cliInvocation } from '@/lib/runtimes/shared/cli-spawn'; -import { providerSpawnEnvironment } from '@/lib/providers/spawn-environment'; -import { assertNotKnowledgeSource, normalizeKnowledgeWritePath } from '@/lib/cortex/knowledge/sources'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -interface SendRequest { - message: string; - cwd?: string; - threadId?: string; // Codex thread UUID for resume - model?: string; -} - -function parseCodexArgs(raw: unknown) { - if (typeof raw !== 'string') return undefined; - const trimmed = raw.trim(); - if (!trimmed) return undefined; - try { - const parsed = JSON.parse(trimmed) as unknown; - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) - ? parsed as Record - : { input: parsed }; - } catch { - return { input: trimmed }; - } -} - -function extractCodexMessageText(item: Record) { - if (typeof item.text === 'string' && item.text.trim()) return item.text; - const content = Array.isArray(item.content) ? item.content as Array> : []; - return content - .filter((part) => part.type === 'output_text' || part.type === 'input_text') - .map((part) => String(part.text ?? '')) - .join(' ') - .trim(); -} - -function extractCodexReasoningText(item: Record) { - const summary = Array.isArray(item.summary) ? item.summary as Array> : []; - return summary - .map((part) => { - if (typeof part.text === 'string') return part.text; - if (typeof part.summary_text === 'string') return part.summary_text; - return ''; - }) - .filter(Boolean) - .join('\n') - .trim(); -} - -function shouldSuppressCodexStderrLine(line: string) { - const trimmed = line.trim(); - if (!trimmed) return true; - if (trimmed.includes('failed to stat skills entry') && trimmed.includes('/.codex/skills/')) return true; - if (trimmed.includes('rmcp::transport::worker') && trimmed.includes('Connection refused')) return true; - return false; -} - -/** - * POST /api/codex/send - * - * Sends a message to Codex CLI in exec mode and streams the response. - * Uses --json for JSONL event streaming. - * - * If threadId is provided, resumes that conversation via `codex exec resume`. - * Otherwise starts a new exec session in the given cwd. - */ -export async function POST(req: NextRequest) { - const body = await req.json().catch(() => null) as SendRequest | null; - if (!body) { - return Response.json({ error: 'Request body must be valid JSON.' }, { status: 400 }); - } - const { message, cwd, threadId, model } = body; - - if (!message?.trim()) { - return new Response(JSON.stringify({ error: 'Message is required' }), { - status: 400, - headers: { 'Content-Type': 'application/json' }, - }); - } - - // Expand tilde in workspace paths - let workingDir: string; - try { - assertNotKnowledgeSource(cwd); - const expandedCwd = cwd?.trim() ? normalizeKnowledgeWritePath(cwd) : undefined; - workingDir = expandedCwd || process.cwd(); - assertNotKnowledgeSource(workingDir); - if (expandedCwd) assertOrchestratorRepoPath(expandedCwd); - } catch (error) { - return Response.json({ - error: `[repo] ${error instanceof Error ? error.message : 'The workspace is unavailable.'}`, - code: 'repo_unavailable', - }, { status: 400 }); - } - - const cliSpec = { - runtimeId: 'codex', - binaryName: 'codex', - humanLabel: 'Codex', - envOverride: 'O8_CODEX_BIN', - }; - let codexBin: string; - try { - codexBin = (await resolveCli(cliSpec)).path; - } catch (error) { - if (!(error instanceof CliNotFoundError)) { - console.error('[codex-send] Failed to resolve Codex:', error); - return Response.json({ - error: '[runtime] Codex could not be started. Check the server log for details.', - code: 'runtime_resolution_failed', - }, { status: 500 }); - } - return Response.json({ - error: formatMissingCliError({ - ...cliSpec, - triedPaths: error.triedPaths, - }), - code: 'runtime_not_installed', - }, { status: 503 }); - } - - // Build command args - let args: string[]; - if (threadId) { - // Resume existing conversation - args = ['exec', 'resume', threadId, message, '--json', '--dangerously-bypass-approvals-and-sandbox']; - } else { - // New conversation - args = ['exec', message, '--json', '--dangerously-bypass-approvals-and-sandbox']; - } - - if (model) { - args.push('--model', model); - } - - // CLI resolution can await; a newly configured source must still refuse the spawn. - try { - assertNotKnowledgeSource(workingDir); - } catch (error) { - return Response.json({ error: error instanceof Error ? error.message : 'The workspace is unavailable.', code: 'repo_unavailable' }, { status: 400 }); - } - const encoder = new TextEncoder(); - - let markClientGone: (() => void) | null = null; - const stream = new ReadableStream({ - start(controller) { - const launch = cliInvocation(codexBin, args); - const child = spawn(launch.command, launch.args, { - windowsHide: true, - cwd: workingDir, - env: providerSpawnEnvironment(childEnvironment({ runtimeId: 'codex', env: { FORCE_COLOR: '0', NO_COLOR: '1' } }), { runtimeId: 'codex' }), - stdio: ['pipe', 'pipe', 'pipe'], - }); - - let fullResponse = ''; - let capturedThreadId = ''; - let streamClosed = false; - markClientGone = () => { - streamClosed = true; - }; - const enqueueChunk = (chunk: Uint8Array) => { - if (streamClosed) return; - controller.enqueue(chunk); - }; - const closeStream = () => { - if (streamClosed) return; - streamClosed = true; - controller.close(); - }; - - child.stdout.on('data', (chunk: Buffer) => { - const text = chunk.toString(); - - for (const line of text.split('\n').filter(Boolean)) { - try { - const event = JSON.parse(line) as Record; - const rawItem = (event.item ?? event.payload ?? {}) as Record; - - // Capture thread ID - if (event.type === 'thread.started' && event.thread_id) { - capturedThreadId = event.thread_id as string; - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ type: 'session', threadId: capturedThreadId })}\n\n` - )); - } - - // Agent message completed — the actual response text - if (event.type === 'item.completed' || event.type === 'response_item') { - const itemType = String(rawItem.type ?? ''); - const itemRole = String(rawItem.role ?? ''); - const messageText = extractCodexMessageText(rawItem); - const reasoningText = extractCodexReasoningText(rawItem); - - if ((itemType === 'agent_message' || (itemType === 'message' && itemRole === 'assistant')) && messageText) { - fullResponse += messageText; - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ type: 'delta', text: messageText })}\n\n` - )); - } - - if (itemType === 'reasoning' && reasoningText) { - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ type: 'thinking', text: reasoningText })}\n\n` - )); - } - - if (itemType === 'tool_call' || itemType === 'function_call' || itemType === 'custom_tool_call') { - const toolName = typeof rawItem.name === 'string' ? rawItem.name : ''; - if (toolName) { - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ - type: 'tool_call', - name: toolName, - status: 'running', - args: parseCodexArgs(rawItem.arguments) - ?? (typeof rawItem.input === 'string' - ? parseCodexArgs(rawItem.input) - : (rawItem.input && typeof rawItem.input === 'object' ? rawItem.input as Record : undefined)), - })}\n\n` - )); - } - } - - if ((itemType === 'function_call_output' || itemType === 'custom_tool_call_output') && typeof rawItem.output === 'string') { - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ - type: 'tool_result', - name: typeof rawItem.name === 'string' ? rawItem.name : undefined, - preview: rawItem.output, - })}\n\n` - )); - } - } - - // Turn completed — usage info - if (event.type === 'turn.completed') { - const usage = event.usage as { input_tokens?: number; output_tokens?: number } | undefined; - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ - type: 'usage', - inputTokens: usage?.input_tokens, - outputTokens: usage?.output_tokens, - })}\n\n` - )); - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ - type: 'done', - text: fullResponse, - threadId: capturedThreadId || undefined, - inputTokens: usage?.input_tokens, - outputTokens: usage?.output_tokens, - })}\n\n` - )); - } - } catch { - // Not JSON or partial — skip - } - } - }); - - child.stderr.on('data', (chunk: Buffer) => { - const errLines = chunk.toString().split('\n').map((line) => line.trim()).filter(Boolean); - const visibleLines = errLines.filter((line) => !shouldSuppressCodexStderrLine(line)); - if (visibleLines.length > 0) { - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ type: 'error', text: visibleLines.join('\n') })}\n\n` - )); - } - }); - - child.on('close', (code) => { - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ - type: 'close', - exitCode: code, - text: fullResponse, - threadId: capturedThreadId || undefined, - })}\n\n` - )); - closeStream(); - }); - - child.on('error', (err) => { - enqueueChunk(encoder.encode( - `data: ${JSON.stringify({ type: 'error', delivery: 'rejected', text: err.message })}\n\n` - )); - closeStream(); - }); - - child.stdin.end(); - }, - cancel() { - // The CLI process keeps its own transcript/session state. Client-side - // cancellation only releases the webview HTTP socket. - markClientGone?.(); - }, - }); - - return new Response(stream, { - headers: { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-store', - 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no', - }, - }); -} diff --git a/src/app/api/cortex/operator-corrections/route.ts b/src/app/api/cortex/operator-corrections/route.ts deleted file mode 100644 index da198d1c05..0000000000 --- a/src/app/api/cortex/operator-corrections/route.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server'; -import { resolveRequestPrincipal } from '@/lib/auth/principal'; -import { forgetCorrectionMemory, listCorrectionMemory } from '@/lib/cortex/correction-memory'; -import { invalidateAnswerCache } from '@/lib/cortex/qa/ask'; -import { publishCortexChange } from '@/lib/realtime/publisher'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; -const headers = { 'Cache-Control': 'no-store' }; -const refused = () => NextResponse.json({ ok: false, error: 'Operator authority is required.' }, { status: 403, headers }); - -export async function GET(request: NextRequest) { - if (resolveRequestPrincipal(request) !== 'operator') return refused(); - const params = request.nextUrl.searchParams; - const offset = Number(params.get('offset') ?? 0), limit = Number(params.get('limit') ?? 50); - if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100) { - return NextResponse.json({ ok: false, error: 'Use a nonnegative offset and a limit from 1 to 100.' }, { status: 400, headers }); - } - try { - return NextResponse.json({ ok: true, ...listCorrectionMemory({ offset, limit, - repoPaths: params.getAll('repoPath').map(value => value.trim()).filter(Boolean), query: params.get('query') ?? '', - projectId: params.has('projectId') ? params.get('projectId')?.trim() || null : undefined, - }) }, { headers }); - } catch { - return NextResponse.json({ ok: false, error: 'Could not load retained corrections. Try again.' }, { status: 500, headers }); - } -} - -export async function DELETE(request: NextRequest) { - if (resolveRequestPrincipal(request) !== 'operator') return refused(); - const body = await request.json().catch(() => null) as { id?: unknown; projectId?: unknown } | null; - if (!body || typeof body.id !== 'string' || !/^(approval|steer):[A-Za-z0-9._:-]{1,240}$/.test(body.id)) { - return NextResponse.json({ ok: false, error: 'A qualified correction ID is required.' }, { status: 400, headers }); - } - if (body.projectId !== undefined && body.projectId !== null && (typeof body.projectId !== 'string' || !body.projectId.trim())) { - return NextResponse.json({ ok: false, error: 'A valid project identity is required.' }, { status: 400, headers }); - } - const projectId = request.nextUrl.searchParams.has('projectId') - ? request.nextUrl.searchParams.get('projectId')?.trim() || null - : body.projectId === null ? null : typeof body.projectId === 'string' ? body.projectId.trim() : undefined; - if (projectId === undefined) { - return NextResponse.json({ ok: false, error: 'Select the correction project, including null for unscoped memory.' }, { status: 400, headers }); - } - if (request.nextUrl.searchParams.has('projectId') && body.projectId !== undefined && body.projectId !== projectId) { - return NextResponse.json({ ok: false, error: 'Correction not found in this project.' }, { status: 404, headers }); - } - try { - if (!forgetCorrectionMemory(body.id, projectId)) return NextResponse.json({ ok: false, error: 'Correction not found in this project.' }, { status: 404, headers }); - invalidateAnswerCache(); - await publishCortexChange({ scope: 'codebase-memory', reason: 'correction-forgotten' }); - return NextResponse.json({ ok: true, id: body.id }, { headers }); - } catch { - return NextResponse.json({ ok: false, error: 'Could not forget this correction. Try again.' }, { status: 500, headers }); - } -} diff --git a/src/app/api/panel/assign-issue/route.ts b/src/app/api/panel/assign-issue/route.ts deleted file mode 100644 index b8d2f3a912..0000000000 --- a/src/app/api/panel/assign-issue/route.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { readJsonObject } from '@/lib/panel/read-json-object'; -import { NextResponse } from 'next/server'; -import { addLabelsToGitHubIssue, commentOnGitHubIssue, resolveRepoSlug } from '@/lib/github-broker'; - -/** - * POST /api/panel/assign-issue - * Body: { issue: number, agent: string } - * - * Assigns a GitHub issue to an agent by adding a comment and label. - * Future: will actually spawn an agent session to work on the issue. - */ - -export async function POST(request: Request) { - try { - const body = await readJsonObject<{ issue: number; agent: string; repo?: string }>(request); - if (!body) { - return NextResponse.json({ error: 'Request body must be a JSON object.' }, { status: 400 }); - } - const { issue, agent, repo } = body; - - if (!issue || !agent) { - return NextResponse.json({ error: 'Missing issue or agent' }, { status: 400 }); - } - - const repoSlug = await resolveRepoSlug(repo ?? null, ''); - if (!repoSlug) { - return NextResponse.json({ error: 'Missing or invalid repo' }, { status: 400 }); - } - - // Add a comment noting the assignment - const comment = `🤖 Assigned to **${agent}** via o8 timeline drill-down.`; - try { - await commentOnGitHubIssue(repoSlug, issue, comment); - } catch { /* comment failed, continue anyway */ } - - // Add label - try { - await addLabelsToGitHubIssue(repoSlug, issue, [`agent:${String(agent).toLowerCase()}`]); - } catch { /* label may not exist, that's ok */ } - - return NextResponse.json({ - ok: true, - issue, - agent, - message: `Issue #${issue} assigned to ${agent}`, - }); - } catch (err) { - return NextResponse.json( - { error: err instanceof Error ? err.message : 'Unknown error' }, - { status: 500 } - ); - } -} diff --git a/src/app/api/panel/branches/checkout/route.ts b/src/app/api/panel/branches/checkout/route.ts deleted file mode 100644 index f3f616adf2..0000000000 --- a/src/app/api/panel/branches/checkout/route.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { readJsonObject } from '@/lib/panel/read-json-object'; -export const dynamic = 'force-dynamic'; - -import { NextRequest, NextResponse } from 'next/server'; -import { execFileSync } from '@/lib/providers/child-process'; -import { isSafeGitRef } from '@/lib/git/refs'; -import { knowledgeSourceWriteRefusal } from '@/lib/cortex/knowledge/sources'; - -export async function POST(req: NextRequest) { - try { - const body = await readJsonObject<{ - repoPath: string; - branch: string; - stash?: boolean; - force?: boolean; - }>(req); - if (!body) { - return NextResponse.json({ error: 'Request body must be a JSON object.' }, { status: 400 }); - } - - const { repoPath, branch, stash, force } = body; - if (!repoPath || !branch) { - return NextResponse.json({ error: 'repoPath and branch required' }, { status: 400 }); - } - if (!isSafeGitRef(branch)) { - return NextResponse.json({ error: 'Invalid branch name' }, { status: 400 }); - } - - const cwd = repoPath.replace(/^~/, process.env.HOME || require('os').homedir()); - const sourceRefusal = knowledgeSourceWriteRefusal(repoPath, cwd); - if (sourceRefusal) return sourceRefusal; - - // Check for uncommitted changes - let dirty = false; - let dirtyFiles: string[] = []; - try { - const status = execFileSync('git', ['status', '--porcelain'], { windowsHide: true, cwd, timeout: 5000 }).toString().trim(); - if (status) { - dirty = true; - dirtyFiles = status.split('\n').slice(0, 10); // First 10 files - } - } catch { - return NextResponse.json({ error: 'Failed to check git status' }, { status: 500 }); - } - - // If dirty and no stash/force requested, return warning - if (dirty && !stash && !force) { - return NextResponse.json({ - error: 'uncommitted_changes', - dirty: true, - fileCount: dirtyFiles.length, - files: dirtyFiles, - message: `${dirtyFiles.length} uncommitted change${dirtyFiles.length === 1 ? '' : 's'}. Stash or force checkout?`, - }, { status: 409 }); - } - - // Stash if requested - if (dirty && stash) { - try { - execFileSync('git', ['stash', 'push', '-m', `o8: auto-stash before switching to ${branch}`], { - windowsHide: true, - cwd, timeout: 10000, - }); - } catch (err) { - return NextResponse.json({ - error: `Stash failed: ${err instanceof Error ? err.message : 'unknown'}`, - }, { status: 500 }); - } - } - - // Checkout - try { - execFileSync('git', ['checkout', ...(force ? ['-f'] : []), branch], { - windowsHide: true, - cwd, timeout: 10000, - }); - } catch (err) { - const msg = err instanceof Error ? err.message : 'unknown'; - return NextResponse.json({ - error: `Checkout failed: ${msg}`, - }, { status: 500 }); - } - - // Verify current branch - let currentBranch = branch; - try { - currentBranch = execFileSync('git', ['branch', '--show-current'], { windowsHide: true, cwd, timeout: 5000 }).toString().trim(); - } catch { /* use requested branch */ } - - return NextResponse.json({ - success: true, - branch: currentBranch, - stashed: Boolean(dirty && stash), - }); - } catch (err) { - return NextResponse.json( - { error: err instanceof Error ? err.message : 'Failed to checkout' }, - { status: 500 }, - ); - } -} diff --git a/src/app/api/panel/cloud-workers/route.ts b/src/app/api/panel/cloud-workers/route.ts deleted file mode 100644 index 39ddcf7251..0000000000 --- a/src/app/api/panel/cloud-workers/route.ts +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Panel-side surface for scoped cloud worker keys and recent connections. - * - * Auth: this route is UI-facing, so it rides the panel middleware gate - * (loopback + ws-token). Individual cloud workers authenticate against - * /api/cloud/* with their own service-account keys — that's a separate - * credential tier. - * - * GET → list current cloud-worker keys + connection summary - * POST → { action: 'create_key', teamId, label } or { action: 'revoke_key', id } - */ -import { NextResponse } from 'next/server'; -import { - createCloudWorkerKey, - listCloudWorkerKeys, - revokeCloudWorkerKey, -} from '@/lib/cloud/worker-auth'; -import { listConnectedCloudWorkers } from '@/lib/cloud/worker-presence'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, max-age=0' }; - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value); -} - -function response(payload: unknown, status = 200) { - return NextResponse.json(payload, { status, headers: NO_STORE_HEADERS }); -} - -function toPublicShape(record: ReturnType[number]) { - return { - id: record.id, - teamId: record.teamId, - label: record.label, - createdAt: record.createdAt, - revokedAt: record.revokedAt ?? null, - }; -} - -export async function GET() { - try { - const keys = listCloudWorkerKeys().map(toPublicShape); - return response({ - keys, - connectedWorkers: listConnectedCloudWorkers(), - }); - } catch (error) { - console.error('[panel-cloud-workers] failed to list keys:', error); - return response({ error: 'Failed to load cloud worker keys.' }, 500); - } -} - -export async function POST(request: Request) { - try { - const body = await request.json().catch(() => null); - if (!isRecord(body) || typeof body.action !== 'string') { - return response({ error: 'Invalid request body.' }, 400); - } - - if (body.action === 'create_key') { - const teamId = typeof body.teamId === 'string' && body.teamId.trim() - ? body.teamId.trim() - : 'team_default'; - const label = typeof body.label === 'string' && body.label.trim() - ? body.label.trim() - : 'Unnamed worker pool'; - const { record, plaintext } = createCloudWorkerKey({ teamId, label }); - return response({ - id: record.id, - plaintextKey: plaintext, - record: toPublicShape(record), - }, 201); - } - - if (body.action === 'revoke_key') { - const id = typeof body.id === 'string' ? body.id.trim() : ''; - if (!id) { - return response({ error: 'id is required' }, 400); - } - const revoked = revokeCloudWorkerKey(id); - if (!revoked) { - return response({ error: 'Key not found' }, 404); - } - return response({ record: toPublicShape(revoked) }); - } - - return response({ error: `Unknown action: ${body.action}` }, 400); - } catch (error) { - console.error('[panel-cloud-workers] action failed:', error); - return response({ error: 'Cloud worker action failed.' }, 500); - } -} diff --git a/src/app/api/panel/commit-diff/route.ts b/src/app/api/panel/commit-diff/route.ts deleted file mode 100644 index 6fc7548de0..0000000000 --- a/src/app/api/panel/commit-diff/route.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { viewerGitJson } from '@/lib/viewers/git-response'; -import { viewerJson } from '@/lib/viewers/response'; -export const dynamic = 'force-dynamic'; - -import { getLocalCommitDiffFiles, isValidCommitHash, resolveWorkspaceRoot } from '@/lib/panel/git-commits'; - -export async function GET(request: Request) { - const { searchParams } = new URL(request.url); - const sha = searchParams.get('sha'); - const workspace = searchParams.get('workspace'); - - if (!sha) { - return viewerJson({ error: 'sha param required' }, { status: 400 }); - } - - if (!isValidCommitHash(sha)) { - return viewerJson({ error: 'Invalid commit hash' }, { status: 400 }); - } - - try { - const files = getLocalCommitDiffFiles(sha, workspace); - return viewerGitJson({ - sha, - workspace: resolveWorkspaceRoot(workspace), - files, - }, resolveWorkspaceRoot(workspace), { oldRef: `${sha}^`, newRef: sha }); - } catch (error) { - return viewerJson({ - sha, - workspace: resolveWorkspaceRoot(workspace), - files: [], - error: error instanceof Error ? error.message : 'Failed to fetch commit diff', - }, { status: 500 }); - } -} diff --git a/src/app/api/panel/dev-server/route.ts b/src/app/api/panel/dev-server/route.ts deleted file mode 100644 index d58eb66ae4..0000000000 --- a/src/app/api/panel/dev-server/route.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { readJsonObject } from '@/lib/panel/read-json-object'; -import { childEnvironment } from '@/lib/providers/spawn-environment'; -export const dynamic = 'force-dynamic'; - -import { NextRequest, NextResponse } from 'next/server'; -import { spawn, type ChildProcess } from '@/lib/providers/child-process'; -import { resolveRequestPrincipal } from '@/lib/auth/principal'; -import { knowledgeSourceWriteRefusal } from '@/lib/cortex/knowledge/sources'; - -// ── Active dev server processes ── -const activeServers = new Map(); - -// GET — list active dev servers -export async function GET(req: NextRequest) { - if (resolveRequestPrincipal(req) !== 'operator') { - return NextResponse.json({ error: 'Dev server controls are operator-only.' }, { status: 403 }); - } - const servers = Array.from(activeServers.entries()).map(([id, srv]) => ({ - id, - pid: srv.pid, - command: srv.command, - cwd: srv.cwd, - port: srv.port, - startedAt: srv.startedAt, - alive: !srv.process.killed, - lastOutput: srv.lastOutput.slice(-500), - })); - return NextResponse.json({ servers }); -} - -// POST — start a dev server -export async function POST(req: NextRequest) { - // Operator-only: this spawns an arbitrary shell (`sh -c ` below). A - // dispatched worker (local-worker token) must never reach this RCE primitive - // (SECURITY_AUDIT_2026-07-02 §HIGH-3). Only the desktop repo-card UI calls it. - if (resolveRequestPrincipal(req) !== 'operator') { - return NextResponse.json({ error: 'Starting a dev server is operator-only.' }, { status: 403 }); - } - try { - const body = await readJsonObject<{ - repoPath: string; - command: string; - port?: number; - }>(req); - if (!body) { - return NextResponse.json({ error: 'Request body must be a JSON object.' }, { status: 400 }); - } - - const { repoPath, command, port } = body; - if (!repoPath || !command) { - return NextResponse.json({ error: 'repoPath and command required' }, { status: 400 }); - } - - // Check if already running for this repo - const existingId = `dev-${repoPath}`; - const existing = activeServers.get(existingId); - if (existing && !existing.process.killed) { - return NextResponse.json({ - error: 'Dev server already running for this repo', - pid: existing.pid, - port: existing.port, - }, { status: 409 }); - } - - // Resolve path - const cwd = repoPath.replace(/^~/, process.env.HOME || require('os').homedir()); - const sourceRefusal = knowledgeSourceWriteRefusal(repoPath, cwd); - if (sourceRefusal) return sourceRefusal; - - // Spawn the dev server - const child = spawn('sh', ['-c', command], { - windowsHide: true, - cwd, - stdio: ['ignore', 'pipe', 'pipe'], - detached: true, - env: childEnvironment({ env: { FORCE_COLOR: '0', NO_COLOR: '1' } }), - }); - - const serverEntry = { - process: child, - pid: child.pid ?? 0, - command, - cwd, - port: port ?? null, - startedAt: Date.now(), - lastOutput: '', - }; - - // Capture output for status display - child.stdout?.on('data', (data: Buffer) => { - serverEntry.lastOutput += data.toString(); - // Keep last 2K - if (serverEntry.lastOutput.length > 2048) { - serverEntry.lastOutput = serverEntry.lastOutput.slice(-1024); - } - // Try to detect port from output - if (!serverEntry.port) { - const portMatch = data.toString().match(/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d+)/); - if (portMatch) serverEntry.port = parseInt(portMatch[1], 10); - } - }); - - child.stderr?.on('data', (data: Buffer) => { - serverEntry.lastOutput += data.toString(); - if (serverEntry.lastOutput.length > 2048) { - serverEntry.lastOutput = serverEntry.lastOutput.slice(-1024); - } - if (!serverEntry.port) { - const portMatch = data.toString().match(/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d+)/); - if (portMatch) serverEntry.port = parseInt(portMatch[1], 10); - } - }); - - child.on('exit', () => { - activeServers.delete(existingId); - }); - - // Unref so the process doesn't keep the server alive - child.unref(); - activeServers.set(existingId, serverEntry); - - return NextResponse.json({ - started: true, - id: existingId, - pid: child.pid, - command, - port: port ?? null, - }); - } catch (err) { - return NextResponse.json( - { error: err instanceof Error ? err.message : 'Failed to start dev server' }, - { status: 500 }, - ); - } -} - -// DELETE — stop a dev server -export async function DELETE(req: NextRequest) { - if (resolveRequestPrincipal(req) !== 'operator') { - return NextResponse.json({ error: 'Stopping a dev server is operator-only.' }, { status: 403 }); - } - try { - const body = await readJsonObject<{ repoPath: string }>(req); - if (!body) { - return NextResponse.json({ error: 'Request body must be a JSON object.' }, { status: 400 }); - } - const id = `dev-${body.repoPath}`; - const server = activeServers.get(id); - - if (!server) { - // Try to find by port scan and kill - return NextResponse.json({ error: 'No active dev server for this repo' }, { status: 404 }); - } - - // Kill the process group (negative PID kills the group) - try { - if (server.process.pid) { - process.kill(-server.process.pid, 'SIGTERM'); - } - } catch { - // Process might already be dead - try { - server.process.kill('SIGTERM'); - } catch { /* already dead */ } - } - - activeServers.delete(id); - - return NextResponse.json({ - stopped: true, - id, - pid: server.pid, - }); - } catch (err) { - return NextResponse.json( - { error: err instanceof Error ? err.message : 'Failed to stop dev server' }, - { status: 500 }, - ); - } -} diff --git a/src/app/api/panel/file-preview/route.ts b/src/app/api/panel/file-preview/route.ts deleted file mode 100644 index 1d3e04417d..0000000000 --- a/src/app/api/panel/file-preview/route.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { viewerBytes } from '@/lib/viewers/bytes'; -import { isVerifiableRasterType, viewerImageBytes } from '@/lib/viewers/image-bytes'; -import { viewerJson } from '@/lib/viewers/response'; -export const dynamic = 'force-dynamic'; - -import { extname } from 'node:path'; -import { expandHome } from '@/lib/fs/safe-path'; -import { isWorkspaceFileError, openWorkspaceFile } from '@/lib/fs/workspace-file'; -import { getDefaultLlmRepoRoot, resolveRegisteredRepoScope } from '@/lib/llm/repo-scope'; - -const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg', '.ico', '.bmp']); -const MIME_MAP: Record = { - '.png': 'image/png', - '.jpg': 'image/jpeg', - '.jpeg': 'image/jpeg', - '.gif': 'image/gif', - '.webp': 'image/webp', - '.avif': 'image/avif', - '.svg': 'image/svg+xml', - '.ico': 'image/x-icon', - '.bmp': 'image/bmp', -}; - -export async function GET(request: Request) { - const { searchParams } = new URL(request.url); - const filePath = searchParams.get('path'); - const workspaceParam = searchParams.get('workspace'); - - if (!filePath) { - return viewerJson({ error: 'path param required' }, { status: 400 }); - } - - let root: string | null = getDefaultLlmRepoRoot(); - if (workspaceParam) { - const scope = await resolveRegisteredRepoScope(expandHome(workspaceParam)); - root = scope.repoRoot; - } - if (!root) { - return viewerJson({ error: 'Workspace is not a registered repository' }, { status: 400 }); - } - - const ext = extname(filePath).toLowerCase(); - if (!IMAGE_EXTENSIONS.has(ext)) { - return viewerJson({ error: 'Not an image file' }, { status: 400 }); - } - - let opened: Awaited> | null = null; - try { - opened = await openWorkspaceFile(root, filePath, 'read'); - // Limit to 10MB - if (opened.stat.size > 10 * 1024 * 1024) { - return viewerJson({ error: 'File too large (>10MB)' }, { status: 400 }); - } - - const buffer = await opened.handle.readFile(); - const mimeType = MIME_MAP[ext] || 'application/octet-stream'; - - // For SVGs, return as text - if (ext === '.svg') { - return viewerJson({ - type: 'svg', - content: buffer.toString('utf-8'), - mimeType, - size: opened.stat.size, - path: filePath, - }); - } - - // SVG returns as JSON text above; serve verifiable rasters through the image - // path (#4773 otherwise refuses them) and keep any other type on the text viewer. - return isVerifiableRasterType(mimeType) ? viewerImageBytes(buffer, mimeType) : viewerBytes(buffer, mimeType); - } catch (error) { - if (isWorkspaceFileError(error)) { - return viewerJson({ error: error.message, code: error.code }, { status: error.status }); - } - return viewerJson({ error: 'Could not read file', code: 'workspace_file_operation_failed' }, { status: 500 }); - } finally { - await opened?.handle.close().catch(() => {}); - } -} diff --git a/src/app/api/panel/ide-surface/route.ts b/src/app/api/panel/ide-surface/route.ts deleted file mode 100644 index 608205af60..0000000000 --- a/src/app/api/panel/ide-surface/route.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { readJsonObject } from '@/lib/panel/read-json-object'; -export const dynamic = 'force-dynamic'; - -import { NextResponse } from 'next/server'; -import { readIdeSurfaceState, writeIdeSurfaceState } from '@/lib/runtime/ide-surface-state'; - -export async function GET() { - return NextResponse.json(readIdeSurfaceState()); -} - -export async function POST(request: Request) { - try { - const body = await readJsonObject<{ - terminalRepoPaths?: string[]; - activeRepoPath?: string | null; - }>(request); - if (!body) { - return NextResponse.json({ error: 'Request body must be a JSON object.' }, { status: 400 }); - } - const next = writeIdeSurfaceState({ - terminalRepoPaths: body.terminalRepoPaths, - activeRepoPath: body.activeRepoPath, - }); - return NextResponse.json(next); - } catch (error) { - return NextResponse.json( - { error: error instanceof Error ? error.message : 'Failed to persist IDE surface state.' }, - { status: 500 }, - ); - } -} diff --git a/src/app/api/panel/mcp-test/route.ts b/src/app/api/panel/mcp-test/route.ts deleted file mode 100644 index b323474a20..0000000000 --- a/src/app/api/panel/mcp-test/route.ts +++ /dev/null @@ -1,103 +0,0 @@ -export const dynamic = 'force-dynamic'; - -/** - * Panel-gated "test connection" probe for a registered external MCP server. - * - * POST /api/panel/mcp-test { serverName?: string; serverId?: string } - * - * Spawns the server (stdio) or hits its URL (http), sends `initialize` + - * `tools/list` over JSON-RPC, and returns the tool count or a structured - * error. The child is killed afterward so we never leave an orphan. - * - * Also accepts an inline config (no DB lookup) for the "add server" form - * so users can preflight before saving. - */ - -import { NextRequest, NextResponse } from 'next/server'; -import { requirePanelAuth } from '@/lib/panel/auth'; -import { listExternalMcpServers, externalServerToMcpConfig } from '@/lib/mcp/external-servers'; -import { testMcpConnection, type McpTestInput } from '@/lib/mcp/test-connection'; - -interface TestRequestBody { - serverId?: string; - serverName?: string; - inline?: { - transport?: 'stdio' | 'http'; - command?: string; - args?: string[]; - env?: Record; - url?: string; - headers?: Record; - }; -} - -function resolveInputByLookup(body: TestRequestBody): McpTestInput | { error: string } { - const servers = listExternalMcpServers(); - const target = body.serverId - ? servers.find((s) => s.id === body.serverId) - : body.serverName - ? servers.find((s) => s.name === body.serverName) - : null; - if (!target) { - return { error: 'Server not found' }; - } - const config = externalServerToMcpConfig(target); - if (config.type === 'http') { - return { - transport: 'http', - url: config.url, - headers: config.headers, - }; - } - return { - transport: 'stdio', - command: config.command, - args: config.args, - env: config.env, - }; -} - -function resolveInlineInput(inline: NonNullable): McpTestInput | { error: string } { - if (inline.transport === 'http') { - const url = typeof inline.url === 'string' ? inline.url.trim() : ''; - if (!url) return { error: 'HTTP test needs a url' }; - return { - transport: 'http', - url, - headers: inline.headers, - }; - } - const command = typeof inline.command === 'string' ? inline.command.trim() : ''; - if (!command) return { error: 'stdio test needs a command' }; - return { - transport: 'stdio', - command, - args: Array.isArray(inline.args) ? inline.args.filter((a): a is string => typeof a === 'string') : [], - env: inline.env ?? undefined, - }; -} - -export async function POST(request: NextRequest) { - const denied = requirePanelAuth(request); - if (denied) return denied; - - const body = await request.json().catch(() => ({})) as TestRequestBody; - - const resolved = body.inline - ? resolveInlineInput(body.inline) - : resolveInputByLookup(body); - - if ('error' in resolved) { - return NextResponse.json({ ok: false, error: resolved.error }, { status: 400 }); - } - - try { - const result = await testMcpConnection(resolved); - return NextResponse.json(result); - } catch (error) { - return NextResponse.json( - { ok: false, error: error instanceof Error ? error.message : 'Test failed' }, - { status: 500 }, - ); - } -} diff --git a/src/app/api/panel/pr/review/route.ts b/src/app/api/panel/pr/review/route.ts deleted file mode 100644 index 9658a4b982..0000000000 --- a/src/app/api/panel/pr/review/route.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { resolveRequestPrincipalContext } from '@/lib/auth/principal'; -import { PrMergeRefused } from '@/lib/github-broker/pr-merge-gate'; -import { PublicationUnknown, PublicationRefused } from '@/lib/github-broker/publication'; -import { NextResponse } from 'next/server'; -import { - DEFAULT_GITHUB_REPO, - commentOnGitHubPullRequest, - invalidateGitHubSync, - mergeGitHubPullRequest, - resolveRepoSlug, - reviewGitHubPullRequest, -} from '@/lib/github-broker'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -export async function POST(request: Request) { - const body = await request.json().catch(() => null) as { - repo?: string | null; - number?: number | string | null; - action?: string | null; - comment?: string | null; - commitSha?: string; - mergeMethod?: 'merge' | 'squash' | 'rebase'; - expectedMergeGate?: string; - } | null; - - const prNumber = typeof body?.number === 'number' - ? body.number - : typeof body?.number === 'string' - ? parseInt(body.number, 10) - : Number.NaN; - const action = body?.action?.trim() ?? ''; - const comment = body?.comment?.trim() ?? ''; - const repo = await resolveRepoSlug(body?.repo ?? null, DEFAULT_GITHUB_REPO); - - if (!repo || !/^[\w.-]+\/[\w.-]+$/.test(repo)) { - return NextResponse.json({ error: 'Invalid repo format' }, { status: 400 }); - } - - if (!Number.isFinite(prNumber) || prNumber < 1) { - return NextResponse.json({ error: 'Valid pull request number required' }, { status: 400 }); - } - - if (!action) { - return NextResponse.json({ error: 'Action is required' }, { status: 400 }); - } - - try { - if (action === 'approve') { - await reviewGitHubPullRequest(repo, prNumber, { event: 'APPROVE', body: comment || undefined }); - invalidateGitHubSync(repo, 'pull_requests'); - return NextResponse.json({ ok: true, success: true, action: 'approved' }); - } - - if (action === 'request_changes') { - if (!comment) { - return NextResponse.json({ error: 'Comment required for request_changes' }, { status: 400 }); - } - await reviewGitHubPullRequest(repo, prNumber, { event: 'REQUEST_CHANGES', body: comment }); - invalidateGitHubSync(repo, 'pull_requests'); - return NextResponse.json({ ok: true, success: true, action: 'changes_requested' }); - } - - if (action === 'comment') { - if (!comment) { - return NextResponse.json({ error: 'Comment text required' }, { status: 400 }); - } - await commentOnGitHubPullRequest(repo, prNumber, comment); - return NextResponse.json({ ok: true, success: true, action: 'commented' }); - } - - if (action === 'merge') { - if (typeof body?.commitSha !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(body.commitSha)) return NextResponse.json({ code: 'approved_head_required', message: 'The approved head SHA is required. Send it as commitSha.', error: 'The approved head SHA is required. Send it as commitSha.' }, { status: 400 }); - const result = await mergeGitHubPullRequest(repo, prNumber, { deleteBranch: true, expectedHeadSha: body.commitSha, - mergeMethod: body.mergeMethod, expectedMergeGate: body.expectedMergeGate, principal: resolveRequestPrincipalContext(request).role }); - invalidateGitHubSync(repo, 'pull_requests'); - return NextResponse.json({ ok: true, success: true, action: result.publication.status, publication: result.publication }); - } - - return NextResponse.json({ error: `Unknown action: ${action}` }, { status: 400 }); - } catch (error) { - if (error instanceof PublicationRefused) return NextResponse.json({ ok: false, mergeRefused: true, error: error.message, publication: error.receipt }, { status: 409 }); - if (error instanceof PublicationUnknown) return NextResponse.json({ ok: false, outcomeUnknown: true, error: error.message, publication: error.receipt }, { status: 202 }); - if (error instanceof PrMergeRefused) return NextResponse.json({ ok: false, mergeRefused: true, error: error.message, mergeGate: error.gate }, { status: 409 }); - const message = error instanceof Error ? error.message : `${action} failed`; - return NextResponse.json({ error: message }, { status: 500 }); - } -} diff --git a/src/app/api/panel/readme/route.ts b/src/app/api/panel/readme/route.ts deleted file mode 100644 index 7fd950c0db..0000000000 --- a/src/app/api/panel/readme/route.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { viewerJson } from '@/lib/viewers/response'; -export const dynamic = 'force-dynamic'; - -import { readFile } from 'node:fs/promises'; -import { join } from 'node:path'; -import { existsSync } from 'node:fs'; - -const DEFAULT_ROOT = process.env.CORTEX_IDE_REVIEW_REPO_ROOT || process.cwd(); - -export async function GET(request: Request) { - const { searchParams } = new URL(request.url); - const workspaceParam = searchParams.get('workspace'); - - const home = process.env.HOME || require('os').homedir(); - let root = DEFAULT_ROOT; - if (workspaceParam) { - root = workspaceParam.startsWith('~') ? workspaceParam.replace('~', home) : workspaceParam; - } - - // Try common readme filenames - const candidates = ['README.md', 'readme.md', 'Readme.md', 'README.MD', 'README']; - for (const name of candidates) { - const filePath = join(root, name); - if (existsSync(filePath)) { - try { - const content = await readFile(filePath, 'utf-8'); - return viewerJson({ content, fileName: name, workspace: workspaceParam ?? root }); - } catch { - continue; - } - } - } - - return viewerJson({ content: null, workspace: workspaceParam ?? root }); -} diff --git a/src/app/api/panel/report-artifact/route.ts b/src/app/api/panel/report-artifact/route.ts deleted file mode 100644 index c3d2eda8b1..0000000000 --- a/src/app/api/panel/report-artifact/route.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { viewerJson } from '@/lib/viewers/response'; -export const dynamic = 'force-dynamic'; -export const runtime = 'nodejs'; - -import { readFile } from 'node:fs/promises'; -import { getArtifact, artifactAbsPath } from '@/lib/artifacts/store'; - -/** - * Serve a stored `report` artifact's HTML by id (#1491). The path is resolved - * from the DB record (never caller-supplied), so there is no traversal surface. - * Returns `{ html }` so the review surface can render it in a sandboxed iframe - * srcDoc (allow-scripts, no same-origin) — the same trust model as HtmlPreview. - */ -export async function GET(request: Request) { - const { searchParams } = new URL(request.url); - const id = searchParams.get('id'); - if (!id) { - return viewerJson({ error: 'id param required' }, { status: 400 }); - } - - const record = getArtifact(id); - if (!record || record.kind !== 'report') { - return viewerJson({ error: 'Report not found' }, { status: 404 }); - } - - try { - const html = await readFile(artifactAbsPath(record.relPath), 'utf8'); - return viewerJson({ html }, { headers: { 'Cache-Control': 'no-store' } }); - } catch { - return viewerJson({ error: 'Could not read report' }, { status: 500 }); - } -} diff --git a/src/app/api/panel/terminal-exec/route.ts b/src/app/api/panel/terminal-exec/route.ts deleted file mode 100644 index b627073199..0000000000 --- a/src/app/api/panel/terminal-exec/route.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { readJsonObject } from '@/lib/panel/read-json-object'; -export const dynamic = 'force-dynamic'; - -import { NextResponse } from 'next/server'; -import { getOrCreateWsToken } from '@/lib/ws-auth'; -import { resolvePortInfo } from '@/lib/panel/api-port'; - -/** - * POST /api/panel/terminal-exec - * Sends a command to a dashboard terminal session owned by the WS bridge. - */ -export async function POST(request: Request) { - try { - const wsToken = getOrCreateWsToken(); - const { wsPort } = resolvePortInfo(); - const body = await readJsonObject<{ sessionName: string; command: string }>(request); - if (!body) { - return NextResponse.json({ error: 'Request body must be a JSON object.' }, { status: 400 }); - } - const { sessionName, command } = body; - - if (!sessionName || !command) { - return NextResponse.json({ error: 'sessionName and command required' }, { status: 400 }); - } - - // Validate session name (prevent injection) - if (!/^cortex-dash-[a-f0-9]+$/.test(sessionName)) { - return NextResponse.json({ error: 'Invalid session name' }, { status: 400 }); - } - - const response = await fetch(`http://127.0.0.1:${wsPort}/terminal-exec`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${wsToken}`, - }, - body: JSON.stringify({ sessionName, command }), - cache: 'no-store', - }); - if (!response.ok) { - const data = await response.json().catch(() => ({})) as { error?: string }; - return NextResponse.json({ error: data.error || 'Failed to execute command' }, { status: response.status }); - } - - return NextResponse.json({ ok: true }); - } catch (error) { - return NextResponse.json( - { error: error instanceof Error ? error.message : 'Failed to execute command' }, - { status: 500 }, - ); - } -} diff --git a/src/app/api/panel/workers/route.ts b/src/app/api/panel/workers/route.ts deleted file mode 100644 index 865403f9de..0000000000 --- a/src/app/api/panel/workers/route.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { NextResponse } from 'next/server'; -import { getRuntime } from '@/lib/runtimes'; -import { getRemoteRuntimeFlag, setRemoteRuntimeFlag } from '@/lib/worker/feature-flags'; -import { createToken, getFleetStatus, listTokens, revokeToken } from '@/lib/worker/tokens'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, max-age=0' }; - -function response(payload: unknown, status = 200) { - return NextResponse.json(payload, { - status, - headers: NO_STORE_HEADERS, - }); -} - -function isRecord(value: unknown): value is Record { - return Boolean(value) && typeof value === 'object' && !Array.isArray(value); -} - -function parsePositiveInteger(value: unknown): number | undefined { - if (typeof value === 'number' && Number.isFinite(value)) { - return Math.max(1, Math.floor(value)); - } - if (typeof value === 'string' && value.trim()) { - const parsed = Number(value); - if (Number.isFinite(parsed)) { - return Math.max(1, Math.floor(parsed)); - } - } - return undefined; -} - -async function buildWorkersResponse() { - return { - tokens: listTokens(), - fleet: getFleetStatus(), - remoteFlag: await getRemoteRuntimeFlag(), - remoteRuntimeRegistered: Boolean(getRuntime('remote-customer')), - }; -} - -export async function GET() { - try { - return response(await buildWorkersResponse()); - } catch (error) { - console.error('[panel-workers] Failed to load workers data:', error); - return response({ error: 'Failed to load workers settings.' }, 500); - } -} - -export async function POST(request: Request) { - try { - const body = await request.json().catch(() => null); - if (!isRecord(body) || typeof body.action !== 'string') { - return response({ error: 'Invalid request body.' }, 400); - } - - if (body.action === 'create_token') { - const label = typeof body.label === 'string' ? body.label.trim() : ''; - if (!label) { - return response({ error: 'Token label is required.' }, 400); - } - - return response(createToken({ - label, - scope: typeof body.scope === 'string' ? body.scope.trim() : undefined, - maxWorkers: parsePositiveInteger(body.maxWorkers), - }), 201); - } - - if (body.action === 'revoke_token') { - const id = typeof body.id === 'string' ? body.id.trim() : ''; - if (!id) { - return response({ error: 'Token id is required.' }, 400); - } - - if (!revokeToken(id)) { - return response({ error: 'Token not found.' }, 404); - } - - return response({ ok: true }); - } - - if (body.action === 'set_remote_flag') { - if (typeof body.enabled !== 'boolean') { - return response({ error: 'enabled must be a boolean.' }, 400); - } - - await setRemoteRuntimeFlag(body.enabled); - return response({ - ok: true, - ...await buildWorkersResponse(), - }); - } - - return response({ error: 'Unknown action.' }, 400); - } catch (error) { - console.error('[panel-workers] Failed to update workers data:', error); - return response({ error: 'Failed to update workers settings.' }, 500); - } -} diff --git a/src/app/api/panel/worktree-diff/route.ts b/src/app/api/panel/worktree-diff/route.ts deleted file mode 100644 index 2cbbb6812e..0000000000 --- a/src/app/api/panel/worktree-diff/route.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { viewerGitJson } from '@/lib/viewers/git-response'; -import { viewerJson } from '@/lib/viewers/response'; -export const dynamic = 'force-dynamic'; - -import { execFileSync } from '@/lib/providers/child-process'; -import os from 'os'; - -/** - * Working-tree diff for a repo — "what have I changed" as one payload, - * shaped like the lane diff route so the canvas diff card renders either - * source unchanged: { ok, branch, stat, diff, truncated }. - */ -export async function GET(request: Request) { - const { searchParams } = new URL(request.url); - const workspaceParam = searchParams.get('workspace') ?? searchParams.get('repoPath'); - const maxBytes = Math.min(512 * 1024, Math.max(16 * 1024, Number(searchParams.get('maxBytes')) || 131_072)); - if (!workspaceParam) { - return viewerJson({ ok: false, error: 'workspace param required' }, { status: 400 }); - } - const root = workspaceParam.startsWith('~') ? workspaceParam.replace('~', os.homedir()) : workspaceParam; - try { - const stat = execFileSync('git', ['diff', '--no-color', '--stat', 'HEAD'], { - windowsHide: true, - cwd: root, encoding: 'utf-8', timeout: 8000, maxBuffer: 1024 * 1024, - }); - let diff = execFileSync('git', ['diff', '--no-color', 'HEAD'], { - windowsHide: true, - cwd: root, encoding: 'utf-8', timeout: 8000, maxBuffer: 4 * 1024 * 1024, - }); - // `git diff HEAD` omits untracked (new) files — append them as new-file - // diffs so the canvas card shows new files too, matching the default - // review snapshot's completeness. Read-only (`--no-index`, `--exclude-standard` - // respects .gitignore); never stages or touches the index. - try { - const untracked = execFileSync('git', ['ls-files', '--others', '--exclude-standard'], { - windowsHide: true, - cwd: root, encoding: 'utf-8', timeout: 5000, maxBuffer: 1024 * 1024, - }).split('\n').map((line) => line.trim()).filter(Boolean); - for (const file of untracked) { - if (Buffer.byteLength(diff, 'utf-8') > maxBytes) break; - try { - execFileSync('git', ['diff', '--no-color', '--no-index', '--', '/dev/null', file], { - windowsHide: true, - cwd: root, encoding: 'utf-8', timeout: 5000, maxBuffer: 1024 * 1024, - }); - } catch (untrackedError) { - // --no-index always "differs" vs /dev/null → exits 1, so the diff - // text comes back on the thrown error's stdout. - const out = (untrackedError as { stdout?: string }).stdout ?? ''; - if (out) diff += (diff && !diff.endsWith('\n') ? '\n' : '') + out; - } - } - } catch { - // no untracked files, or git error — the tracked diff still stands - } - let branch = ''; - try { - branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { windowsHide: true, cwd: root, encoding: 'utf-8', timeout: 3000 }).trim(); - } catch { - // detached/fresh repo — branch stays blank - } - const truncated = Buffer.byteLength(diff, 'utf-8') > maxBytes; - if (truncated) diff = diff.slice(0, maxBytes); - return viewerGitJson({ ok: true, branch, stat: stat.trim(), diff, truncated }, root); - } catch (error) { - return viewerJson({ ok: false, error: error instanceof Error ? error.message : 'git diff failed' }); - } -} diff --git a/src/app/api/review/diff/route.ts b/src/app/api/review/diff/route.ts deleted file mode 100644 index 7fa47d7e7f..0000000000 --- a/src/app/api/review/diff/route.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { viewerGitJson } from '@/lib/viewers/git-response'; -import { viewerJson } from '@/lib/viewers/response'; -import { execFile } from '@/lib/providers/child-process'; -import os from 'node:os'; -import path from 'node:path'; -import { promisify } from 'node:util'; - -import { getWorkspaceReviewSnapshot } from '@/lib/review/workspace'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -const exec = promisify(execFile); -const MAX_BYTES = 131072; -const MAX_BUFFER = 16 * 1024 * 1024; - -/** - * GET /api/review/diff — the active review's unified diff, for the canvas to - * render as a PR review card. The Alerts "Review ready · PR #N" row resolves - * to THIS, not the unrelated working-tree diff of whatever repo the canvas - * happens to point at (that mismatch was the bug this fixes). - * - * The alert is titled by its pull request, so the diff follows the PR: pull - * the committed patch straight from GitHub (`gh api …/pulls/N/files`). Only - * when no PR is attached do we fall back to the review repo's working tree - * (`git diff HEAD`, the same baseline workspace.ts uses). Gated loopback-only - * via the `/api/review/` middleware prefix. - */ -function expandHome(p: string): string { - if (p === '~') return os.homedir(); - if (p.startsWith('~/')) return path.join(os.homedir(), p.slice(2)); - return p; -} - -interface PrFile { - filename: string; - previous_filename?: string; - status?: string; - additions?: number; - deletions?: number; - patch?: string; -} - -/** PR #N's committed diff straight from GitHub — the alert names a PR, so the - * card shows that PR, not the local tree. Assembles a combined unified diff - * from the per-file patches plus a path-level stat. */ -async function loadPrDiff(repoSlug: string, prNumber: number): Promise<{ diff: string; stat: string } | null> { - try { - const { stdout } = await exec('gh', ['api', `repos/${repoSlug}/pulls/${prNumber}/files?per_page=100`], { windowsHide: true, maxBuffer: MAX_BUFFER }); - const files = JSON.parse(stdout) as PrFile[]; - if (!Array.isArray(files) || !files.length) return null; - const diff = files - .filter((file) => file.patch) - .map((file) => `diff --git a/${file.previous_filename ?? file.filename} b/${file.filename}\n${file.patch}`) - .join('\n\n'); - const stat = files - .map((file) => `${file.filename} +${file.additions ?? 0} -${file.deletions ?? 0}`) - .join('\n'); - return { diff, stat }; - } catch { - return null; - } -} - -/** The review repo's working tree vs HEAD — the fallback when no PR is attached. - * repoPath is ~-shortened by the snapshot, so expand before `git -C`. */ -async function loadLocalDiff(repoPath: string): Promise<{ diff: string; stat: string }> { - const run = async (args: string[]) => { - try { - const { stdout } = await exec('git', ['-C', repoPath, ...args], { windowsHide: true, maxBuffer: MAX_BUFFER }); - return stdout; - } catch { - return ''; - } - }; - const [diff, stat] = await Promise.all([ - run(['diff', '--no-ext-diff', '-M', 'HEAD']), - run(['diff', '--stat=120', 'HEAD']), - ]); - return { diff, stat: stat.trim() }; -} - -export async function GET(request: Request) { - try { - const { searchParams } = new URL(request.url); - const workspacePath = searchParams.get('workspace') || undefined; - const repoSlug = searchParams.get('repo') || undefined; - - const snapshot = await getWorkspaceReviewSnapshot({ workspacePath, repoSlug }); - const lead = snapshot.pullRequests[0]; - - let source: 'pull_request' | 'local' | 'none' = 'none'; - let diff = ''; - let stat = snapshot.diffStat || ''; - - if (lead && snapshot.repoSlug) { - const pr = await loadPrDiff(snapshot.repoSlug, lead.number); - if (pr && pr.diff.trim()) { - diff = pr.diff; - stat = pr.stat || stat; - source = 'pull_request'; - } - } - if (!diff.trim() && snapshot.repoPath) { - const local = await loadLocalDiff(expandHome(snapshot.repoPath)); - if (local.diff.trim()) { - diff = local.diff; - stat = local.stat || stat; - source = 'local'; - } - } - - const truncated = diff.length > MAX_BYTES; - return viewerGitJson({ - ok: true, - source, - branch: snapshot.branch, - stat, - diff: truncated ? diff.slice(0, MAX_BYTES) : diff, - truncated, - changedFiles: snapshot.changedFiles?.length ?? 0, - prNumber: lead?.number ?? null, - prTitle: lead?.title ?? null, - prUrl: lead?.url ?? null, - }, source === 'local' && snapshot.repoPath ? expandHome(snapshot.repoPath) : ''); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to load review diff'; - console.error('[review/diff]', message); - return viewerJson({ ok: false, reason: message }, { status: 500 }); - } -} diff --git a/src/app/api/review/file/route.ts b/src/app/api/review/file/route.ts deleted file mode 100644 index 44da9cf05a..0000000000 --- a/src/app/api/review/file/route.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { viewerGitJson } from '@/lib/viewers/git-response'; -import { getDefaultLlmRepoRoot } from '@/lib/llm/repo-scope'; -import { viewerJson } from '@/lib/viewers/response'; -import { NextRequest } from 'next/server'; -import { getReviewFileDetail } from '@/lib/review/workspace'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -export async function GET(request: NextRequest) { - const reviewPath = request.nextUrl.searchParams.get('path')?.trim(); - - if (!reviewPath) { - return viewerJson({ error: 'Review file path is required.' }, { status: 400 }); - } - - try { - const file = await getReviewFileDetail(reviewPath); - return viewerGitJson( - { file }, getDefaultLlmRepoRoot(), {}, - { - headers: { - 'Cache-Control': 'no-store, max-age=0', - }, - }, - ); - } catch (error) { - const message = error instanceof Error ? error.message : 'Unable to load review file detail'; - const status = message.includes('no longer part of the live review surface') ? 404 : 500; - - return viewerJson({ error: message }, { status }); - } -} diff --git a/src/app/api/telemetry/config/route.ts b/src/app/api/telemetry/config/route.ts deleted file mode 100644 index 01a29bf382..0000000000 --- a/src/app/api/telemetry/config/route.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * GET /api/telemetry/config — the webview's Sentry bootstrap. - * - * Returns the resolved Sentry runtime config: the baked DSN (only ever non-empty - * in a PACKAGED build — dev returns ''), the "Crash & error reports" toggle, the - * app version (release), plan, and a `founder` BOOLEAN (never the operator - * number). The webview (sentry-browser.ts) inits @sentry/browser only when `dsn` - * is non-empty and re-polls this route to honor the toggle within ~30s. - * - * Gated by the default-deny middleware (loopback / ws-token) like every other - * /api route — the webview is loopback so it passes; no allowlist entry. Carries - * NO identity: no user id, no email, no machine name. NEVER throws. - */ - -import { NextResponse } from 'next/server'; - -import { resolveSentryConfig } from '@/lib/telemetry/sentry-config'; - -export const runtime = 'nodejs'; -export const dynamic = 'force-dynamic'; - -const NO_STORE = { 'Cache-Control': 'no-store, max-age=0' }; - -const DORMANT = { - dsn: '', - enabled: false, - release: 'unknown', - environment: 'production', - plan: 'free', - founder: false, -}; - -export async function GET() { - try { - const cfg = resolveSentryConfig(); - return NextResponse.json( - { - dsn: cfg.dsn, - enabled: cfg.enabled, - release: cfg.release, - environment: cfg.environment, - plan: cfg.plan, - founder: cfg.founder, - }, - { headers: NO_STORE }, - ); - } catch { - // Structured fallback — never throw out of an API route. Dormant is safe. - return NextResponse.json(DORMANT, { status: 200, headers: NO_STORE }); - } -} diff --git a/src/app/api/worktrees/merge/handler.ts b/src/app/api/worktrees/merge/handler.ts deleted file mode 100644 index bfc1fee38e..0000000000 --- a/src/app/api/worktrees/merge/handler.ts +++ /dev/null @@ -1,568 +0,0 @@ -/** - * Worktree Merge API - * - * POST /api/worktrees/merge — Create PR, merge to main, or discard a worktree - * - * @see https://github.com/o8-run/o8/issues/70 - */ - -import path from 'node:path'; -import { prFirstMergeRefusal } from '@/lib/lane/pr-first-delivery'; -import { NextResponse, type NextRequest } from 'next/server'; -import { resolveRequestPrincipal } from '@/lib/auth/principal'; -import { pushLfsObjects } from '@/lib/git/lfs-push'; -import { NO_REPOSITORY_HOOKS } from '@/lib/git/no-repository-hooks'; -import { assertLaneHeadOnBranch, laneGit } from '@/lib/lane/lane-git'; -import { readLaneCreationBaseCommit } from '@/lib/lane/creation-base'; -import { listLanes } from '@/lib/lane/registry'; -import { commitDirtyWorktree } from '@/lib/lane/worktree-merge-git'; -import { findRepoByLocalPath } from '@/lib/repos/registry'; -import { requirePanelAuth } from '@/lib/panel/auth'; -import { requestRealtimeRefresh } from '@/lib/realtime/publisher'; -import { - discardExactManagedWorktree, - ExactDiscardUnavailableError, -} from '@/lib/workspace/exact-discard'; -import { probeOwnedSessionProcessQuiescence } from '@/lib/workspace/process-probes'; -import { - withWorkspaceMaterializedMutation, - WorkspaceMutationUnavailableError, -} from '@/lib/workspace/mutation-materialization-guard'; -import { getWorktreeManager } from '@/lib/worktree/launch'; -import { - findWorkspaceMaterializationRetirement, - replayWorkspaceMaterializationRetirement, -} from '@/lib/workspace/workspace-materialization-retirement'; -import { - isMaterializationExecutionRefusal, - materializationAwareExecFile, -} from '@/lib/worktree/materialization-execution'; -import type { MergeResult } from '@/lib/worktree/types'; - -const execFileAsync = materializationAwareExecFile; - -interface MergeBody { - repo: string; - worktreeId: string; - action: 'pr' | 'merge' | 'discard'; - /** Target branch for merge (default: main) */ - targetBranch?: string; - /** PR title override */ - prTitle?: string; - /** PR body override */ - prBody?: string; -} - -export interface WorktreeMergeRouteDependencies { - afterWorkspaceMaterializationProof?: (action: MergeBody['action']) => Promise | void; - beforeWorkspaceCleanup?: (action: 'pr' | 'merge') => Promise | void; - afterWorkspaceCleanup?: (action: MergeBody['action']) => Promise | void; - discardExact?: typeof discardExactManagedWorktree; - createPR?: typeof createPR; - mergeToTarget?: typeof mergeToTarget; -} - -export async function handlePost( - req: NextRequest, - dependencies: WorktreeMergeRouteDependencies, -) { - const principal = resolveRequestPrincipal(req); - if (principal === 'worker') { - return NextResponse.json({ error: 'Worktree publication is operator-controlled.' }, { status: 403 }); - } - if (principal !== 'device') { - const denied = requirePanelAuth(req); - if (denied) return denied; - } - - let body: MergeBody; - try { - body = (await req.json()) as MergeBody; - } catch { - return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 }); - } - - if (!body.repo || !body.worktreeId || !body.action) { - return NextResponse.json( - { error: 'repo, worktreeId, and action are required' }, - { status: 400 }, - ); - } - if (body.action !== 'pr' && body.action !== 'merge' && body.action !== 'discard') { - return NextResponse.json({ error: 'Unknown action' }, { status: 400 }); - } - - const mgr = getWorktreeManager(body.repo); - try { - const registeredRepo = await findRepoByLocalPath(body.repo); - if (registeredRepo) { - const pending = findWorkspaceMaterializationRetirement( - registeredRepo.id, - body.worktreeId, - body.action, - ); - if (pending) { - const cleaned = await mgr.cleanup(body.worktreeId, { - force: true, - deleteBranch: body.action !== 'pr', - overrideLiveGuard: true, - workspaceRetirementAction: body.action, - }); - if (!cleaned) { - return NextResponse.json({ - action: body.action, - ok: false, - note: 'Terminal workspace cleanup is still pending exact retirement.', - } satisfies MergeResult, { status: 409 }); - } - await replayWorkspaceMaterializationRetirement( - registeredRepo.id, body.worktreeId, body.action, - ); - return NextResponse.json({ - action: body.action, - ok: true, - note: `${body.action} already completed; terminal workspace retirement was replayed.`, - } satisfies MergeResult); - } - } - } catch (error) { - return NextResponse.json({ - action: body.action, - ok: false, - note: error instanceof Error ? error.message : 'Terminal workspace truth could not be verified.', - } satisfies MergeResult, { status: 409 }); - } - - const worktree = await mgr.get(body.worktreeId); - - if (!worktree) { - return NextResponse.json({ error: 'Worktree not found' }, { status: 404 }); - } - - const repoPath = path.resolve(body.repo); - const worktreePath = path.resolve(worktree.path); - const lanes = listLanes().filter((lane) => ( - Boolean(lane.packetId?.trim()) - && path.resolve(lane.repoPath) === repoPath - && lane.worktreePath !== null - && path.resolve(lane.worktreePath) === worktreePath - && lane.branch === worktree.branch - )); - if (lanes.length !== 1) { - return NextResponse.json({ - action: body.action, - ok: false, - note: lanes.length === 0 - ? 'Worktree publication refused because its exact packet lane is unavailable.' - : 'Worktree publication refused because its packet lane ownership is ambiguous.', - } satisfies MergeResult, { status: 409 }); - } - const lane = lanes[0]!; - if (body.action === 'merge') { - const note = await prFirstMergeRefusal(lane); - if (note) return NextResponse.json({ action: 'merge', ok: false, reason: 'pr_only', note }, { status: 409 }); - } - - try { - const result = await withWorkspaceMaterializedMutation(lane, async (): Promise => { - await dependencies.afterWorkspaceMaterializationProof?.(body.action); - switch (body.action) { - case 'pr': { - const prResult = await (dependencies.createPR ?? createPR)(worktree.path, worktree.branch, worktree.dirtyFiles, { - repoPath, - title: body.prTitle, - body: body.prBody, - targetBranch: body.targetBranch ?? 'main', - agentType: worktree.agentType, - createdAt: worktree.createdAt, - lfsBase: readLaneCreationBaseCommit(lane.id), - }); - // Cleanup worktree but keep branch (PR needs it) - if (prResult.ok) { - await dependencies.beforeWorkspaceCleanup?.('pr'); - const cleaned = await mgr.cleanup(body.worktreeId, { - force: true, - deleteBranch: false, - workspaceRetirementAction: 'pr', - }); - if (!cleaned) { - return { - action: 'pr', - ok: false, - note: `${prResult.note} Local workspace cleanup remains pending and can be retried safely.`, - }; - } - await dependencies.afterWorkspaceCleanup?.('pr'); - } - return prResult; - } - - case 'merge': { - const mergeResult = await (dependencies.mergeToTarget ?? mergeToTarget)(body.repo, worktree.path, worktree.branch, body.targetBranch ?? 'main', { - importBranchFromWorkspace: worktree.isolationKind === 'apfs-cow-clone', - lfsBase: readLaneCreationBaseCommit(lane.id), - }); - if (mergeResult.ok) { - await dependencies.beforeWorkspaceCleanup?.('merge'); - const cleaned = await mgr.cleanup(body.worktreeId, { - force: true, - deleteBranch: true, - workspaceRetirementAction: 'merge', - }); - if (cleaned) await dependencies.afterWorkspaceCleanup?.('merge'); - // #538 — Post-merge decomposition pipeline. Never blocks the response - // and never rolls back the merge on failure. - try { - const { enqueueDecompositionsAfterMerge } = await import('@/lib/dispatch/decomposition-pipeline'); - const runtime = worktree.agentType === 'claude-code' ? 'claude-code' : 'codex'; - await enqueueDecompositionsAfterMerge({ - repoPath: body.repo, - runtime, - }); - } catch (decompositionError) { - console.warn( - `[worktrees/merge] Decomposition scan failed for ${body.repo}: ${decompositionError instanceof Error ? decompositionError.message : String(decompositionError)}`, - ); - } - if (!cleaned) { - return { - action: 'merge', - ok: false, - note: `${mergeResult.note} Local workspace cleanup remains pending and can be retried safely.`, - }; - } - } - return mergeResult; - } - - case 'discard': - await (dependencies.discardExact ?? discardExactManagedWorktree)({ - lane, - worktreeId: body.worktreeId, - isolationKind: worktree.isolationKind ?? 'git-worktree', - processProbe: probeOwnedSessionProcessQuiescence, - }); - await dependencies.afterWorkspaceCleanup?.('discard'); - return { action: 'discard', ok: true, note: `Discarded worktree ${body.worktreeId}` }; - - default: - return { action: body.action, ok: false, note: 'Unknown action' }; - } - }); - - if (result.ok) { - void requestRealtimeRefresh({ - targets: ['global', 'mobileInbox'], - fresh: true, - reason: `worktree.${body.action}`, - }); - } - - return NextResponse.json(result); - } catch (err) { - if (err instanceof ExactDiscardUnavailableError) { - return NextResponse.json({ - action: body.action, - ok: false, - note: err.message, - } satisfies MergeResult, { status: 409 }); - } - if (isMaterializationExecutionRefusal(err)) { - return NextResponse.json({ - action: body.action, - ok: false, - note: 'Managed workspace ownership changed before the requested action; no mutation ran.', - } satisfies MergeResult, { status: 409 }); - } - if (err instanceof WorkspaceMutationUnavailableError) { - return NextResponse.json({ - action: body.action, - ok: false, - note: err.message, - } satisfies MergeResult, { status: 409 }); - } - return NextResponse.json( - { error: err instanceof Error ? err.message : 'Unknown error' }, - { status: 500 }, - ); - } -} - -export function createWorktreeMergePostForTesting(dependencies: WorktreeMergeRouteDependencies) { - return (req: NextRequest) => handlePost(req, dependencies); -} - -async function commitWorkspaceChanges( - action: 'pr' | 'merge', - worktreePath: string, - repoPath: string, - branch: string, - message: string, -): Promise { - const status = async () => (await laneGit(worktreePath, repoPath, - ['status', '--porcelain=v1', '--untracked-files=all'], { timeout: 5_000 })).stdout.trim(); - try { - const dirty = await status(); - await assertLaneHeadOnBranch(worktreePath, repoPath, branch); - if (!dirty) return null; - await commitDirtyWorktree(worktreePath, repoPath, branch, message); - if (await status()) { - return { - action, - ok: false, - note: `Workspace commit failed before ${action} publication; the workspace remained dirty and was preserved.`, - }; - } - return null; - } catch (error) { - const ownershipChanged = isMaterializationExecutionRefusal(error); - return { - action, - ok: false, - note: ownershipChanged - ? `Managed workspace ownership changed before ${action} publication; no publish command ran.` - : `Workspace commit failed before ${action} publication; the workspace was preserved: ${error instanceof Error ? error.message : String(error)}`, - }; - } -} - -// ── PR Creation ── - -async function createPR( - worktreePath: string, - branch: string, - dirtyFiles: string[], - opts: { repoPath: string; title?: string; body?: string; targetBranch: string; agentType: string; createdAt?: number; lfsBase?: string | null }, -): Promise { - const commitFailure = await commitWorkspaceChanges( - 'pr', - worktreePath, - opts.repoPath, - branch, - `chore: worktree changes from ${opts.agentType}`, - ); - if (commitFailure) return commitFailure; - - // Push branch - try { - await pushLfsObjects((args, options) => laneGit(worktreePath, opts.repoPath, args, options), 'origin', branch, opts.lfsBase ?? null); - await laneGit(worktreePath, opts.repoPath, ['push', '-u', 'origin', branch], { timeout: 30_000 }); - } catch (err) { - return { - action: 'pr', - ok: false, - note: `Failed to push branch: ${err instanceof Error ? err.message : String(err)}`, - }; - } - - // Get diffstat for PR body - let diffstat = ''; - try { - const { stdout: statOut } = await execFileAsync('git', [ - 'diff', '--shortstat', `${opts.targetBranch}...HEAD`, - ], { windowsHide: true, cwd: worktreePath, timeout: 5000 }); - diffstat = statOut.trim(); - } catch { /* non-critical */ } - - // Get duration estimate - const durationMin = opts.createdAt - ? Math.round((Date.now() - opts.createdAt) / 60_000) - : undefined; - - // Create PR via gh CLI - const taskName = branch.split('/').pop() ?? branch; - const title = opts.title ?? `${opts.agentType}: ${taskName}`; - const fileList = dirtyFiles.map((f) => `- \`${f}\``).join('\n'); - const prBody = opts.body ?? [ - `## Changes`, - `**Agent:** ${opts.agentType}${durationMin ? ` · **Duration:** ${durationMin} min` : ''}`, - `**Branch:** \`${branch}\`${diffstat ? ` · ${diffstat}` : ''}`, - ``, - `### Files Modified (${dirtyFiles.length})`, - fileList, - ``, - `---`, - `*Created by o8 WorktreeManager*`, - ].join('\n'); - - try { - const { stdout } = await execFileAsync('gh', [ - 'pr', 'create', - '--title', title, - '--body', prBody, - '--base', opts.targetBranch, - '--head', branch, - ], { windowsHide: true, cwd: worktreePath, timeout: 30_000 }); - - const prUrl = stdout.trim(); - return { - action: 'pr', - ok: true, - note: `PR created: ${prUrl}`, - prUrl, - }; - } catch (err) { - return { - action: 'pr', - ok: false, - note: `Failed to create PR: ${err instanceof Error ? err.message : String(err)}`, - }; - } -} - -// ── Direct Merge ── - -async function mergeToTarget( - repoRoot: string, - worktreePath: string, - branch: string, - targetBranch: string, - opts?: { importBranchFromWorkspace?: boolean; lfsBase?: string | null }, -): Promise { - const commitFailure = await commitWorkspaceChanges( - 'merge', - worktreePath, - repoRoot, - branch, - 'chore: worktree changes', - ); - if (commitFailure) return commitFailure; - - if (opts?.importBranchFromWorkspace) { - try { - await execFileAsync('git', [...NO_REPOSITORY_HOOKS, 'fetch', worktreePath, `${branch}:refs/heads/${branch}`], { - windowsHide: true, - cwd: repoRoot, - timeout: 30_000, - }); - } catch (err) { - return { - action: 'merge', - ok: false, - note: `Failed to import workspace branch before merge: ${err instanceof Error ? err.message : String(err)}`, - }; - } - } - - // Safety: refuse to merge if repo root has uncommitted changes - try { - const { stdout: dirtyCheck } = await execFileAsync('git', ['status', '--porcelain'], { - windowsHide: true, - cwd: repoRoot, - timeout: 5000, - }); - if (dirtyCheck.trim().length > 0) { - return { - action: 'merge', - ok: false, - note: 'Repo root has uncommitted changes. Commit or stash first, or use "Create PR" instead.', - }; - } - } catch { - // If we can't check, refuse - return { - action: 'merge', - ok: false, - note: 'Could not verify repo root is clean. Use "Create PR" instead.', - }; - } - - // Check for conflicts before merging using merge-tree (no working tree mutation) - try { - const { stdout: mergeCheck } = await execFileAsync('git', [ - 'merge-tree', '--write-tree', targetBranch, branch, - ], { windowsHide: true, cwd: repoRoot, timeout: 10_000 }); - - if (mergeCheck.includes('CONFLICT')) { - return { - action: 'merge', - ok: false, - note: 'Merge conflicts detected. Use "Create PR" instead for manual resolution.', - }; - } - } catch { - // merge-tree may not be available; fall through to try merge - } - - // Save current branch to restore after merge - let originalBranch: string | null = null; - try { - const { stdout } = await execFileAsync('git', ['branch', '--show-current'], { - windowsHide: true, - cwd: repoRoot, - timeout: 5000, - }); - originalBranch = stdout.trim() || null; - } catch { /* best effort */ } - - // Perform the merge - try { - await execFileAsync('git', [...NO_REPOSITORY_HOOKS, 'checkout', targetBranch], { - windowsHide: true, - cwd: repoRoot, - timeout: 10_000, - }); - - await execFileAsync('git', [...NO_REPOSITORY_HOOKS, 'merge', '--no-ff', branch, '-m', `Merge worktree: ${branch}`], { - windowsHide: true, - cwd: repoRoot, - timeout: 15_000, - }); - - // #534 — push the merge to origin. Failure here must NOT revert the merge: - // the base branch already has the commit locally. - let pushedToOrigin = false; - let pushError: string | undefined; - try { - await pushLfsObjects((args, options) => execFileAsync('git', [...NO_REPOSITORY_HOOKS, ...args], { - windowsHide: true, - cwd: repoRoot, - ...options, - }), 'origin', targetBranch, opts?.lfsBase ?? null); - await execFileAsync('git', [...NO_REPOSITORY_HOOKS, 'push', 'origin', targetBranch], { - windowsHide: true, - cwd: repoRoot, - timeout: 60_000, - }); - pushedToOrigin = true; - } catch (pushErr) { - pushError = pushErr instanceof Error ? pushErr.message : String(pushErr); - console.warn(`[worktrees/merge] Push to origin failed for ${targetBranch} after merging ${branch}: ${pushError}`); - } - - // Restore original branch if it was different from target - if (originalBranch && originalBranch !== targetBranch) { - await execFileAsync('git', [...NO_REPOSITORY_HOOKS, 'checkout', originalBranch], { - windowsHide: true, - cwd: repoRoot, - timeout: 10_000, - }).catch(() => { /* best effort restore */ }); - } - - return { - action: 'merge', - ok: true, - note: pushedToOrigin - ? `Merged ${branch} into ${targetBranch} and pushed to origin.` - : `Merged ${branch} into ${targetBranch} LOCALLY — push to origin failed: ${pushError ?? 'unknown error'}.`, - pushedToOrigin, - pushError, - }; - } catch (err) { - // Abort any partial merge - await execFileAsync('git', [...NO_REPOSITORY_HOOKS, 'merge', '--abort'], { windowsHide: true, cwd: repoRoot, timeout: 5000 }).catch(() => {}); - // Restore original branch - if (originalBranch) { - await execFileAsync('git', [...NO_REPOSITORY_HOOKS, 'checkout', originalBranch], { - windowsHide: true, - cwd: repoRoot, - timeout: 10_000, - }).catch(() => {}); - } - return { - action: 'merge', - ok: false, - note: `Merge failed: ${err instanceof Error ? err.message : String(err)}. Use "Create PR" instead.`, - }; - } -} diff --git a/src/app/api/worktrees/merge/route-real-path.test.ts b/src/app/api/worktrees/merge/route-real-path.test.ts deleted file mode 100644 index 88d8446ac4..0000000000 --- a/src/app/api/worktrees/merge/route-real-path.test.ts +++ /dev/null @@ -1,457 +0,0 @@ -import { createHash } from 'node:crypto'; -import { execFileSync } from 'node:child_process'; -import { - lstatSync, - chmodSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - realpathSync, - renameSync, - writeFileSync, -} from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { pathToFileURL } from 'node:url'; -import { NextRequest } from 'next/server'; -import { afterAll, describe, expect, it } from 'vitest'; - -const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'o8-mobile-publish-real-'))); -const dataDir = path.join(root, 'data'); -const repoPath = path.join(root, 'repo'); -const deviceToken = 'mobile-real-device-token-0123456789abcdef'; -mkdirSync(dataDir); -mkdirSync(repoPath); -writeFileSync(path.join(dataDir, 'ws-token'), 'mobile-real-operator-token-0123456789abcdef\n'); -writeFileSync( - path.join(dataDir, 'mobile-device-tokens'), - `${createHash('sha256').update(deviceToken).digest('hex')}\n`, -); -process.env.O8_DATA_DIR = dataDir; -process.env.CORTEX_IDE_DATA_DIR = dataDir; -process.env.O8_WORKTREE_ROOT = path.join(root, 'worktrees'); -const probes = path.join(root, 'native-cwd-probes'); -mkdirSync(probes, { mode: 0o700 }); -writeFileSync(path.join(process.env.O8_TEST_RUN_DATA_ROOT!, '.o8-test-run-retain.json'), - JSON.stringify({ schema: 'o8/native-publication-fixture-retention/v1', reason: 'Preserve exact publication retirement evidence' }) + '\n', - { mode: 0o600 }); -const previousProbeRoot = process.env.O8_TEST_NATIVE_CWD_PROBE_ROOT; -const previousNodeOptions = process.env.NODE_OPTIONS; -process.env.O8_TEST_NATIVE_CWD_PROBE_ROOT = probes; -const observer = pathToFileURL(path.join(process.cwd(), 'tests/generated-output-native-cwd-observer.mjs')).href; -process.env.NODE_OPTIONS = [process.env.NODE_OPTIONS, `--import=${observer}`].filter(Boolean).join(' '); -await import(/* @vite-ignore */ observer); - -function git(cwd: string, ...args: string[]): string { - return execFileSync('git', args, { cwd, encoding: 'utf8' }).trim(); -} - -git(repoPath, 'init', '-q', '-b', 'main'); -git(repoPath, 'config', 'user.name', 'o8 test'); -git(repoPath, 'config', 'user.email', 'o8-test@example.test'); -writeFileSync(path.join(repoPath, 'tracked.txt'), 'reviewed\n'); -git(repoPath, 'add', 'tracked.txt'); -git(repoPath, 'commit', '-qm', 'reviewed'); - -const { closeDb } = await import('@/lib/db'); -const { createLane, getLane } = await import('@/lib/lane/registry'); -const { addRepo, findRepoByLocalPath, getRepoRegistryPath } = await import('@/lib/repos/registry'); -const { registerOwnedSessionLifecycleHandler } = await import('@/lib/runtimes/shared/owned-session-lifecycle'); -const { resolveWorktreeRootLayout } = await import('@/lib/worktree/root-layout'); -const { withWorktreeMetaTransaction } = await import('@/lib/worktree/metadata-store'); -const { - createWorkspaceSnapshot, - getWorkspaceSnapshot, - transitionWorkspaceSnapshot, -} = await import('@/lib/worktree/snapshot-state'); -const { panelGateMiddleware } = await import('@/middleware'); -const { createWorktreeMergePostForTesting } = await import('./handler'); -const { discardExactManagedWorktree } = await import('@/lib/workspace/exact-discard'); - -const repo = await addRepo(repoPath); -if (getRepoRegistryPath() !== path.join(dataDir, 'repos.json')) { - throw new Error(`Registry path escaped test data dir: ${getRepoRegistryPath()}`); -} -const ownedWorkspaceBindings = new Map(); - -registerOwnedSessionLifecycleHandler({ - runtimeId: 'codex', - surfaceIdPrefix: 'owned:mobile-real-', - commandLabel: 'mobile-publication-test', - resolveRoot: () => root, - sessionState: async () => 'active', - archiveSession: async () => ({ archived: false, note: 'unused' }), - getWorkspaceBinding: async (surfaceId) => { - const binding = ownedWorkspaceBindings.get(surfaceId); - if (!binding) return null; - const retainedRuns = binding.live ? [{ - id: `live-${binding.packetId}`, - outcome: 'running' as const, - pid: process.pid, - commandIdentity: path.basename(process.execPath), - }] : []; - return { - surfaceId, - runtimeId: 'codex', - sessionState: 'active', - binding: { - logicalWorkspaceId: `packet:${binding.packetId}`, - repositoryUuid: repo.id, - packetId: binding.packetId, - cwd: binding.workspacePath, - version: 1, - verifiedAt: '2026-08-15T00:00:00.000Z', - }, - activeRun: null, - retainedRuns, - retainedRunsComplete: true, - retainedRunTotal: retainedRuns.length, - }; - }, - rebindWorkspace: async () => ({ status: 'missing', receipt: null, note: 'unused' }), -}); - -function request(worktreeId: string, action: 'pr' | 'merge' | 'discard'): NextRequest { - // A paired device reaches the loopback server through the relay; #4814 refuses a non-loopback Host. - return new NextRequest('http://127.0.0.1/api/worktrees/merge', { - method: 'POST', - headers: { - authorization: `Bearer ${deviceToken}`, - 'content-type': 'application/json', - 'x-o8-client-addr': '192.0.2.10', - }, - body: JSON.stringify({ repo: repoPath, worktreeId, action }), - }); -} - -async function createOwnedWorkspace(label: string, createSnapshot = true) { - const packetId = `mobile-real-${label}`; - const worktreeId = `packet-${packetId}`; - const workspacePath = path.join(resolveWorktreeRootLayout(repoPath).primaryBase, worktreeId); - mkdirSync(path.dirname(workspacePath), { recursive: true }); - git(root, 'clone', '-q', '--local', repoPath, workspacePath); - const lane = createLane({ - repoPath, - worktreePath: workspacePath, - branch: 'main', - baseBranch: 'main', - runtime: 'codex', - packetId, - sessionKey: `owned:${packetId}`, - ownership: 'managed', - }); - ownedWorkspaceBindings.set(lane.sessionKey!, { packetId, workspacePath, live: false }); - const head = git(workspacePath, 'rev-parse', 'HEAD'); - const recoveryRef = `refs/o8/recovery/${packetId}`; - // A previously restored snapshot must have its actual preserved commit, - // not only a declared recovery-ref name in the snapshot row. - if (createSnapshot) git(repoPath, 'update-ref', recoveryRef, head); - let snapshot = createSnapshot ? createWorkspaceSnapshot({ - repositoryUuid: repo.id, - packetId, - laneId: lane.id, - originalPath: workspacePath, - branch: 'main', - baseCommit: head, - headCommit: head, - treeSha: git(workspacePath, 'rev-parse', 'HEAD^{tree}'), - recoveryRef, - diffFingerprint: `${packetId}-diff`, - sessionIdentities: [{ kind: 'owned-session', identity: lane.sessionKey! }], - creationId: `${packetId}-created`, - }).record : null; - if (snapshot) { - for (const [index, state] of [ - 'parkable', 'hibernating', 'parked', 'restoring', 'materialized', - ].entries() as ArrayIterator<[number, typeof snapshot.state]>) { - const result = transitionWorkspaceSnapshot({ - repositoryUuid: repo.id, - packetId, - transitionId: `${packetId}-prior-restore-${index}`, - expectedState: snapshot.state, - expectedVersion: snapshot.version, - expectedGeneration: snapshot.snapshotGeneration, - toState: state, - }); - if (result.status !== 'applied') throw new Error('prior parked restore cycle failed'); - snapshot = result.record; - } - } - const identity = lstatSync(workspacePath); - const parentIdentity = lstatSync(path.dirname(workspacePath)); - await withWorktreeMetaTransaction(repoPath, (transaction) => transaction.save(worktreeId, { - id: worktreeId, - agentType: 'codex', - sessionKey: lane.sessionKey!, - baseBranch: 'main', - createdAt: Date.now(), - claudeManaged: false, - taskName: worktreeId, - branchName: 'main', - status: 'ready', - isolationKind: 'apfs-cow-clone', - materializationIdentity: { - device: identity.dev, - inode: identity.ino, - canonicalPath: realpathSync(workspacePath), - }, - materializationParentIdentity: { - device: parentIdentity.dev, - inode: parentIdentity.ino, - canonicalPath: realpathSync(path.dirname(workspacePath)), - }, - })); - return { packetId, worktreeId, workspacePath }; -} - -afterAll(() => { - closeDb(); - if (previousProbeRoot === undefined) delete process.env.O8_TEST_NATIVE_CWD_PROBE_ROOT; - else process.env.O8_TEST_NATIVE_CWD_PROBE_ROOT = previousProbeRoot; - if (previousNodeOptions === undefined) delete process.env.NODE_OPTIONS; - else process.env.NODE_OPTIONS = previousNodeOptions; - console.error(`[publication-fixture] retained native evidence at ${root}`); -}); - -describe('paired-device publication uses the captured managed workspace', () => { - it.each(['pr', 'merge', 'discard'] as const)( - 'refuses %s when the same path is replaced after durable ownership proof', - async (action) => { - const fixture = await createOwnedWorkspace(action, false); - const retained = path.join(root, `${action}-retained-owner`); - const occupantBytes = `unrelated ${action} occupant\n`; - const repoHead = git(repoPath, 'rev-parse', 'HEAD'); - expect(await findRepoByLocalPath(repoPath)).toMatchObject({ id: repo.id, localPath: repoPath }); - expect(panelGateMiddleware(request(fixture.worktreeId, action)).headers.get('x-middleware-next')).toBe('1'); - - const response = await createWorktreeMergePostForTesting({ - afterWorkspaceMaterializationProof: () => { - renameSync(fixture.workspacePath, retained); - git(root, 'clone', '-q', '--local', repoPath, fixture.workspacePath); - writeFileSync(path.join(fixture.workspacePath, 'tracked.txt'), occupantBytes); - }, - })(request(fixture.worktreeId, action)); - const body = await response.json() as { ok: boolean; note: string }; - - expect(response.status, body.note).toBe(action === 'discard' ? 409 : 200); - expect(body.ok).toBe(false); - expect(body.note).toContain('Managed workspace ownership changed'); - expect(readFileSync(path.join(fixture.workspacePath, 'tracked.txt'), 'utf8')).toBe(occupantBytes); - expect(readFileSync(path.join(retained, 'tracked.txt'), 'utf8')).toBe('reviewed\n'); - expect(git(repoPath, 'rev-parse', 'HEAD')).toBe(repoHead); - expect(git(repoPath, 'status', '--porcelain')).toBe(''); - }, - 60_000, - ); - - it.each(['pr', 'merge'] as const)( - 'preserves dirty bytes and refuses %s when the workspace commit fails, running no workspace hook', - async (action) => { - const fixture = await createOwnedWorkspace(`commit-${action}`); - const dirtyBytes = `dirty ${action} bytes\n`; - writeFileSync(path.join(fixture.workspacePath, 'dirty.txt'), dirtyBytes); - const hookRan = path.join(root, `${action}-hook-ran`); - const hookPath = path.join(fixture.workspacePath, '.git', 'hooks', 'pre-commit'); - writeFileSync(hookPath, `#!/bin/sh\ntouch ${JSON.stringify(hookRan)}\nexit 9\n`); - chmodSync(hookPath, 0o755); - // A held lock on the branch makes the commit itself fail. - writeFileSync(path.join(fixture.workspacePath, '.git', 'refs', 'heads', 'main.lock'), ''); - const repoHead = git(repoPath, 'rev-parse', 'HEAD'); - - const response = await createWorktreeMergePostForTesting({})( - request(fixture.worktreeId, action), - ); - const body = await response.json() as { ok: boolean; note: string }; - - expect(response.status).toBe(200); - expect(body).toMatchObject({ ok: false }); - expect(body.note).toContain('Workspace commit failed'); - expect(readFileSync(path.join(fixture.workspacePath, 'dirty.txt'), 'utf8')).toBe(dirtyBytes); - expect(git(fixture.workspacePath, 'status', '--porcelain')).toContain('dirty.txt'); - expect(git(repoPath, 'rev-parse', 'HEAD')).toBe(repoHead); - expect(existsSync(fixture.workspacePath)).toBe(true); - expect(existsSync(hookRan)).toBe(false); - }, - 30_000, - ); - - it.each(['pr', 'merge'] as const)( - 'refuses %s without committing when the workspace is on another branch', - async (action) => { - const fixture = await createOwnedWorkspace(`switched-${action}`); - git(fixture.workspacePath, 'checkout', '-q', '-b', 'other'); - const otherHead = git(fixture.workspacePath, 'rev-parse', 'other'); - const dirtyBytes = `dirty ${action} bytes\n`; - writeFileSync(path.join(fixture.workspacePath, 'dirty.txt'), dirtyBytes); - const repoHead = git(repoPath, 'rev-parse', 'HEAD'); - - const response = await createWorktreeMergePostForTesting({})( - request(fixture.worktreeId, action), - ); - const body = await response.json() as { ok: boolean; note: string }; - - expect(body).toMatchObject({ ok: false }); - expect(body.note).toContain('Workspace commit failed'); - expect(git(fixture.workspacePath, 'rev-parse', 'other')).toBe(otherHead); - expect(readFileSync(path.join(fixture.workspacePath, 'dirty.txt'), 'utf8')).toBe(dirtyBytes); - expect(git(repoPath, 'rev-parse', 'HEAD')).toBe(repoHead); - }, - 30_000, - ); - - it('refuses live-worker discard before reset or clean changes a byte', async () => { - const fixture = await createOwnedWorkspace('live-discard'); - const trackedBytes = 'live worker tracked bytes\n'; - const untrackedPath = path.join(fixture.workspacePath, 'live-untracked.txt'); - writeFileSync(path.join(fixture.workspacePath, 'tracked.txt'), trackedBytes); - writeFileSync(untrackedPath, 'live worker untracked bytes\n'); - ownedWorkspaceBindings.get(`owned:${fixture.packetId}`)!.live = true; - - const response = await createWorktreeMergePostForTesting({})( - request(fixture.worktreeId, 'discard'), - ); - const body = await response.json() as { ok: boolean; note: string }; - - expect(response.status).toBe(409); - expect(body).toMatchObject({ ok: false }); - expect(body.note).toContain('process truth is live'); - expect(readFileSync(path.join(fixture.workspacePath, 'tracked.txt'), 'utf8')).toBe(trackedBytes); - expect(readFileSync(untrackedPath, 'utf8')).toBe('live worker untracked bytes\n'); - expect(getWorkspaceSnapshot(repo.id, fixture.packetId)).toMatchObject({ state: 'materialized' }); - }, 30_000); - - it.each(['pr', 'merge'] as const)( - 'reports successful %s publication with exact local cleanup still pending', - async (action) => { - const fixture = await createOwnedWorkspace(`cleanup-pending-${action}`); - const retained = path.join(root, `cleanup-pending-${action}-retained-owner`); - const occupantBytes = `cleanup-pending ${action} occupant\n`; - const response = await createWorktreeMergePostForTesting({ - createPR: async () => ({ action: 'pr' as const, ok: true, note: 'PR created' }), - mergeToTarget: async () => ({ action: 'merge' as const, ok: true, note: 'Merged' }), - beforeWorkspaceCleanup: () => { - renameSync(fixture.workspacePath, retained); - git(root, 'clone', '-q', '--local', repoPath, fixture.workspacePath); - writeFileSync(path.join(fixture.workspacePath, 'tracked.txt'), occupantBytes); - }, - })(request(fixture.worktreeId, action)); - const body = await response.json() as { ok: boolean; note?: string; error?: string }; - - expect(response.status, body.note ?? body.error).toBe(200); - expect(body.ok).toBe(false); - expect(body.note).toContain('cleanup remains pending'); - expect(readFileSync(path.join(fixture.workspacePath, 'tracked.txt'), 'utf8')).toBe(occupantBytes); - expect(readFileSync(path.join(retained, 'tracked.txt'), 'utf8')).toBe('reviewed\n'); - expect(getWorkspaceSnapshot(repo.id, fixture.packetId)).toMatchObject({ state: 'materialized' }); - }, - 60_000, - ); - - it.each(['pr', 'merge', 'discard'] as const)( - 'durably retires a previously restored workspace after successful %s', - async (action) => { - const fixture = await createOwnedWorkspace(`terminal-${action}`); - const dependencies = { - createPR: async () => ({ action: 'pr' as const, ok: true, note: 'PR created' }), - mergeToTarget: async () => ({ action: 'merge' as const, ok: true, note: 'Merged' }), - }; - - const response = await createWorktreeMergePostForTesting(dependencies)( - request(fixture.worktreeId, action), - ); - const body = await response.json() as { ok: boolean; note?: string; error?: string }; - - expect(response.status, body.note ?? body.error).toBe(200); - expect(body.ok, body.note ?? body.error).toBe(true); - expect(existsSync(fixture.workspacePath)).toBe(false); - expect(getWorkspaceSnapshot(repo.id, fixture.packetId)).toMatchObject({ state: 'retired' }); - expect(getLane( - getWorkspaceSnapshot(repo.id, fixture.packetId)!.laneId!, - )).toMatchObject({ status: 'archived', worktreePath: null }); - }, - // Exact native retirement repeats process, preservation and parent probes. - 120_000, - ); - - it('replays exact terminal truth after cleanup completed before the response', async () => { - const fixture = await createOwnedWorkspace('crash-after-pr-cleanup'); - const dependencies = { - createPR: async () => ({ action: 'pr' as const, ok: true, note: 'PR created' }), - afterWorkspaceCleanup: async () => { - throw new Error('simulated response crash'); - }, - }; - const first = await createWorktreeMergePostForTesting(dependencies)( - request(fixture.worktreeId, 'pr'), - ); - expect(first.status).toBe(500); - expect(existsSync(fixture.workspacePath)).toBe(false); - expect(getWorkspaceSnapshot(repo.id, fixture.packetId)).toMatchObject({ state: 'retired' }); - - const replay = await createWorktreeMergePostForTesting({})( - request(fixture.worktreeId, 'pr'), - ); - expect(replay.status).toBe(200); - expect(await replay.json()).toMatchObject({ action: 'pr', ok: true }); - }, 120_000); - - it('rolls a pre-removal discard failure back to materialized and allows an exact retry', async () => { - const fixture = await createOwnedWorkspace('discard-reset-failure'); - let processChecks = 0; - const refused = await createWorktreeMergePostForTesting({ - discardExact: input => discardExactManagedWorktree({ - ...input, - processProbe: async (...args) => { - const receipt = await input.processProbe(...args); - // Interrupt after the actual native check, before the source rename. - if (++processChecks === 2) throw new Error('fixture pre-removal interruption'); - return receipt; - }, - }), - })( - request(fixture.worktreeId, 'discard'), - ); - expect(refused.status).toBe(500); - expect(getWorkspaceSnapshot(repo.id, fixture.packetId)).toMatchObject({ state: 'materialized' }); - expect(existsSync(fixture.workspacePath)).toBe(true); - - const retry = await createWorktreeMergePostForTesting({})( - request(fixture.worktreeId, 'discard'), - ); - const body = await retry.json() as { ok: boolean; note?: string; error?: string }; - expect(retry.status, body.note ?? body.error).toBe(200); - expect(body.ok, body.note ?? body.error).toBe(true); - expect(getWorkspaceSnapshot(repo.id, fixture.packetId)).toMatchObject({ state: 'retired' }); - expect(existsSync(fixture.workspacePath)).toBe(false); - }, 120_000); - - it('imports a never-parked copy-on-write head into the canonical recovery ref before retirement', async () => { - const fixture = await createOwnedWorkspace('apfs-terminal-bootstrap', false); - git(fixture.workspacePath, 'config', 'user.name', 'o8 test'); - git(fixture.workspacePath, 'config', 'user.email', 'o8-test@example.test'); - writeFileSync(path.join(fixture.workspacePath, 'clone-only.txt'), 'clone-only reviewed bytes\n'); - git(fixture.workspacePath, 'add', 'clone-only.txt'); - git(fixture.workspacePath, 'commit', '-qm', 'clone-only reviewed head'); - const reviewedHead = git(fixture.workspacePath, 'rev-parse', 'HEAD'); - expect(() => git(repoPath, 'cat-file', '-e', `${reviewedHead}^{commit}`)).toThrow(); - - const response = await createWorktreeMergePostForTesting({})( - request(fixture.worktreeId, 'discard'), - ); - const body = await response.json() as { ok: boolean; note?: string; error?: string }; - expect(response.status, body.note ?? body.error).toBe(200); - expect(body.ok, body.note ?? body.error).toBe(true); - expect(existsSync(fixture.workspacePath)).toBe(false); - - closeDb(); - const snapshot = getWorkspaceSnapshot(repo.id, fixture.packetId); - expect(snapshot).toMatchObject({ state: 'retired', headCommit: reviewedHead }); - expect(git(repoPath, 'rev-parse', `${snapshot!.recoveryRef}^{commit}`)).toBe(reviewedHead); - expect(git(repoPath, 'rev-parse', `${reviewedHead}^{tree}`)).toBe(snapshot!.treeSha); - }, 60_000); -}); diff --git a/src/app/api/worktrees/merge/route.test.ts b/src/app/api/worktrees/merge/route.test.ts deleted file mode 100644 index f1eeb9cd74..0000000000 --- a/src/app/api/worktrees/merge/route.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { createHash } from 'node:crypto'; -import { mkdtempSync, writeFileSync } from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { NextRequest } from 'next/server'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -import type { Lane } from '@/lib/lane/types'; -import type { WorkspaceSnapshotRecord } from '@/lib/worktree/snapshot-state-types'; - -const h = vi.hoisted(() => ({ - cleanup: vi.fn(), - findRepoByLocalPath: vi.fn(), - getWorktree: vi.fn(), - identity: { device: 1, inode: 2, canonicalPath: '/tmp/o8-mobile-route-worktree' }, - lanes: [] as Lane[], - snapshots: [] as WorkspaceSnapshotRecord[], -})); - -vi.mock('@/lib/lane/registry', () => ({ - findLatestLaneByPacket: (packetId: string) => h.lanes.find((lane) => lane.packetId === packetId), - listLanes: () => h.lanes, -})); -vi.mock('@/lib/repos/registry', () => ({ - findRepoByLocalPath: h.findRepoByLocalPath, - listRepos: () => [], -})); -vi.mock('@/lib/worktree/snapshot-state', () => ({ - listWorkspaceSnapshotsByPacketId: () => h.snapshots, - listWorkspaceSnapshotsByRepositoryUuid: (repositoryUuid: string) => ( - h.snapshots.filter((snapshot) => snapshot.repositoryUuid === repositoryUuid) - ), -})); -vi.mock('@/lib/worktree/launch', () => ({ - getWorktreeManager: () => ({ get: h.getWorktree, cleanup: h.cleanup }), -})); -vi.mock('@/lib/workspace/managed-materialization-identity', () => ({ - assertManagedWorkspaceMaterialization: vi.fn(async () => h.identity), -})); -vi.mock('@/lib/realtime/publisher', () => ({ requestRealtimeRefresh: vi.fn() })); - -const dataDir = mkdtempSync(path.join(os.tmpdir(), 'o8-mobile-worktree-route-')); -const deviceToken = 'route-device-token-0123456789abcdef'; -writeFileSync(path.join(dataDir, 'ws-token'), 'route-operator-token-0123456789abcdef\n'); -writeFileSync( - path.join(dataDir, 'mobile-device-tokens'), - `${createHash('sha256').update(deviceToken).digest('hex')}\n`, -); -process.env.O8_DATA_DIR = dataDir; -process.env.CORTEX_IDE_DATA_DIR = dataDir; - -const { panelGateMiddleware } = await import('@/middleware'); -const { withPacketLifecycleMutationLock } = await import('@/lib/orchestrator/lifecycle-mutation-lock'); -const { createWorktreeMergePostForTesting } = await import('./handler'); -const post = createWorktreeMergePostForTesting({ - discardExact: async () => { await h.cleanup(); }, -}); - -const packetId = 'packet-mobile-route'; -const repoPath = '/tmp/o8-mobile-route-repo'; -const workspacePath = '/tmp/o8-mobile-route-worktree'; - -function lane(): Lane { - return { - id: 'lane-mobile-route', - projectId: null, - label: 'Mobile route lane', - repoPath, - worktreePath: workspacePath, - branch: 'inline/mobile-route', - baseBranch: 'main', - runtime: 'codex', - sessionKey: 'owned:mobile-route', - packetId, - prNumber: null, - status: 'reviewing', - outcome: null, - outcomeNote: null, - ownership: 'managed', - writerToken: null, - lastHeartbeatAt: null, - createdAt: new Date(0).toISOString(), - updatedAt: new Date(0).toISOString(), - lastEventAt: null, - lastEventLabel: null, - }; -} - -function snapshot(state: WorkspaceSnapshotRecord['state']): WorkspaceSnapshotRecord { - return { - repositoryUuid: 'repo-mobile-route', - packetId, - missionId: 'mission-mobile-route', - laneId: 'lane-mobile-route', - originalPath: workspacePath, - branch: 'inline/mobile-route', - baseCommit: 'a'.repeat(40), - headCommit: 'b'.repeat(40), - treeSha: 'c'.repeat(40), - recoveryRef: 'refs/o8/recovery/mobile-route', - diffFingerprint: 'mobile-route-diff', - dependencyRecipeKey: null, - sessionIdentities: [], - reservation: null, - snapshotFingerprint: 'mobile-route-snapshot', - snapshotGeneration: 1, - state, - version: 1, - lastTransitionId: 'transition-mobile-route', - transitionStartedAt: 1, - stateEnteredAt: 1, - lastError: null, - lastErrorAt: null, - createdAt: 1, - updatedAt: 1, - }; -} - -function request(action: 'pr' | 'merge' | 'discard'): NextRequest { - return new NextRequest('http://o8.remote/api/worktrees/merge', { - method: 'POST', - headers: { - authorization: `Bearer ${deviceToken}`, - 'content-type': 'application/json', - 'x-o8-client-addr': '192.0.2.10', - }, - body: JSON.stringify({ repo: repoPath, worktreeId: 'packet-mobile-route', action }), - }); -} - -async function deferred() { - let resolve!: (value: T | PromiseLike) => void; - const promise = new Promise((settle) => { resolve = settle; }); - return { promise, resolve }; -} - -describe('mobile worktree publication route', () => { - beforeEach(() => { - h.cleanup.mockReset().mockResolvedValue(undefined); - h.findRepoByLocalPath.mockReset().mockResolvedValue({ - id: 'repo-mobile-route', - localPath: repoPath, - }); - h.getWorktree.mockReset().mockResolvedValue({ - id: 'packet-mobile-route', - path: workspacePath, - branch: 'inline/mobile-route', - baseBranch: 'main', - agentType: 'codex', - status: 'ready', - createdAt: 1, - lastActivityAt: 1, - dirtyFiles: ['tracked.ts'], - claudeManaged: false, - isolationKind: 'git-worktree', - }); - h.lanes = [lane()]; - h.snapshots = [snapshot('materialized')]; - }); - - it('accepts the paired-device principal through middleware and the real handler', async () => { - expect(panelGateMiddleware(request('discard')).headers.get('x-middleware-next')).toBe('1'); - - const response = await post(request('discard')); - - expect(response.status, JSON.stringify(await response.clone().json())).toBe(200); - expect(h.cleanup).toHaveBeenCalledOnce(); - }); - - it.each(['pr', 'merge', 'discard'] as const)( - 'refuses parked %s before any Git, network, or cleanup mutation', - async (action) => { - h.snapshots = [snapshot('parked')]; - - const response = await post(request(action)); - - expect(response.status).toBe(409); - expect(h.cleanup).not.toHaveBeenCalled(); - }, - ); - - it('holds the packet lifecycle lock through cleanup so parking observes the publication first', async () => { - const cleanupStarted = await deferred(); - const releaseCleanup = await deferred(); - h.cleanup.mockImplementationOnce(async () => { - cleanupStarted.resolve(); - await releaseCleanup.promise; - }); - - const publication = post(request('discard')); - await cleanupStarted.promise; - const lifecycle = withPacketLifecycleMutationLock(packetId, async ({ contended }) => contended); - releaseCleanup.resolve(); - - expect((await publication).status).toBe(200); - expect(await lifecycle).toBe(true); - }); - - it('refuses publication when a lifecycle transition wins the lock first', async () => { - const lifecycleStarted = await deferred(); - const releaseLifecycle = await deferred(); - const lifecycle = withPacketLifecycleMutationLock(packetId, async () => { - h.snapshots = [snapshot('parked')]; - lifecycleStarted.resolve(); - await releaseLifecycle.promise; - }); - await lifecycleStarted.promise; - - const publication = post(request('discard')); - releaseLifecycle.resolve(); - await lifecycle; - - expect((await publication).status).toBe(409); - expect(h.cleanup).not.toHaveBeenCalled(); - }); -}); diff --git a/src/app/api/worktrees/merge/route.ts b/src/app/api/worktrees/merge/route.ts deleted file mode 100644 index c63f3aacfd..0000000000 --- a/src/app/api/worktrees/merge/route.ts +++ /dev/null @@ -1,8 +0,0 @@ -export const dynamic = 'force-dynamic'; - -import type { NextRequest } from 'next/server'; -import { handlePost } from './handler'; - -export async function POST(req: NextRequest) { - return handlePost(req, {}); -} diff --git a/src/lib/agents/service.ts b/src/lib/agents/service.ts index 5ffa090434..fb6a751e8b 100644 --- a/src/lib/agents/service.ts +++ b/src/lib/agents/service.ts @@ -39,12 +39,10 @@ import { listAgentPresenceAcrossRepos, listRecentAgentMessages, listRecentAgentMessagesAcrossRepos, - listAgentConversations, normalizeAgentBusRepoPath, persistAgentMessage, releaseAgentInboxWake, updateAgentMessageDelivery, - updateAgentConversation, upsertAgentPresence, } from './store'; @@ -326,43 +324,6 @@ export async function postAgentMessage( return projectNetworkMessage(message, sqlite); } -export function readAgentConversations( - input: { repo: string | null; limit: number }, - principal: RequestPrincipalContext, - sqlite: Database.Database = getSqlite(), -) { - if (principal.role !== 'operator') { - throw new AgentBusError('Conversation history requires an operator credential.', 'agent_conversations_forbidden', 403); - } - const repo = requiredString(input.repo, 'repo', 2_000); - return { repo: normalizeAgentBusRepoPath(repo), conversations: listAgentConversations(repo, input.limit, sqlite) }; -} - -export function changeAgentConversation( - input: unknown, - principal: RequestPrincipalContext, - sqlite: Database.Database = getSqlite(), -) { - if (principal.role !== 'operator') { - throw new AgentBusError('Only the operator can stop or extend a conversation.', 'agent_conversation_operator_required', 403); - } - const body = objectInput(input, 'invalid_agent_conversation'); - const id = requiredString(body.id, 'id', 200); - const repo = requiredString(body.repo, 'repo', 2_000); - if (body.action !== 'close' && body.action !== 'extend') { - throw new AgentBusError('action must be close or extend.', 'invalid_agent_conversation_action', 400); - } - const summary = optionalString(body.summary, 'summary', AGENT_MESSAGE_TEXT_MAX_LENGTH); - try { - return updateAgentConversation({ id, repo, action: body.action, summary }, sqlite); - } catch (error) { - if (error instanceof AgentConversationError) { - throw new AgentBusError(error.message, error.code, error.status); - } - throw error; - } -} - export function joinAgentPresence( input: unknown, principal: RequestPrincipalContext, diff --git a/src/lib/agents/store.ts b/src/lib/agents/store.ts index 0e7a629cba..c7526f7b1b 100644 --- a/src/lib/agents/store.ts +++ b/src/lib/agents/store.ts @@ -15,8 +15,6 @@ export type { AgentMessage, AgentMessageRefs, AgentPresence } from './types'; export { normalizeAgentBusRepoPath } from './repo-paths'; export const AGENT_MESSAGE_TEXT_MAX_LENGTH = 4_000; export const AGENT_CONVERSATION_DEFAULT_LIMIT = 8; -export const AGENT_CONVERSATION_EXTENSION = 4; -export const AGENT_CONVERSATION_MAX_LIMIT = 24; export const AGENT_PRESENCE_TTL_MS = 6 * 60_000; // Re-wake after a bounded delay so a lost queued turn cannot silence a target indefinitely. export const AGENT_NATIVE_WAKE_TTL_MS = 15 * 60_000; @@ -304,17 +302,6 @@ export function getAgentConversation( return row ? mapConversation(row) : null; } -export function listAgentConversations( - repo: string, - limit: number, - sqlite: Database.Database = getSqlite(), -): AgentConversation[] { - ensureAgentBusSchema(sqlite); - return (sqlite.prepare(` - SELECT * FROM agent_conversations WHERE repo_path = ? ORDER BY updated_at DESC LIMIT ? - `).all(normalizeAgentBusRepoPath(repo), limit) as ConversationRow[]).map(mapConversation); -} - export function mapMessage(row: MessageRow, sqlite: Database.Database): AgentMessage { const conversation = row.conversation_id ? sqlite.prepare('SELECT * FROM agent_conversations WHERE id = ?').get(row.conversation_id) as ConversationRow | undefined @@ -763,38 +750,3 @@ export function listRecentAgentMessagesAcrossRepos( `).all(limit) as MessageRow[]; return rows.map((row) => mapMessage(row, sqlite)); } - -export function updateAgentConversation( - input: { id: string; repo: string; action: 'close' | 'extend'; summary?: string | null }, - sqlite: Database.Database = getSqlite(), -): AgentConversation { - ensureAgentBusSchema(sqlite); - const repo = normalizeAgentBusRepoPath(input.repo); - return sqlite.transaction(() => { - const row = sqlite.prepare('SELECT * FROM agent_conversations WHERE id = ?').get(input.id) as ConversationRow | undefined; - if (!row || row.repo_path !== repo) { - throw new AgentConversationError('Conversation was not found in this repository.', 'agent_conversation_not_found', 404); - } - const now = new Date().toISOString(); - if (input.action === 'close') { - if (row.closed_at) return mapConversation(row); - sqlite.prepare(` - UPDATE agent_conversations SET closed_at = ?, closed_reason = 'operator_stop', summary = ?, updated_at = ? WHERE id = ? - `).run(now, input.summary ?? null, now, input.id); - } else { - if (!row.closed_at) { - throw new AgentConversationError('Only a closed conversation can be extended.', 'agent_conversation_open', 409); - } - const nextLimit = Math.min(AGENT_CONVERSATION_MAX_LIMIT, row.turn_count + AGENT_CONVERSATION_EXTENSION); - if (nextLimit <= row.turn_count) { - throw new AgentConversationError('This conversation has reached the maximum turn limit.', 'agent_conversation_max_limit', 409); - } - sqlite.prepare(` - UPDATE agent_conversations - SET turn_limit = ?, closed_at = NULL, closed_reason = NULL, summary = NULL, updated_at = ? - WHERE id = ? - `).run(nextLimit, now, input.id); - } - return mapConversation(sqlite.prepare('SELECT * FROM agent_conversations WHERE id = ?').get(input.id) as ConversationRow); - }).immediate(); -} diff --git a/src/lib/cloud/job-queue.ts b/src/lib/cloud/job-queue.ts index fbdc19e4ae..8aca54ef3b 100644 --- a/src/lib/cloud/job-queue.ts +++ b/src/lib/cloud/job-queue.ts @@ -18,7 +18,6 @@ import type { CloudJobControlType, CloudJobDrainStatus, CloudJobEvent, - CloudJobMetrics, QueueCloudJobControlResult, } from './job-store'; import { SqliteCloudJobStore } from './sqlite-job-store'; @@ -216,10 +215,6 @@ export function listJobControls(teamId: string, jobId: string): CloudJobControl[ return store.listControls(teamId, jobId); } -export function getJobMetrics(teamId: string, jobId: string): CloudJobMetrics | undefined { - return store.metrics(teamId, jobId); -} - export function beginJobDrain(teamId: string): CloudJobDrainStatus { return store.beginDrain(teamId, CLOUD_JOB_BOOT_ID); } diff --git a/src/lib/codebase-memory/mcp-client.ts b/src/lib/codebase-memory/mcp-client.ts index 30f02a4762..b65cbe33e4 100644 --- a/src/lib/codebase-memory/mcp-client.ts +++ b/src/lib/codebase-memory/mcp-client.ts @@ -6,7 +6,7 @@ * child and issue several related calls without paying process startup for * every symbol and fallback lookup. * - * Wire format mirrors src/lib/mcp/test-connection.ts. Both build on the + * Wire format uses the * MCP 2024-11-05 protocol with newline-delimited JSON-RPC frames. */ diff --git a/src/lib/cortex/correction-memory.ts b/src/lib/cortex/correction-memory.ts deleted file mode 100644 index e46b7a029f..0000000000 --- a/src/lib/cortex/correction-memory.ts +++ /dev/null @@ -1,57 +0,0 @@ -import path from 'node:path'; -import { getSqlite } from '@/lib/db'; -import { readOperatorCorrections, retainedCorrectionPredicate } from './operator-corrections'; -import { advanceMemoryRevision } from './memory-revision'; - -/** Inventory pages select IDs in SQL before the contextual reader's scan cap. */ -export function listCorrectionMemory(input: { repoPaths: string[]; projectId?: string | null; query: string; offset: number; limit: number }) { - const db = getSqlite(); - const rows = db.prepare(` - WITH corrections AS ( - SELECT 'approval:' || a.id AS id, a.title AS title, - json_extract(a.resolution_json, '$.note') AS reason, - l.repo_path AS repo_path, a.project_id, 0 AS standing, - strftime('%Y-%m-%dT%H:%M:%fZ', COALESCE(a.resolved_at, a.updated_at) / 1000.0, 'unixepoch') AS at - FROM approvals a LEFT JOIN lanes l ON l.id = COALESCE(a.lane_id, - json_extract(a.continuation_json, '$.laneId'), - (SELECT id FROM lanes WHERE a.packet_id IS NOT NULL AND packet_id = a.packet_id ORDER BY created_at DESC LIMIT 1)) - WHERE a.status = 'rejected' AND json_valid(a.resolution_json) - AND COALESCE(a.tool_name, '') != 'orchestrator_review' - AND TRIM(COALESCE(json_extract(a.resolution_json, '$.note'), '')) != '' - UNION ALL - SELECT 'steer:' || e.id, l.label, json_extract(e.payload_json, '$.message'), l.repo_path, l.project_id, - CASE WHEN LOWER(TRIM(json_extract(e.payload_json, '$.source'))) = 'operator' THEN 0 ELSE 1 END, e.timestamp - FROM lane_events e JOIN lanes l ON l.id = e.lane_id - WHERE e.verb = 'steered_packet' AND json_valid(e.payload_json) - AND json_type(e.payload_json, '$.message') = 'text' - AND TRIM(json_extract(e.payload_json, '$.message')) != '' - ) - SELECT id FROM corrections c WHERE ${retainedCorrectionPredicate('c.id')} - AND (@repos = '[]' OR repo_path IN (SELECT value FROM json_each(@repos))) - AND (@allProjects OR project_id IS @projectId) - AND (@query = '' OR instr(lower(title || ' ' || reason), @query) > 0) - ORDER BY standing, at DESC, id - LIMIT @limit OFFSET @offset - `).all({ repos: JSON.stringify(input.repoPaths.map(value => path.resolve(value))), query: input.query.toLowerCase(), - allProjects: Number(input.projectId === undefined), projectId: input.projectId ?? null, - offset: input.offset, limit: input.limit + 1 }) as Array<{ id: string }>; - const ids = rows.slice(0, input.limit).map(row => row.id); - const corrections = ids.length ? readOperatorCorrections({ ids, projectId: input.projectId, limit: ids.length, throwOnError: true }) : []; - const byId = new Map(corrections.map(correction => [correction.id, correction])); - return { corrections: ids.map(id => byId.get(id)).filter(value => value !== undefined), hasMore: rows.length > input.limit }; -} - -/** Forget recall standing, not the immutable approval/terminal audit. */ -export function forgetCorrectionMemory(id: string, projectId: string | null): boolean { - const db = getSqlite(); - return db.transaction(() => { - db.exec(`CREATE TABLE IF NOT EXISTS forgotten_operator_corrections ( - id TEXT PRIMARY KEY, forgotten_at TEXT NOT NULL - )`); - const found = readOperatorCorrections({ ids: [id], projectId, limit: 1, throwOnError: true })[0]; - if (!found) return false; - db.prepare('INSERT INTO forgotten_operator_corrections (id, forgotten_at) VALUES (?, ?)').run(id, new Date().toISOString()); - advanceMemoryRevision(db); - return true; - })(); -} diff --git a/src/lib/github-broker/actions.ts b/src/lib/github-broker/actions.ts index aeac756cf5..8d53155c78 100644 --- a/src/lib/github-broker/actions.ts +++ b/src/lib/github-broker/actions.ts @@ -125,28 +125,6 @@ export async function createGitHubIssue( }; } -export async function commentOnGitHubIssue(repoFullName: string, issueNumber: number, body: string) { - const { response } = await githubInstallationFetch(repoFullName, `/repos/${repoFullName}/issues/${issueNumber}/comments`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ body }), - }); - return parseGitHubJson<{ html_url?: string | null }>(response); -} - -export async function addLabelsToGitHubIssue(repoFullName: string, issueNumber: number, labels: string[]) { - const normalized = labels.map((label) => label.trim()).filter(Boolean); - if (normalized.length === 0) return []; - - const { response } = await githubInstallationFetch(repoFullName, `/repos/${repoFullName}/issues/${issueNumber}/labels`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ labels: normalized }), - }); - - return parseGitHubJson>(response); -} - export async function findGitHubPullRequestByHead(repoFullName: string, branch: string) { const owner = repoFullName.split('/')[0] ?? ''; const { response } = await githubInstallationFetch( diff --git a/src/lib/github-broker/index.ts b/src/lib/github-broker/index.ts index d72b5dce3b..f137930bb2 100644 --- a/src/lib/github-broker/index.ts +++ b/src/lib/github-broker/index.ts @@ -17,8 +17,6 @@ export { fetchGitHubCommits, fetchGitHubWorkflowRuns, fetchGitHubWorkflowRunDeta export { fetchGitHubLabels, createGitHubIssue, - commentOnGitHubIssue, - addLabelsToGitHubIssue, findGitHubPullRequestByHead, createGitHubPullRequest, reviewGitHubPullRequest, diff --git a/src/lib/hooks/claude-code-pretool-hook.ts b/src/lib/hooks/claude-code-pretool-hook.ts index f3197eb6e4..fff5fef621 100644 --- a/src/lib/hooks/claude-code-pretool-hook.ts +++ b/src/lib/hooks/claude-code-pretool-hook.ts @@ -210,7 +210,7 @@ async function main() { // Distinguish o8-spawned autonomous agents from the operator's own paired // Claude Code session. o8 sets O8_MANAGED_SESSION=1 on every spawn - // (orchestrator, claude-code adapter, auto-compact, claude-code/send + // (orchestrator, claude-code adapter, auto-compact // route); an operator running `claude` directly in their terminal does // not have this env var. // diff --git a/src/lib/mcp/test-connection.ts b/src/lib/mcp/test-connection.ts deleted file mode 100644 index f5ab58d5dc..0000000000 --- a/src/lib/mcp/test-connection.ts +++ /dev/null @@ -1,418 +0,0 @@ -/** - * Exercises a stdio or HTTP MCP server enough to answer: - * - * - Did it start? - * - Does it respond to JSON-RPC `initialize`? - * - How many tools does `tools/list` report? - * - * We don't take a dependency on `@modelcontextprotocol/sdk` here — the - * Tauri bundle doesn't ship it, and the wire format is small enough to - * implement directly. - * - * Timeouts are strict. A stuck child process is killed with SIGTERM (then - * SIGKILL). Partial stderr is captured and returned so the UI can show - * actionable diagnostics. - */ - -import { spawn } from '@/lib/providers/child-process'; -import { childEnvironment } from '@/lib/providers/spawn-environment'; -import { cliInvocation } from '@/lib/runtimes/shared/cli-spawn'; -import { isNpxFamily } from './npx-detection'; - -export interface McpTestSuccess { - ok: true; - transport: 'stdio' | 'http'; - tools: Array<{ name: string; description?: string }>; - toolCount: number; - durationMs: number; - stderr?: string; - /** True when the probe used the extended npx-family timeout. */ - npxFamily?: boolean; -} - -export interface McpTestFailure { - ok: false; - transport: 'stdio' | 'http'; - error: string; - stderr?: string; - durationMs: number; - /** True when the probe used the extended npx-family timeout. */ - npxFamily?: boolean; -} - -export type McpTestResult = McpTestSuccess | McpTestFailure; - -export interface StdioTestInput { - transport: 'stdio'; - command: string; - args?: string[]; - env?: Record; -} - -export interface HttpTestInput { - transport: 'http'; - url: string; - headers?: Record; -} - -export type McpTestInput = StdioTestInput | HttpTestInput; - -const DEFAULT_TIMEOUT_MS = 8_000; -const NPX_TIMEOUT_MS = 45_000; -const STDERR_CAP = 4000; - -interface JsonRpcRequest { - jsonrpc: '2.0'; - id: number; - method: string; - params?: Record; -} - -interface JsonRpcResponse { - jsonrpc: '2.0'; - id?: number | string | null; - result?: unknown; - error?: { code: number; message: string }; -} - -interface ToolsListResult { - tools?: Array<{ name?: unknown; description?: unknown }>; -} - -function shortenStderr(text: string): string { - const trimmed = text.trim(); - if (trimmed.length <= STDERR_CAP) return trimmed; - return `${trimmed.slice(0, STDERR_CAP)}… (${trimmed.length - STDERR_CAP} more bytes)`; -} - -function normalizeTools(result: unknown): Array<{ name: string; description?: string }> { - if (!result || typeof result !== 'object') return []; - const payload = result as ToolsListResult; - if (!Array.isArray(payload.tools)) return []; - const out: Array<{ name: string; description?: string }> = []; - for (const tool of payload.tools) { - const name = typeof tool?.name === 'string' ? tool.name : ''; - if (!name) continue; - const description = typeof tool?.description === 'string' ? tool.description : undefined; - out.push(description !== undefined ? { name, description } : { name }); - } - return out; -} - -async function testStdio(input: StdioTestInput, timeoutMs: number, npxFamily: boolean): Promise { - const started = Date.now(); - let stderrBuf = ''; - let resolved = false; - let killed = false; - - return new Promise((resolve) => { - let child: ReturnType | null = null; - const childEnv = childEnvironment({ env: input.env ?? {}, inject: false }); - try { - // Most stdio MCP servers are configured as `npx …`, which on Windows is - // `npx.cmd` — spawning it directly throws EINVAL and the user sees - // "spawn failed" for a server that is installed and fine. - const launch = cliInvocation(input.command, input.args ?? []); - child = spawn(launch.command, launch.args, { - windowsHide: true, - stdio: ['pipe', 'pipe', 'pipe'], - env: childEnv, - }); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - resolve({ - ok: false, - transport: 'stdio', - error: `Spawn failed — ${message}`, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - return; - } - - const finish = (result: McpTestResult) => { - if (resolved) return; - resolved = true; - if (child && !killed) { - killed = true; - try { child.kill('SIGTERM'); } catch { /* ignore */ } - setTimeout(() => { - if (child && !child.killed) { - try { child.kill('SIGKILL'); } catch { /* ignore */ } - } - }, 500); - } - resolve(result); - }; - - const timeout = setTimeout(() => { - finish({ - ok: false, - transport: 'stdio', - error: `Timed out after ${timeoutMs}ms waiting for tools/list`, - stderr: shortenStderr(stderrBuf) || undefined, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - }, timeoutMs); - - child.on('error', (err) => { - clearTimeout(timeout); - finish({ - ok: false, - transport: 'stdio', - error: `Process error — ${err.message}`, - stderr: shortenStderr(stderrBuf) || undefined, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - }); - - child.stderr?.on('data', (chunk: Buffer) => { - stderrBuf += chunk.toString('utf-8'); - if (stderrBuf.length > STDERR_CAP * 2) { - stderrBuf = stderrBuf.slice(-STDERR_CAP * 2); - } - }); - - child.on('exit', (code, signal) => { - if (resolved) return; - clearTimeout(timeout); - const hint = signal ? `signal ${signal}` : `exit code ${code ?? '?'}`; - finish({ - ok: false, - transport: 'stdio', - error: `Process exited before tools/list completed (${hint})`, - stderr: shortenStderr(stderrBuf) || undefined, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - }); - - // Parse stdout as newline-delimited JSON-RPC. - let stdoutBuf = ''; - const pending = new Map void>(); - - child.stdout?.on('data', (chunk: Buffer) => { - stdoutBuf += chunk.toString('utf-8'); - let newlineIdx = stdoutBuf.indexOf('\n'); - while (newlineIdx !== -1) { - const line = stdoutBuf.slice(0, newlineIdx).trim(); - stdoutBuf = stdoutBuf.slice(newlineIdx + 1); - newlineIdx = stdoutBuf.indexOf('\n'); - if (!line) continue; - try { - const msg = JSON.parse(line) as JsonRpcResponse; - if (typeof msg.id === 'number' && pending.has(msg.id)) { - const handler = pending.get(msg.id)!; - pending.delete(msg.id); - handler(msg); - } - } catch { - // Ignore malformed or notification frames. - } - } - }); - - const writeRequest = (req: JsonRpcRequest) => { - if (!child?.stdin || child.stdin.destroyed) { - finish({ - ok: false, - transport: 'stdio', - error: 'Child stdin closed before request was sent', - stderr: shortenStderr(stderrBuf) || undefined, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - return false; - } - try { - child.stdin.write(JSON.stringify(req) + '\n'); - return true; - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - finish({ - ok: false, - transport: 'stdio', - error: `Failed to write request — ${message}`, - stderr: shortenStderr(stderrBuf) || undefined, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - return false; - } - }; - - const awaitResponse = (id: number): Promise => { - return new Promise((responseResolve) => { - pending.set(id, responseResolve); - }); - }; - - // 1. Send initialize. - const initId = 1; - if (!writeRequest({ - jsonrpc: '2.0', - id: initId, - method: 'initialize', - params: { - protocolVersion: '2024-11-05', - capabilities: {}, - clientInfo: { name: 'o8-test-connection', version: '1.0.0' }, - }, - })) return; - - void awaitResponse(initId).then((initResp) => { - if (initResp.error) { - finish({ - ok: false, - transport: 'stdio', - error: `initialize failed — ${initResp.error.message}`, - stderr: shortenStderr(stderrBuf) || undefined, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - return; - } - - // Optional per-spec: notify initialized. - writeRequest({ jsonrpc: '2.0', id: 2, method: 'notifications/initialized' }); - - // 2. Send tools/list. - const listId = 3; - if (!writeRequest({ jsonrpc: '2.0', id: listId, method: 'tools/list' })) return; - - void awaitResponse(listId).then((listResp) => { - if (listResp.error) { - finish({ - ok: false, - transport: 'stdio', - error: `tools/list failed — ${listResp.error.message}`, - stderr: shortenStderr(stderrBuf) || undefined, - durationMs: Date.now() - started, - ...(npxFamily ? { npxFamily: true } : {}), - }); - return; - } - const tools = normalizeTools(listResp.result); - clearTimeout(timeout); - finish({ - ok: true, - transport: 'stdio', - tools, - toolCount: tools.length, - durationMs: Date.now() - started, - stderr: shortenStderr(stderrBuf) || undefined, - ...(npxFamily ? { npxFamily: true } : {}), - }); - }); - }); - }); -} - -async function testHttp(input: HttpTestInput, timeoutMs: number): Promise { - const started = Date.now(); - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), timeoutMs); - - try { - const headers: Record = { - 'content-type': 'application/json', - accept: 'application/json, text/event-stream', - ...input.headers, - }; - - const requestBody = { - jsonrpc: '2.0', - id: 1, - method: 'tools/list', - }; - - const res = await fetch(input.url, { - method: 'POST', - headers, - body: JSON.stringify(requestBody), - signal: controller.signal, - }); - - clearTimeout(timeout); - - if (!res.ok) { - return { - ok: false, - transport: 'http', - error: `HTTP ${res.status} ${res.statusText}`, - durationMs: Date.now() - started, - }; - } - - const text = await res.text(); - let payload: JsonRpcResponse | null = null; - try { - payload = JSON.parse(text) as JsonRpcResponse; - } catch { - // Some MCP HTTP servers reply as SSE. Grab the last `data:` chunk. - const lines = text.split('\n').map((line) => line.trim()).filter(Boolean); - for (let i = lines.length - 1; i >= 0; i -= 1) { - if (!lines[i].startsWith('data:')) continue; - const data = lines[i].slice(5).trim(); - if (!data) continue; - try { - payload = JSON.parse(data) as JsonRpcResponse; - break; - } catch { - // Keep scanning. - } - } - } - - if (!payload) { - return { - ok: false, - transport: 'http', - error: 'Server replied with non-JSON body', - durationMs: Date.now() - started, - }; - } - - if (payload.error) { - return { - ok: false, - transport: 'http', - error: `tools/list failed — ${payload.error.message}`, - durationMs: Date.now() - started, - }; - } - - const tools = normalizeTools(payload.result); - return { - ok: true, - transport: 'http', - tools, - toolCount: tools.length, - durationMs: Date.now() - started, - }; - } catch (error) { - clearTimeout(timeout); - const aborted = controller.signal.aborted; - const message = error instanceof Error ? error.message : String(error); - return { - ok: false, - transport: 'http', - error: aborted ? `Timed out after ${timeoutMs}ms` : `Request failed — ${message}`, - durationMs: Date.now() - started, - }; - } -} - -export async function testMcpConnection( - input: McpTestInput, - timeoutMs?: number, -): Promise { - if (input.transport === 'stdio') { - const npxFamily = isNpxFamily(input.command); - const resolvedTimeout = timeoutMs ?? (npxFamily ? NPX_TIMEOUT_MS : DEFAULT_TIMEOUT_MS); - return testStdio(input, resolvedTimeout, npxFamily); - } - return testHttp(input, timeoutMs ?? DEFAULT_TIMEOUT_MS); -} diff --git a/src/lib/panel/git-commits.ts b/src/lib/panel/git-commits.ts index eabc3e7371..c851c6e536 100644 --- a/src/lib/panel/git-commits.ts +++ b/src/lib/panel/git-commits.ts @@ -297,11 +297,6 @@ export function getWorkspaceCommitDiffFiles(root: string, sha: string) { .filter((file): file is PanelCommitDiffFile => file !== null); } -export function getLocalCommitDiffFiles(sha: string, workspace?: string | null) { - const root = resolvePanelWorkspaceRoot(workspace); - return getWorkspaceCommitDiffFiles(root, sha); -} - export function getLocalCommitDetail(sha: string, workspace?: string | null) { const root = resolvePanelWorkspaceRoot(workspace); const meta = runGit(root, ['log', '-1', '--format=%H%n%s%n%an%n%ae%n%aI%n%b', sha]).trim(); diff --git a/src/lib/runtime/ide-surface-state.ts b/src/lib/runtime/ide-surface-state.ts index 3230e8612b..1736dc6314 100644 --- a/src/lib/runtime/ide-surface-state.ts +++ b/src/lib/runtime/ide-surface-state.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import path from 'node:path'; import { getDataDir } from '@/lib/data-dir-migration'; @@ -35,25 +35,6 @@ export function readIdeSurfaceState(): IdeSurfaceState | null { } } -export function writeIdeSurfaceState(input: { terminalRepoPaths?: string[]; activeRepoPath?: string | null }) { - const terminalRepoPaths = Array.from(new Set( - (input.terminalRepoPaths ?? []) - .map((repoPath) => normalizeRepoPath(repoPath)) - .filter((repoPath): repoPath is string => Boolean(repoPath)), - )); - const next: IdeSurfaceState = { - updatedAt: new Date().toISOString(), - terminalRepoPaths, - activeRepoPath: normalizeRepoPath(input.activeRepoPath), - }; - - if (!existsSync(STATE_DIR)) { - mkdirSync(STATE_DIR, { recursive: true }); - } - writeFileSync(SURFACE_STATE_FILE, JSON.stringify(next, null, 2)); - return next; -} - export function listIdeSurfaceRepoPaths() { const state = readIdeSurfaceState(); if (!state) return []; diff --git a/src/lib/supervisor/spawn-environment-rule.ts b/src/lib/supervisor/spawn-environment-rule.ts index 7eb0e23df2..36683723b6 100644 --- a/src/lib/supervisor/spawn-environment-rule.ts +++ b/src/lib/supervisor/spawn-environment-rule.ts @@ -43,7 +43,6 @@ const DEFERRED_BOUNDARIES: ReadonlyMap = new Map([ ['src/lib/mcp/tool-spine/build.ts', 'payer policy part b'], ['src/lib/mcp/tool-spine/emit-claude.ts', 'payer policy part b'], ['src/lib/mcp/tool-spine/emit-codex.ts', 'payer policy part b'], - ['src/lib/mcp/test-connection.ts', 'payer policy part b'], ['src/lib/mcp/operator-node22-reexec.ts', 'payer policy part b'], ['src/lib/codebase-memory/mcp-client.ts', 'payer policy part b'], ['src/lib/providers/deferred-mcp-arguments.ts', 'payer policy part b'], diff --git a/src/lib/viewers/http-routes.ts b/src/lib/viewers/http-routes.ts index ed469d1ddd..de53e5930a 100644 --- a/src/lib/viewers/http-routes.ts +++ b/src/lib/viewers/http-routes.ts @@ -4,24 +4,15 @@ export const viewerHttpRoutes = [ { path: '/api/v2/files', load: () => import('@/app/api/v2/files/route') }, { path: '/api/panel/file-io', load: () => import('@/app/api/panel/file-io/route') }, { path: '/api/panel/file-diff', load: () => import('@/app/api/panel/file-diff/route') }, - { path: '/api/panel/worktree-diff', load: () => import('@/app/api/panel/worktree-diff/route') }, - { path: '/api/panel/commit-diff', load: () => import('@/app/api/panel/commit-diff/route') }, { path: '/api/panel/commits/[hash]', load: () => import('@/app/api/panel/commits/[hash]/route') }, { path: '/api/panel/commits/[hash]/file', load: () => import('@/app/api/panel/commits/[hash]/file/route') }, { path: '/api/panel/git-log', load: () => import('@/app/api/panel/git-log/route') }, { path: '/api/panel/git/log', load: () => import('@/app/api/panel/git/log/route') }, - { path: '/api/review/file', load: () => import('@/app/api/review/file/route') }, - { path: '/api/review/diff', load: () => import('@/app/api/review/diff/route') }, - { path: '/api/panel/file-preview', load: () => import('@/app/api/panel/file-preview/route') }, - { path: '/api/panel/readme', load: () => import('@/app/api/panel/readme/route') }, { path: '/api/panel/file-asset', load: () => import('@/app/api/panel/file-asset/route') }, { path: '/api/panel/serve-image', load: () => import('@/app/api/panel/serve-image/route') }, { path: '/api/mobile/media', load: () => import('@/app/api/mobile/media/route') }, - { path: '/api/panel/report-artifact', load: () => import('@/app/api/panel/report-artifact/route') }, { path: '/api/panel/threads/artifact', load: () => import('@/app/api/panel/threads/artifact/route') }, { path: '/api/v2/context/files', load: () => import('@/app/api/v2/context/files/route') }, { path: '/api/task-artifacts/[id]', load: () => import('@/app/api/task-artifacts/[id]/route') }, - { path: '/api/codex/diffs', load: () => import('@/app/api/codex/diffs/route') }, - { path: '/api/claude-code/diffs', load: () => import('@/app/api/claude-code/diffs/route') }, { path: '/api/repo-spec', load: () => import('@/app/api/repo-spec/route') }, ].map(entry => ({ ...entry, methods: entry.path === '/api/v2/context/files' ? ['GET', 'POST'] : ['GET'] })); diff --git a/src/lib/worker/feature-flags.ts b/src/lib/worker/feature-flags.ts index 94a5f87731..3bf826402d 100644 --- a/src/lib/worker/feature-flags.ts +++ b/src/lib/worker/feature-flags.ts @@ -1,7 +1,6 @@ import 'server-only'; import { readFileSync } from 'node:fs'; -import { mkdir, readFile, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { getDataDir } from '@/lib/data-dir-migration'; @@ -40,23 +39,6 @@ function isMissingFile(error: unknown) { return (error as NodeJS.ErrnoException).code === 'ENOENT'; } -export async function getRemoteRuntimeFlag(): Promise { - const envFlag = getEnvRemoteRuntimeFlag(); - if (envFlag) return envFlag; - - try { - const raw = await readFile(getFeatureFlagsPath(), 'utf8'); - const fileFlag = readRemoteRuntimeFlag(raw); - if (fileFlag) return fileFlag; - } catch (error) { - if (!isMissingFile(error)) { - console.error('[worker-flags] Failed to read feature flags:', error); - } - } - - return { enabled: false, source: 'off' }; -} - export function getRemoteRuntimeFlagSync(): RemoteRuntimeFlagState { const envFlag = getEnvRemoteRuntimeFlag(); if (envFlag) return envFlag; @@ -73,24 +55,3 @@ export function getRemoteRuntimeFlagSync(): RemoteRuntimeFlagState { return { enabled: false, source: 'off' }; } - -export async function setRemoteRuntimeFlag(enabled: boolean): Promise { - const filePath = getFeatureFlagsPath(); - let nextFlags: Record = {}; - - try { - const raw = await readFile(filePath, 'utf8'); - const parsed = JSON.parse(raw) as Record; - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { - nextFlags = parsed; - } - } catch (error) { - if (!isMissingFile(error)) { - console.error('[worker-flags] Failed to read existing feature flags before write:', error); - } - } - - nextFlags.remoteRuntime = enabled; - await mkdir(path.dirname(filePath), { recursive: true }); - await writeFile(filePath, `${JSON.stringify(nextFlags, null, 2)}\n`, 'utf8'); -} diff --git a/src/lib/worker/tokens.ts b/src/lib/worker/tokens.ts index 1b86971445..0763d7bfa3 100644 --- a/src/lib/worker/tokens.ts +++ b/src/lib/worker/tokens.ts @@ -4,100 +4,10 @@ import { createHash, randomBytes, randomUUID } from 'node:crypto'; import { getSqlite } from '@/lib/db'; import { writeActivePacketWorkerTokenHashes } from '@/lib/auth/packet-worker-token'; -export type FleetStatusKind = 'running' | 'completed' | 'failed' | 'cancelled'; - -export interface WorkerTokenSummary { - id: string; - label: string | null; - scope: string; - maxWorkers: number; - createdAt: string; - revokedAt: string | null; -} - -export interface FleetStatusCounts { - running: number; - completed: number; - failed: number; - cancelled: number; -} - -export interface FleetTokenSummary { - tokenId: string; - label: string | null; - totalRuns: number; - lastRunAt: string; - hasActiveRuns: boolean; - counts: FleetStatusCounts; -} - -export interface FleetStatusSummary { - counts: FleetStatusCounts; - tokens: FleetTokenSummary[]; -} - -interface FleetRunRow { - worker_token_id: string; - label: string | null; - status: string; - started_at: string; - completed_at: string | null; - last_event_at: string; -} - -function createEmptyCounts(): FleetStatusCounts { - return { - running: 0, - completed: 0, - failed: 0, - cancelled: 0, - }; -} - function nowIso() { return new Date().toISOString(); } -function normalizeStatus(status: string): FleetStatusKind { - if (status === 'completed') return 'completed'; - if (status === 'cancelled') return 'cancelled'; - if (status === 'errored' || status === 'failed') return 'failed'; - return 'running'; -} - -function getRunTimestamp(row: FleetRunRow) { - return row.last_event_at || row.completed_at || row.started_at; -} - -export function listTokens(): WorkerTokenSummary[] { - return getSqlite() - .prepare(` - SELECT id, label, scope, max_workers, created_at, revoked_at - FROM worker_tokens - ORDER BY created_at DESC - `) - .all() - .map((row) => { - const token = row as { - id: string; - label: string | null; - scope: string; - max_workers: number; - created_at: string; - revoked_at: string | null; - }; - - return { - id: token.id, - label: token.label, - scope: token.scope, - maxWorkers: token.max_workers, - createdAt: token.created_at, - revokedAt: token.revoked_at, - }; - }); -} - export function createToken(input: { label: string; scope?: string; @@ -136,56 +46,3 @@ export function revokeToken(id: string): boolean { return result.changes > 0; }).immediate(); } - -export function getFleetStatus(): FleetStatusSummary { - const rows = getSqlite() - .prepare(` - SELECT wr.worker_token_id, wt.label, wr.status, wr.started_at, wr.completed_at, wr.last_event_at - FROM worker_runs wr - JOIN worker_tokens wt ON wt.id = wr.worker_token_id - ORDER BY COALESCE(wr.last_event_at, wr.completed_at, wr.started_at) DESC - LIMIT 100 - `) - .all() as FleetRunRow[]; - - const counts = createEmptyCounts(); - const tokenMap = new Map(); - - for (const row of rows) { - const status = normalizeStatus(row.status); - counts[status] += 1; - - const existing = tokenMap.get(row.worker_token_id) ?? { - tokenId: row.worker_token_id, - label: row.label, - totalRuns: 0, - lastRunAt: getRunTimestamp(row), - hasActiveRuns: false, - counts: createEmptyCounts(), - }; - - existing.totalRuns += 1; - existing.counts[status] += 1; - existing.hasActiveRuns = existing.hasActiveRuns || status === 'running'; - - const runAt = getRunTimestamp(row); - if (runAt > existing.lastRunAt) { - existing.lastRunAt = runAt; - } - - tokenMap.set(row.worker_token_id, existing); - } - - return { - counts, - tokens: [...tokenMap.values()].sort((a, b) => { - if (a.hasActiveRuns !== b.hasActiveRuns) { - return a.hasActiveRuns ? -1 : 1; - } - if (a.lastRunAt !== b.lastRunAt) { - return a.lastRunAt > b.lastRunAt ? -1 : 1; - } - return b.totalRuns - a.totalRuns; - }), - }; -} diff --git a/src/lib/workspace/exact-discard.ts b/src/lib/workspace/exact-discard.ts deleted file mode 100644 index 9c852ba7d3..0000000000 --- a/src/lib/workspace/exact-discard.ts +++ /dev/null @@ -1,79 +0,0 @@ -import type { Lane } from '@/lib/lane/types'; -import { materializationAwareExecFile } from '@/lib/worktree/materialization-execution'; -import { withWorktreeMetaTransaction } from '@/lib/worktree/metadata-store'; -import type { WorkspaceIsolationKind } from '@/lib/worktree/types'; -import { completeExactManagedDirectoryRetirement, retireExactManagedDirectory } from './exact-managed-directory-retirement'; -import { assertManagedWorkspaceMaterialization, readManagedWorkspaceMaterialization } from './managed-materialization-identity'; -import type { ProcessQuiescenceReceipt } from './process-quiescence'; -import { - finishWorkspaceMaterializationRetirement, - prepareWorkspaceMaterializationRetirement, - rollbackWorkspaceMaterializationRetirement, -} from './workspace-materialization-retirement'; - -interface ExactDiscardInput { - lane: Lane; - worktreeId: string; - isolationKind: WorkspaceIsolationKind; - processProbe: (sessionKey: string, workspacePath: string) => Promise; -} - -export class ExactDiscardUnavailableError extends Error { - constructor(readonly code: 'workspace_process_not_quiescent', message: string) { - super(message); - this.name = 'ExactDiscardUnavailableError'; - } -} - -/** Discard source changes through the preservation-bound exact retirement claim. */ -export async function discardExactManagedWorktree(input: ExactDiscardInput): Promise { - const workspacePath = input.lane.worktreePath; - const sessionKey = input.lane.sessionKey; - if (!workspacePath || !sessionKey) throw new Error('Exact discard requires a managed workspace path and owned session.'); - const verifyProcess = async (candidatePath: string) => { - const receipt = await input.processProbe(sessionKey, candidatePath); - if (receipt.state !== 'quiescent') { - throw new ExactDiscardUnavailableError('workspace_process_not_quiescent', - `Exact discard refused because owned-workspace process truth is ${receipt.state}.`); - } - }; - await verifyProcess(workspacePath); - const managed = await readManagedWorkspaceMaterialization(input.lane.repoPath, workspacePath); - if (managed.metadata.id !== input.worktreeId || managed.metadata.sessionKey !== sessionKey - || !managed.metadata.materializationParentIdentity) throw new Error('Exact discard manager ownership changed.'); - const snapshot = await prepareWorkspaceMaterializationRetirement(input.lane.repoPath, workspacePath, 'discard'); - if (!snapshot) throw new Error('Exact discard has no persisted packet retirement owner.'); - try { - await withWorktreeMetaTransaction(input.lane.repoPath, async (transaction) => { - const current = (await transaction.readAll())[input.worktreeId]; - if (!current || current.materializationIdentity?.device !== managed.identity.device - || current.materializationIdentity.inode !== managed.identity.inode - || current.sessionKey !== sessionKey) throw new Error('Exact discard manager receipt changed.'); - await retireExactManagedDirectory({ - repositoryPath: input.lane.repoPath, worktreeId: input.worktreeId, - directoryPath: workspacePath, identity: managed.identity, - parentIdentity: managed.metadata.materializationParentIdentity, - beforeRetirementRename: () => verifyProcess(workspacePath), - beforeRetirementPurge: verifyProcess, - }); - await finishWorkspaceMaterializationRetirement(workspacePath, 'discard'); - await transaction.remove(input.worktreeId); - completeExactManagedDirectoryRetirement(input.lane.repoPath, input.worktreeId); - }); - if (input.isolationKind === 'git-worktree') { - await materializationAwareExecFile('git', ['worktree', 'prune'], { - cwd: input.lane.repoPath, windowsHide: true, timeout: 10_000, - }); - } - if (snapshot.branch !== input.lane.baseBranch) { - await materializationAwareExecFile('git', ['update-ref', '-d', `refs/heads/${snapshot.branch}`, snapshot.headCommit], { - cwd: input.lane.repoPath, windowsHide: true, timeout: 5_000, - }); - } - } catch (error) { - await assertManagedWorkspaceMaterialization(input.lane.repoPath, workspacePath).then(() => { - rollbackWorkspaceMaterializationRetirement(workspacePath, 'discard', error); - }).catch(() => undefined); - throw error; - } -} diff --git a/src/lib/workspace/workspace-materialization-retirement.ts b/src/lib/workspace/workspace-materialization-retirement.ts index 3c92a8c14c..6cc6c05f80 100644 --- a/src/lib/workspace/workspace-materialization-retirement.ts +++ b/src/lib/workspace/workspace-materialization-retirement.ts @@ -14,7 +14,6 @@ import { createWorkspaceSnapshot, listWorkspaceSnapshotTransitions, listWorkspaceSnapshotsByOriginalPath, - listWorkspaceSnapshotsByRepositoryUuid, transitionWorkspaceSnapshot, type WorkspaceSnapshotRecord, } from '@/lib/worktree/snapshot-state'; @@ -580,35 +579,3 @@ export async function confirmWorkspaceMaterializationRetirement( workspacePath: path.resolve(workspacePath), }); } - -/** Read exact terminal replay truth without advancing durable or physical state. */ -export function findWorkspaceMaterializationRetirement( - repositoryUuid: string, - worktreeId: string, - action: WorkspaceRetirementAction, -): WorkspaceSnapshotRecord | null { - const matches = listWorkspaceSnapshotsByRepositoryUuid(repositoryUuid).filter((snapshot) => ( - path.basename(path.resolve(snapshot.originalPath)) === worktreeId - && (snapshot.state === 'retiring' || snapshot.state === 'retired') - )); - if (matches.length > 1) { - throw new Error('Workspace retirement replay found ambiguous durable worktree truth.'); - } - const snapshot = matches[0]; - if (!snapshot) return null; - if (recordedAction(snapshot) !== action) { - throw new Error('Workspace retirement replay action conflicts with durable terminal truth.'); - } - return snapshot; -} - -/** Resolve an exact retry after physical cleanup completed before the route response. */ -export async function replayWorkspaceMaterializationRetirement( - repositoryUuid: string, - worktreeId: string, - action: WorkspaceRetirementAction, -): Promise { - const snapshot = findWorkspaceMaterializationRetirement(repositoryUuid, worktreeId, action); - if (!snapshot) return null; - return finishWorkspaceMaterializationRetirement(snapshot.originalPath, action); -} diff --git a/src/middleware.ts b/src/middleware.ts index 3c0fbf014a..f1b4a611aa 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -153,12 +153,11 @@ const DEVICE_CAPABILITIES: Array<{ methods: ReadonlySet; path: RegExp }> { methods: new Set(['GET', 'POST', 'PATCH', 'DELETE']), path: /^\/api\/mobile\/(?:action|activity|bootstrap|diff-comments?|genui\/stream|history|inbox|live-activity\/(?:register|sync)|media|orchestrator\/(?:openclaw-agents|openclaw-availability|packets|threads(?:\/[^/]+\/reveal|\/reveal)?)|search|sync|terminal-input|terminal-sessions)\/?$/ }, { methods: new Set(['GET', 'POST']), path: /^\/api\/panel\/approvals\/?$/ }, { methods: new Set(['GET']), path: /^\/api\/panel\/(?:status|github-status|repos|operator-defaults|projects|search)\/?$/ }, - { methods: new Set(['POST']), path: /^\/api\/panel\/(?:operator-defaults|pr\/review)\/?$/ }, + { methods: new Set(['POST']), path: /^\/api\/panel\/operator-defaults\/?$/ }, { methods: new Set(['GET', 'POST', 'PATCH', 'DELETE']), path: /^\/api\/v2\/chat-history(?:\/list)?\/?$/ }, { methods: new Set(['GET']), path: /^\/api\/v2\/repos\/?$/ }, { methods: new Set(['POST']), path: /^\/api\/v2\/proxy\/(?:llm|cli)\/?$/ }, { methods: new Set(['POST']), path: /^\/api\/runtime\/launch\/?$/ }, - { methods: new Set(['POST']), path: /^\/api\/worktrees\/merge\/?$/ }, { methods: new Set(['POST']), path: /^\/api\/orchestrator\/reset-session\/?$/ }, // Layer-3 steer from the phone. The relay connector forwards the per-device // bearer verbatim (stamping a NON-loopback client-addr), so the steer route is diff --git a/src/ws-server.ts b/src/ws-server.ts index 00a54bd4fc..2e5b6addd4 100644 --- a/src/ws-server.ts +++ b/src/ws-server.ts @@ -6984,58 +6984,6 @@ const httpServer = createServer(async (req, res) => { return; } - if (req.url === '/terminal-exec' && req.method === 'POST') { - if (!isAuthorizedInternalRequest(req)) { - res.writeHead(401); - res.end('unauthorized'); - return; - } - - const chunks: Buffer[] = []; - req.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))); - req.on('end', () => { - let payload: { sessionName?: string; command?: string } | null = null; - try { - payload = JSON.parse(Buffer.concat(chunks).toString('utf-8')) as { sessionName?: string; command?: string }; - } catch { - res.writeHead(400); - res.end('invalid json'); - return; - } - - const sessionName = payload?.sessionName?.trim(); - const command = payload?.command; - if (!sessionName || !command) { - res.writeHead(400); - res.end('sessionName and command required'); - return; - } - - const attachment = terminalAttachments.get(sessionName); - if (!attachment) { - res.writeHead(404); - res.end('session not found'); - return; - } - if (attachment.controlClientId) { - res.writeHead(409, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'terminal_busy' })); - return; - } - - try { - // PTY raw-mode TUIs (like Claude Code) interpret \r as Enter, not \n - attachment.ptyProcess.write(`${command}\r`); - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ ok: true })); - } catch (error) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'Failed to write to terminal' })); - } - }); - return; - } - if (req.url?.startsWith('/terminal-scrollback') && req.method === 'GET') { if (!isAuthorizedInternalRequest(req)) { res.writeHead(401); diff --git a/tests/agent-message-bus-real-path.test.ts b/tests/agent-message-bus-real-path.test.ts index 81c536e6be..aac88366f1 100644 --- a/tests/agent-message-bus-real-path.test.ts +++ b/tests/agent-message-bus-real-path.test.ts @@ -30,7 +30,6 @@ const heartbeatRoute = await import('@/app/api/lanes/[id]/heartbeat/route'); const presenceRoute = await import('@/app/api/agents/presence/route'); const inboxRoute = await import('@/app/api/agents/inbox/route'); const messageRoute = await import('@/app/api/agents/message/route'); -const conversationRoute = await import('@/app/api/agents/conversation/route'); const { createAgentMessagePostHandler } = await import('@/lib/agents/message-route-handler'); const broadcastEventsRoute = await import('@/app/api/broadcast/events/route'); const { panelGateMiddleware } = await import('@/middleware'); @@ -929,24 +928,11 @@ describe('agent message bus real path', () => { expect(overBudget.status).toBe(409); expect(count()).toBe(8); - const workerExtend = await conversationRoute.POST(request('http://localhost:3001/api/agents/conversation', { - token: workerToken, method: 'POST', body: { id: conversationId, repo, action: 'extend' }, - })); - expect(workerExtend.status).toBe(403); - const extended = await conversationRoute.POST(request('http://localhost:3001/api/agents/conversation', { - token: OPERATOR_TOKEN, method: 'POST', body: { id: conversationId, repo, action: 'extend' }, - })); - expect(extended.status).toBe(200); - await expect(extended.json()).resolves.toMatchObject({ conversation: { turnLimit: 12, remainingTurns: 4, status: 'open' } }); - const ninth = await send({ fromAgentId: 'conversation-a', to: 'Birch', text: 'Operator reopened this.', replyToId: latest.id }); - expect(ninth.status).toBe(201); - expect(ninth.body.message?.conversation).toMatchObject({ turnIndex: 9, turnLimit: 12 }); - const exchanges = await messageRoute.GET(request(`http://localhost:3001/api/agents/message?repo=${encodeURIComponent(repo)}&limit=10`, { token: OPERATOR_TOKEN })); await expect(exchanges.json()).resolves.toMatchObject({ messages: expect.arrayContaining([expect.objectContaining({ id: firstId, conversation: expect.objectContaining({ id: conversationId }) })]) }); }); - it('accepts an early final reply and an operator stop without a delivery side effect on rejected replies', async () => { + it('accepts an early final reply without a delivery side effect on rejected replies', async () => { const repo = `/tmp/o8-agent-final-${Date.now()}`; for (const [agentId, name] of [['final-a', 'Harbor'], ['final-b', 'Maple']]) { expect((await presenceRoute.POST(request('http://localhost:3001/api/agents/presence', { @@ -966,20 +952,7 @@ describe('agent message bus real path', () => { const rejected = await send({ fromAgentId: 'final-a', to: 'Maple', text: 'More?', replyToId: final.body.message!.id }); expect(rejected.status).toBe(409); expect(rejected.body.error?.code).toBe('agent_conversation_closed'); - const stopped = await conversationRoute.POST(request('http://localhost:3001/api/agents/conversation', { - token: OPERATOR_TOKEN, method: 'POST', body: { id: first.body.message!.conversation.id, repo, action: 'close' }, - })); - expect(stopped.status).toBe(200); - const extended = await conversationRoute.POST(request('http://localhost:3001/api/agents/conversation', { - token: OPERATOR_TOKEN, method: 'POST', body: { id: first.body.message!.conversation.id, repo, action: 'extend' }, - })); - await expect(extended.json()).resolves.toMatchObject({ conversation: { turnLimit: 6, remainingTurns: 4, status: 'open' } }); - const operatorStopped = await conversationRoute.POST(request('http://localhost:3001/api/agents/conversation', { - token: OPERATOR_TOKEN, method: 'POST', body: { id: first.body.message!.conversation.id, repo, action: 'close', summary: 'Stop after review.' }, - })); - expect(operatorStopped.status).toBe(200); - const history = await conversationRoute.GET(request(`http://localhost:3001/api/agents/conversation?repo=${encodeURIComponent(repo)}`, { token: OPERATOR_TOKEN })); - await expect(history.json()).resolves.toMatchObject({ conversations: [expect.objectContaining({ status: 'closed', closedReason: 'operator_stop', summary: 'Stop after review.' })] }); + }); it('lets an agent answer an operator handoff in the same conversation', async () => { diff --git a/tests/cloud-forgotten-context-real-path.test.ts b/tests/cloud-forgotten-context-real-path.test.ts index ff28a22c3d..4b76965a32 100644 --- a/tests/cloud-forgotten-context-real-path.test.ts +++ b/tests/cloud-forgotten-context-real-path.test.ts @@ -5,7 +5,6 @@ import { afterAll, beforeAll, expect, it, vi } from 'vitest'; const root = mkdtempSync(join(tmpdir(), 'o8-cloud-forget-')); let db: typeof import('@/lib/db'); let poll: typeof import('@/app/api/cloud/worker-poll/route'); -let status: typeof import('@/app/api/cloud/job-status/route'); let jobs: typeof import('@/lib/cloud/job-queue'); let revision: typeof import('@/lib/cortex/memory-revision'); let headers: { Authorization: string }; @@ -14,7 +13,6 @@ beforeAll(async () => { vi.stubEnv('CORTEX_IDE_DB_PATH', join(root, 'memory.db')); db = await import('@/lib/db'); poll = await import('@/app/api/cloud/worker-poll/route'); - status = await import('@/app/api/cloud/job-status/route'); jobs = await import('@/lib/cloud/job-queue'); revision = await import('@/lib/cortex/memory-revision'); const { createCloudWorkerKey } = await import('@/lib/cloud/worker-auth'); @@ -29,9 +27,6 @@ it('holds and cancels a queued packet prompt forgotten before worker pickup, whi expect(held.status).toBe(409); expect(await held.text()).not.toContain('forgotten queued prompt'); expect(jobs.getJob('team_default', 'old-job')?.status).toBe('cancelled'); - const details = await status.GET(new Request('http://localhost/api/cloud/job-status?jobId=old-job', { headers })); - expect(details.status).toBe(409); - expect(await details.text()).not.toContain('forgotten queued prompt'); jobs.enqueueCloudJob('team_default', 'fresh-job', { cwd: root, prompt: 'current queued prompt', packetId: 'fresh-packet', remoteSource: source, promptMemoryRevision: revision.readMemoryRevision() }); const fresh = await poll.GET(new Request('http://localhost/api/cloud/worker-poll?waitMs=0&workerId=fixture', { headers })); expect(fresh.status).toBe(200); diff --git a/tests/cloud-job-spine-real-path.test.ts b/tests/cloud-job-spine-real-path.test.ts index 7aac663e72..bf75ca4c18 100644 --- a/tests/cloud-job-spine-real-path.test.ts +++ b/tests/cloud-job-spine-real-path.test.ts @@ -20,13 +20,11 @@ const runtimeRoute = await import('@/app/api/runtime/launch/route'); const pollRoute = await import('@/app/api/cloud/worker-poll/route'); const streamRoute = await import('@/app/api/cloud/worker-stream/route'); const controlRoute = await import('@/app/api/cloud/worker-control/route'); -const statusRoute = await import('@/app/api/cloud/job-status/route'); -const workerPanelRoute = await import('@/app/api/panel/cloud-workers/route'); const taskRoute = await import('@/app/api/tasks/[taskId]/route'); const drainRoute = await import('@/app/api/panel/cloud-jobs/drain/route'); const { createCloudWorkerKey, revokeCloudWorkerKey } = await import('@/lib/cloud/worker-auth'); -const { recordCloudWorkerPresence } = await import('@/lib/cloud/worker-presence'); -const { getJob, getLatestSessionJob, getJobDrainStatus, listJobControls, listJobs } = await import('@/lib/cloud/job-queue'); +const { listConnectedCloudWorkers, recordCloudWorkerPresence } = await import('@/lib/cloud/worker-presence'); +const { getJob, readJobEvents, getLatestSessionJob, getJobDrainStatus, listJobControls, listJobs } = await import('@/lib/cloud/job-queue'); const { closeDb, getSqlite } = await import('@/lib/db'); const { getOrCreateWsToken } = await import('@/lib/ws-auth'); const { cloudRuntime } = await import('@/lib/runtimes/cloud-adapter'); @@ -238,13 +236,6 @@ function acknowledgeControl(job: { })); } -function jobStatus(jobId: string) { - return statusRoute.GET(new NextRequest( - `http://localhost/api/cloud/job-status?jobId=${encodeURIComponent(jobId)}&sinceId=0`, - { headers: { authorization: `Bearer ${workerKey.plaintext}` } }, - )); -} - async function startWorkerHttpBridge() { const server = createServer(async (incoming, outgoing) => { try { @@ -302,12 +293,10 @@ describe('durable cloud execution through the runtime launch path', () => { { headers: { authorization: `Bearer ${presenceKey.plaintext}` } }, )); expect(poll.status).toBe(204); - const connected = await workerPanelRoute.GET(); - expect((await connected.json() as { connectedWorkers: Array<{ workerId: string }> }).connectedWorkers) + expect(listConnectedCloudWorkers()) .toEqual(expect.arrayContaining([expect.objectContaining({ workerId: 'presence-fixture' })])); closeDb(); - const afterRestart = await workerPanelRoute.GET(); - expect((await afterRestart.json() as { connectedWorkers: Array<{ workerId: string }> }).connectedWorkers) + expect(listConnectedCloudWorkers()) .toEqual(expect.arrayContaining([expect.objectContaining({ workerId: 'presence-fixture' })])); const crowdedKey = createCloudWorkerKey({ teamId: 'team_default', label: 'bounded presence fixture' }); @@ -321,8 +310,7 @@ describe('durable cloud execution through the runtime launch path', () => { SELECT COUNT(*) AS count FROM cloud_worker_presence WHERE key_id = ? `).get(crowdedKey.record.id) as { count: number }; expect(count.count).toBeLessThanOrEqual(32); - const fairPanel = await workerPanelRoute.GET(); - expect((await fairPanel.json() as { connectedWorkers: Array<{ workerId: string }> }).connectedWorkers) + expect(listConnectedCloudWorkers()) .toEqual(expect.arrayContaining([expect.objectContaining({ workerId: 'presence-fixture' })])); const invalid = await pollRoute.GET(new NextRequest( @@ -332,8 +320,7 @@ describe('durable cloud execution through the runtime launch path', () => { expect(invalid.status).toBe(401); revokeCloudWorkerKey(presenceKey.record.id); revokeCloudWorkerKey(crowdedKey.record.id); - const revoked = await workerPanelRoute.GET(); - expect((await revoked.json() as { connectedWorkers: Array<{ workerId: string }> }).connectedWorkers) + expect(listConnectedCloudWorkers()) .not.toEqual(expect.arrayContaining([expect.objectContaining({ workerId: 'presence-fixture' })])); }); @@ -624,16 +611,14 @@ describe('durable cloud execution through the runtime launch path', () => { teamId: 'team_default', keyId: workerKey.record.id, workerId: 'worker-recovery', nowMs: Date.now() - 61_000, }); - const beforeAcceptedEvent = await workerPanelRoute.GET(); - expect((await beforeAcceptedEvent.json() as { connectedWorkers: Array<{ workerId: string }> }).connectedWorkers) + expect(listConnectedCloudWorkers()) .not.toEqual(expect.arrayContaining([expect.objectContaining({ workerId: 'worker-recovery' })])); const rejectedPresence = await workerStream({ jobId, workerId: 'forged-presence', leaseToken: firstClaim?.leaseToken, type: 'heartbeat', payload: { status: 'running' }, }); expect(rejectedPresence.status).toBe(409); - const afterRejectedEvent = await workerPanelRoute.GET(); - expect((await afterRejectedEvent.json() as { connectedWorkers: Array<{ workerId: string }> }).connectedWorkers) + expect(listConnectedCloudWorkers()) .not.toEqual(expect.arrayContaining([expect.objectContaining({ workerId: 'forged-presence' })])); const output = await workerStream({ @@ -644,8 +629,7 @@ describe('durable cloud execution through the runtime launch path', () => { payload: { text: 'durable worker output' }, }); expect(output.status).toBe(200); - const afterAcceptedEvent = await workerPanelRoute.GET(); - expect((await afterAcceptedEvent.json() as { connectedWorkers: Array<{ workerId: string }> }).connectedWorkers) + expect(listConnectedCloudWorkers()) .toEqual(expect.arrayContaining([expect.objectContaining({ workerId: 'worker-recovery' })])); const diff = await workerStream({ jobId, @@ -704,20 +688,6 @@ describe('durable cloud execution through the runtime launch path', () => { additions: 4, deletions: 1, }]); - const status = await jobStatus(jobId); - expect(status.status).toBe(200); - const statusBody = await status.json(); - expect(JSON.stringify(statusBody)).not.toContain(repoPath); - expect(statusBody).toMatchObject({ - job: { id: jobId, status: 'completed' }, - metrics: { - claimCount: 2, - leaseRecoveryCount: 1, - executionAttempts: 0, - queueWaitMs: expect.any(Number), - terminalLatencyMs: expect.any(Number), - }, - }); }, 60_000); it('parks real failures and resolves steer, abort, and restart-drain races deterministically', async () => { @@ -969,15 +939,7 @@ describe('durable cloud execution through the runtime launch path', () => { '--git-dir', bareRemotePath, 'rev-parse', `refs/heads/o8/worker-process-${index}`, ], { encoding: 'utf8' }).trim(); closeDb(); - const status = await jobStatus(jobId); - expect(status.status).toBe(200); - const receipt = await status.json() as { - job: { launch: Record }; - events: Array<{ type: string; payload: { commitSha?: string; checkout?: { cacheHit: boolean; durationMs: number } } }>; - }; - expect(JSON.stringify(receipt.job.launch)).not.toContain(repoPath); - expect(JSON.stringify(receipt.job.launch)).not.toContain(realpathSync.native(repoPath)); - expect(receipt.events).toEqual(expect.arrayContaining([ + expect(readJobEvents('team_default', jobId, 0)).toEqual(expect.arrayContaining([ expect.objectContaining({ type: 'completed', payload: expect.objectContaining({ commitSha: pushedSha }) }), expect.objectContaining({ type: 'chunk', payload: expect.objectContaining({ checkout: expect.objectContaining({ cacheHit: index === 2, durationMs: expect.any(Number) }), @@ -1016,10 +978,7 @@ describe('durable cloud execution through the runtime launch path', () => { executionAttempts: 3, lastError: expect.stringContaining('git push failed'), }); - const rejectedEvents = (await jobStatus(rejectedId).then((status) => status.json())) as { - events: Array<{ type: string }>; - }; - expect(rejectedEvents.events.some((event) => event.type === 'completed')).toBe(false); + expect(readJobEvents('team_default', rejectedId, 0).some(event => event.type === 'completed')).toBe(false); expect(() => execFileSync('git', [ '--git-dir', bareRemotePath, 'rev-parse', '--verify', 'refs/heads/o8/worker-process-reject', ], { stdio: 'pipe' })).toThrow(); diff --git a/tests/cold-start-runtime-spawn-routes.test.ts b/tests/cold-start-runtime-spawn-routes.test.ts index 40d0a276a5..796bf28467 100644 --- a/tests/cold-start-runtime-spawn-routes.test.ts +++ b/tests/cold-start-runtime-spawn-routes.test.ts @@ -3,7 +3,6 @@ import { mkdtempSync, rmSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { NextRequest } from 'next/server'; import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; const spawnMock = vi.hoisted(() => vi.fn()); @@ -33,7 +32,6 @@ delete process.env.O8_DATA_DIR; const { CliNotFoundError } = await import('@/lib/runtimes/shared/cli-resolver'); const cliProxyRoute = await import('@/app/api/v2/proxy/cli/route'); -const codexSendRoute = await import('@/app/api/codex/send/route'); beforeEach(() => { spawnMock.mockReset(); @@ -67,37 +65,6 @@ describe('cold-start runtime spawn routes', () => { expect(spawnMock).not.toHaveBeenCalled(); }); - it('returns an install action instead of a raw spawn ENOENT from workspace Codex chat', async () => { - const response = await codexSendRoute.POST(new NextRequest('http://localhost/api/codex/send', { - method: 'POST', - body: JSON.stringify({ message: 'hello', cwd: repoPath }), - })); - const payload = await response.json() as { code?: string; error?: string }; - - expect(response.status).toBe(503); - expect(payload.code).toBe('runtime_not_installed'); - expect(payload.error).toContain('[runtime] Codex is not installed'); - expect(payload.error).not.toContain('ENOENT'); - expect(spawnMock).not.toHaveBeenCalled(); - }); - - it('names a vanished workspace before attempting CLI resolution', async () => { - const missingPath = path.join(dataDir, 'repo-was-deleted'); - const response = await codexSendRoute.POST(new NextRequest('http://localhost/api/codex/send', { - method: 'POST', - body: JSON.stringify({ message: 'hello', cwd: missingPath }), - })); - const payload = await response.json() as { code?: string; error?: string }; - - expect(response.status).toBe(400); - expect(payload.code).toBe('repo_unavailable'); - expect(payload.error).toContain(missingPath); - expect(payload.error).toContain('Repository folder not found'); - expect(payload.error).not.toContain('ENOENT'); - expect(resolveCliMock).not.toHaveBeenCalled(); - expect(spawnMock).not.toHaveBeenCalled(); - }); - it('refuses an unregistered repo path instead of silently spawning from the server cwd', async () => { const response = await cliProxyRoute.POST(new Request('http://localhost/api/v2/proxy/cli', { method: 'POST', diff --git a/tests/crash-reports-toggle.test.ts b/tests/crash-reports-toggle.test.ts index 85ad8e4cab..1ca876dea0 100644 --- a/tests/crash-reports-toggle.test.ts +++ b/tests/crash-reports-toggle.test.ts @@ -8,7 +8,7 @@ import { describe, expect, it } from 'vitest'; * Real-path test (reachability rule): drive the ACTUAL operator-defaults route * with a constructed Request and assert the observable effect the three Sentry * layers depend on — resolveCrashReportsEnabledSync() (the exact function the - * node beforeSend + the /api/telemetry/config resolver read, and the same + * node beforeSend read, and the same * ~/.o8/operator-defaults.json file the Rust before_send re-reads) reflects the * persisted toggle. Testing updateOperatorDefaults() in isolation would prove * the writer works but not that a real POST reaches it (the evaporation class). diff --git a/tests/e2e/packet-identity.spec.ts b/tests/e2e/packet-identity.spec.ts index 6805e8fc9f..8e47de82c4 100644 --- a/tests/e2e/packet-identity.spec.ts +++ b/tests/e2e/packet-identity.spec.ts @@ -42,22 +42,6 @@ async function stubDesktopPacketApis(page: Page) { await fulfillMissionState(route, missionState); }); - const sseBody = [ - 'data: {"type":"delta","text":"Packet received."}', - 'data: {"type":"done","text":"Packet received."}', - '', - ].join('\n'); - - for (const path of ['**/api/codex/send', '**/api/claude-code/send']) { - await page.route(path, async (route) => { - await route.fulfill({ - status: 200, - headers: { 'content-type': 'text/event-stream' }, - body: sseBody, - }); - }); - } - for (const path of ['**/api/codex/transcript**', '**/api/claude-code/transcript**']) { await page.route(path, async (route) => { await route.fulfill({ diff --git a/tests/fixtures/forgotten-correction.ts b/tests/fixtures/forgotten-correction.ts new file mode 100644 index 0000000000..72794bdd3d --- /dev/null +++ b/tests/fixtures/forgotten-correction.ts @@ -0,0 +1,9 @@ +import type Database from 'better-sqlite3'; + +// Load an exclusion in the format written by older installations. +export async function seedForgottenCorrection(db: Database.Database, id: string) { + const { advanceMemoryRevision } = await import('@/lib/cortex/memory-revision'); + db.exec('CREATE TABLE IF NOT EXISTS forgotten_operator_corrections (id TEXT PRIMARY KEY, forgotten_at TEXT NOT NULL)'); + db.prepare('INSERT INTO forgotten_operator_corrections (id, forgotten_at) VALUES (?, ?)').run(id, '2026-01-01T00:00:00Z'); + advanceMemoryRevision(db); +} diff --git a/tests/forget-corrections-real-path.test.ts b/tests/forget-corrections-real-path.test.ts index 2ec4c7fac5..2a550bfa86 100644 --- a/tests/forget-corrections-real-path.test.ts +++ b/tests/forget-corrections-real-path.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { NextRequest } from 'next/server'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { seedForgottenCorrection } from './fixtures/forgotten-correction'; import type { OrchestratorPacket } from '@/lib/orchestrator/types'; vi.mock('@/lib/realtime/publisher', async importOriginal => ({ @@ -27,7 +28,6 @@ let approvalRoute: typeof import('@/app/api/panel/approvals/route'); let prompt: typeof import('@/lib/orchestrator/packet-prompt'); let retrieve: typeof import('@/lib/cortex/qa/retrieve'); let recall: typeof import('@/lib/cortex/qa/recall'); -let route: { GET(request: NextRequest): Promise; DELETE(request: NextRequest): Promise }; beforeAll(async () => { vi.stubEnv('O8_DATA_DIR', root); vi.stubEnv('CORTEX_IDE_DATA_DIR', root); @@ -42,16 +42,6 @@ beforeAll(async () => { }, 120_000); // Allow cold transformation of the production route/prompt graph; test deadlines stay unchanged. afterAll(() => { db?.closeDb(); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }); }); -async function loadRoute() { - const name = '@/app/api/cortex/operator-corrections/route'; - route = await import(name); -} -function request(method = 'GET', body?: object, token = operator, query = '') { - return new NextRequest(`http://localhost/api/cortex/operator-corrections${query}`, { - method, headers: { host: 'localhost', authorization: `Bearer ${token}`, 'content-type': 'application/json' }, - ...(body ? { body: JSON.stringify({ projectId: 'default', ...body }) } : {}), - }); -} function packet(id: string) { return { id, workspaceTargetPath: repo, referenceLabel: id, title: 'Parser correction', summary: '', status: 'draft', queueState: 'queued', runtime: 'codex', dependencyPacketIds: [], dependencyLabels: [], @@ -124,7 +114,7 @@ describe('selective correction recall through operator routes and persisted cons expect(await prompt.buildPacketPrompt(packet(packetId), [])).not.toContain(summary); }); - it('inspects and forgets a route-recorded rejection, invalidating recall while retaining its audit and neighbors after reopen', async () => { + it('honors a stored rejection exclusion in recall, prompts and the audit after reopen', async () => { const removed = await rejection('remove-feedback'); const kept = await rejection('keep-feedback'); expect(await brainReasons()).toContain(removed.reason); const relay = await import('@/lib/orchestrator/context-relay'); @@ -133,14 +123,11 @@ describe('selective correction recall through operator routes and persisted cons const dependent = { ...packet('correction-dependent'), dependencyPacketIds: ['remove-feedback'] }; expect(await prompt.buildPacketPrompt(dependent, [packet('remove-feedback'), dependent])).toContain(removed.reason); expect(await prompt.buildPacketPrompt(packet('remove-feedback'), [])).toContain(removed.reason); - await loadRoute(); - const listed = await (await route.GET(request())).json(); - expect(listed.corrections.map((c: { id: string }) => c.id)).toContain(removed.id); const rows = [{ citation: { kind: 'correction', rowId: removed.rowId, table: 'approvals' }, fields: { body: removed.reason } }] as import('@/lib/cortex/qa/types').TypedRow[]; recall.seedRecallCacheForTests({ question: 'cached feedback', repoPath: repo, rows, vector: [1, 0] }); recall.setRecallDependenciesForTests({ hasEmbedding: () => true, assertSpend: async () => {}, classify: async () => ({ class: 'A', bm25Variants: ['feedback'] }), retrieve: async () => [], embed: async () => [1, 0] }); expect((await recall.recallRows('cached feedback', repo)).rows).toHaveLength(1); - expect((await route.DELETE(request('DELETE', { id: removed.id }))).status).toBe(200); + await seedForgottenCorrection(db.getSqlite(), removed.id); expect((await recall.recallRows('cached feedback', repo)).rows).toEqual([]); expect(approvals.getApproval(removed.rowId)?.resolution?.note).toBe(removed.reason); db.closeDb(); db.getSqlite(); @@ -148,67 +135,21 @@ describe('selective correction recall through operator routes and persisted cons expect(await prompt.buildPacketPrompt(dependent, [packet('remove-feedback'), dependent])).not.toContain(removed.reason); expect(await brainReasons()).toContain(kept.reason); expect(await prompt.buildPacketPrompt(packet('remove-feedback'), [])).not.toContain(removed.reason); - expect((await (await route.GET(request())).json()).corrections.map((c: { id: string }) => c.id)).toEqual([kept.id]); - expect((await route.DELETE(request('DELETE', { id: removed.id }))).status).toBe(404); }); - it('forgets one persisted steer without erasing its terminal audit or a neighboring steer', async () => { - await loadRoute(); + it('honors a stored steer exclusion without erasing its terminal audit or a neighboring steer', async () => { const lane = lanes.createLane({ repoPath: repo, branch: 'fixture', runtime: 'codex', packetId: 'steer-packet' }); const events = await import('@/lib/lane/events'); const removed = events.recordLaneEvent(lane.id, 'steered_packet', 'orchestrator', { packetId: 'steer-packet', source: 'operator', message: 'remove steer canary' }); const kept = events.recordLaneEvent(lane.id, 'steered_packet', 'orchestrator', { packetId: 'steer-packet', source: 'operator', message: 'keep steer canary' }); expect(await prompt.buildPacketPrompt(packet('steer-packet'), [])).toContain('remove steer canary'); - expect((await route.DELETE(request('DELETE', { id: `steer:${removed.id}` }))).status).toBe(200); + await seedForgottenCorrection(db.getSqlite(), `steer:${removed.id}`); expect(await prompt.buildPacketPrompt(packet('steer-packet'), [])).not.toContain('remove steer canary'); expect(await prompt.buildPacketPrompt(packet('steer-packet'), [])).toContain('keep steer canary'); expect(lanes.getLaneEvents(lane.id, 10).map(e => e.id)).toEqual(expect.arrayContaining([removed.id, kept.id])); expect(await brainReasons()).not.toContain('remove steer canary'); }); - it('paginates and searches the whole retained ledger, beyond the contextual retrieval scan and across repository scopes', async () => { - await loadRoute(); - const lane = lanes.createLane({ repoPath: repo, branch: 'fixture', runtime: 'codex', packetId: 'history' }); - const events = await import('@/lib/lane/events'); - const oldest = events.recordLaneEvent(lane.id, 'steered_packet', 'orchestrator', { packetId: 'history', source: 'operator', message: 'old retained needle' }); - for (let index = 0; index < 205; index++) events.recordLaneEvent(lane.id, 'steered_packet', 'orchestrator', { source: 'operator', message: `newer correction ${index}` }); - const query = '?limit=50&repoPath=' + encodeURIComponent(repo); - const first = await (await route.GET(request('GET', undefined, operator, query))).json(); - const second = await (await route.GET(request('GET', undefined, operator, query + '&offset=50'))).json(); - expect(first.corrections).toHaveLength(50); expect(first.hasMore).toBe(true); - expect(second.corrections).toHaveLength(50); - expect(new Set([...first.corrections, ...second.corrections].map(c => c.id)).size).toBe(100); - const search = await (await route.GET(request('GET', undefined, operator, query + '&query=old%20retained'))).json(); - expect(search.corrections.map((c: { id: string }) => c.id)).toEqual([`steer:${oldest.id}`]); - const foreign = await (await route.GET(request('GET', undefined, operator, '?repoPath=' + encodeURIComponent(join(root, 'other'))))).json(); - expect(foreign.corrections).toEqual([]); - }); - - it('refuses anonymous, worker and device reads/deletes at the handler and retains data on invalid selection', async () => { - await loadRoute(); - const worker = (await import('@/lib/auth/worker-token')).getOrCreateLocalWorkerToken(); - for (const token of ['invalid', worker, device]) for (const method of ['GET', 'DELETE'] as const) { - expect((await route[method](request(method, method === 'DELETE' ? { id: 'steer:missing' } : undefined, token))).status).toBe(403); - } - for (const id of ['../approval', 'unqualified', 'approval:']) expect((await route.DELETE(request('DELETE', { id }))).status).toBe(400); - expect((await route.DELETE(request('DELETE', { id: 'approval:missing' }))).status).toBe(404); - }); - - it('rolls back the recall exclusion and revision if persistence fails', async () => { - await loadRoute(); - const primed = await rejection('prime-forget-ledger'); - expect((await route.DELETE(request('DELETE', { id: primed.id }))).status).toBe(200); - const selected = await rejection('rollback-feedback'); - const { readMemoryRevision } = await import('@/lib/cortex/memory-revision'); - const revision = readMemoryRevision(); - db.getSqlite().exec("CREATE TRIGGER refuse_correction_forget BEFORE INSERT ON forgotten_operator_corrections BEGIN SELECT RAISE(ABORT, 'fixture refusal'); END"); - try { - expect((await route.DELETE(request('DELETE', { id: selected.id }))).status).toBe(500); - expect(await brainReasons()).toContain(selected.reason); - expect(readMemoryRevision()).toBe(revision); - } finally { db.getSqlite().exec('DROP TRIGGER refuse_correction_forget'); } - }); - it('exposes older and expired outcomes in a bounded inventory and deletes with the listed project identity', async () => { const outcomes = await import('@/app/api/cortex/recent-outcomes/route'); const insert = db.getSqlite().prepare(`INSERT INTO session_outcomes diff --git a/tests/forget-project-matrix-real-path.test.ts b/tests/forget-project-matrix-real-path.test.ts index 7a1f4c76f3..146b04a20a 100644 --- a/tests/forget-project-matrix-real-path.test.ts +++ b/tests/forget-project-matrix-real-path.test.ts @@ -6,6 +6,7 @@ import { join } from 'node:path'; import { NextRequest } from 'next/server'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import type { OrchestratorPacket } from '@/lib/orchestrator/types'; +import { seedForgottenCorrection } from './fixtures/forgotten-correction'; import type { PacketContext } from '@/lib/orchestrator/types'; const inventoryState = vi.hoisted(() => ({ agents: [] as import('@/lib/fleet/types').AgentSummary[] })); @@ -29,7 +30,7 @@ const projects = [ ]; const cases = projects.flatMap(project => [0, 1].map(sibling => ({ ...project, sibling }))); let db: typeof import('@/lib/db'); -let corrections: typeof import('@/app/api/cortex/operator-corrections/route'); +let readOperatorCorrections: typeof import('@/lib/cortex/operator-corrections').readOperatorCorrections; let outcomes: typeof import('@/app/api/cortex/recent-outcomes/route'); let relay: typeof import('@/lib/orchestrator/context-relay'); let projectsModule: typeof import('@/lib/repos/projects'); @@ -52,7 +53,7 @@ function request(endpoint: string, projectId: string, repoPath: string, method = } async function inventory(projectId: string, repoPath: string) { return { - corrections: (await (await corrections.GET(request('operator-corrections', projectId, repoPath))).json()).corrections, + corrections: readOperatorCorrections({ projectId, repoPaths: [repoPath], limit: 100 }), outcomes: (await (await outcomes.GET(request('recent-outcomes', projectId, repoPath))).json()).outcomes, } as { corrections: Array<{ id: string; projectId: string }>; outcomes: Array<{ id: string; projectId: string; summary: string }> }; } @@ -67,7 +68,7 @@ beforeAll(async () => { })); db = await import('@/lib/db'); projectsModule = await import('@/lib/repos/projects'); - corrections = await import('@/app/api/cortex/operator-corrections/route'); + ({ readOperatorCorrections } = await import('@/lib/cortex/operator-corrections')); outcomes = await import('@/app/api/cortex/recent-outcomes/route'); relay = await import('@/lib/orchestrator/context-relay'); ({ buildPacketPrompt } = await import('@/lib/orchestrator/packet-prompt')); @@ -148,24 +149,18 @@ describe.each(cases.map((value, index) => ({ ...value, index })))('$projectId, f expect.soft(pairs[index].contexts[0].sourceOutcomeId).not.toBe(pairs[index].contexts[1].sourceOutcomeId); }); - it('forget: cross-project IDs are 404 and leave recall unchanged; own IDs are 200', async () => { + it('outcome deletion is project-scoped and stored correction exclusions load', async () => { const pair = pairs[index], selected = pair.contexts[sibling]; if (projectId !== 'matrix-a') { const { readMemoryRevision } = await import('@/lib/cortex/memory-revision'); const revision = readMemoryRevision(); - for (const id of pair.corrections[sibling]) { - expect.soft((await corrections.DELETE(request('operator-corrections', 'matrix-a', sharedRepo, 'DELETE', { id, projectId: 'matrix-a' }))).status).toBe(404); - } expect.soft((await outcomes.DELETE(request('recent-outcomes', 'matrix-a', sharedRepo, 'DELETE', { id: selected.sourceOutcomeId, projectId: 'matrix-a', repoPath: sharedRepo, }))).status).toBe(404); expect.soft(readMemoryRevision()).toBe(revision); - expect.soft((await corrections.DELETE(request('operator-corrections', 'matrix-a', sharedRepo, 'DELETE', { - id: pair.corrections[sibling][0], projectId, - }))).status).toBe(404); } for (const id of pair.corrections[sibling]) { - expect.soft((await corrections.DELETE(request('operator-corrections', projectId, repoPath, 'DELETE', { id, projectId }))).status).toBe(200); + await seedForgottenCorrection(db.getSqlite(), id); } expect.soft((await outcomes.DELETE(request('recent-outcomes', projectId, repoPath, 'DELETE', { id: selected.sourceOutcomeId, repoPath, projectId, @@ -220,14 +215,3 @@ describe.each(cases.map((value, index) => ({ ...value, index })))('$projectId, f await projectsModule.setActiveProject('matrix-a'); }, 45_000); }); - -it('requires explicit correction project identity and refuses conflicting project selectors', async () => { - const pair = pairs[0]; - const missingProject = new NextRequest('http://localhost/api/cortex/operator-corrections', { - method: 'DELETE', headers: { authorization: `Bearer ${token}` }, body: JSON.stringify({ id: pair.corrections[1][0] }), - }); - expect((await corrections.DELETE(missingProject)).status).toBe(400); - expect((await corrections.DELETE(request('operator-corrections', 'matrix-a', sharedRepo, 'DELETE', { - id: pair.corrections[1][0], projectId: 'matrix-b', - }))).status).toBe(404); -}); diff --git a/tests/hosting-publication-real-path.test.ts b/tests/hosting-publication-real-path.test.ts index 0f0ad98560..a8e07aaac3 100644 --- a/tests/hosting-publication-real-path.test.ts +++ b/tests/hosting-publication-real-path.test.ts @@ -9,7 +9,6 @@ import { getOrCreateWsToken } from '@/lib/ws-auth'; import { githubProvider } from '@/lib/git-providers/github'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { POST as publish } from '@/app/api/panel/prs/[number]/route'; -import { POST as legacy } from '@/app/api/panel/pr/review/route'; const host = vi.hoisted(() => ({ installation: 9000, head: 'a'.repeat(40), merged: false, queue: false, queued: false, closed: false, failRead: false, failStateRead: false, holdFinalRead: null as (() => Promise) | null, holdMutation: null as (() => Promise) | null, holdStateRead: null as (() => Promise) | null, lost: false, lostBeforeApply: false, raceHead: false, internalError: false, auto: false, failCheck: false, missingCheck: false, mutations: [] as Array>, reads: 0 })); @@ -18,14 +17,14 @@ vi.mock('@/lib/github-broker/managed', () => ({ readManagedGithubToken: () => ({ const approved = 'a'.repeat(40); const mergedSha = 'c'.repeat(40); let number = 7000; -const requestFor = (old = false, extra: Record = {}, token = getOrCreateWsToken()) => { +const requestFor = (extra: Record = {}, token = getOrCreateWsToken()) => { const body = { repo: 'example/publication', number, action: 'merge', mergeMethod: 'squash', commitSha: approved, ...extra }; - return new NextRequest(`http://localhost${old ? '/api/panel/pr/review' : `/api/panel/prs/${number}`}`, { method: 'POST', headers: { host: 'localhost', authorization: `Bearer ${token}` }, body: JSON.stringify(body) }); + return new NextRequest(`http://localhost/api/panel/prs/${number}`, { method: 'POST', headers: { host: 'localhost', authorization: `Bearer ${token}` }, body: JSON.stringify(body) }); }; -const post = (old = false, extra: Record = {}) => { +const post = (extra: Record = {}) => { const body = { repo: 'example/publication', number, action: 'merge', mergeMethod: 'squash', commitSha: approved, ...extra }; const request = new Request(`http://localhost/api/panel/prs/${number}`, { method: 'POST', headers: { authorization: `Bearer ${getOrCreateWsToken()}` }, body: JSON.stringify(body) }); - return old ? legacy(request) : publish(request, { params: Promise.resolve({ number: String(number) }) }); + return publish(request, { params: Promise.resolve({ number: String(number) }) }); }; beforeEach(() => { number++; host.installation++; Object.assign(host, { head: approved, merged: false, queue: false, queued: false, lost: false, lostBeforeApply: false, raceHead: false, internalError: false, auto: false, failCheck: false, missingCheck: false, closed: false, failRead: false, failStateRead: false, holdFinalRead: null, holdMutation: null, holdStateRead: null, mutations: [], reads: 0 }); @@ -67,14 +66,14 @@ afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); }); it('installs publication tables at database boot before a publication', () => { expect(getSqlite().prepare("SELECT name FROM sqlite_master WHERE name LIKE 'github_publication_%' ORDER BY name").all()).toEqual([{ name: 'github_publication_events' }, { name: 'github_publication_intents' }]); }); -it('legacy refuses without an approved SHA before any mutation', async () => { - const response = await post(true, { commitSha: undefined }); +it('refuses without an approved SHA before any mutation', async () => { + const response = await post({ commitSha: undefined }); expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({ code: 'approved_head_required', message: 'The approved head SHA is required. Send it as commitSha.' }); + expect(await response.json()).toMatchObject({ error: 'A reviewed commit and merge method are required' }); expect(host.mutations).toHaveLength(0); }); -it.each([false, true])('approved head publishes through route, legacy=%s', async old => { - expect((await post(old)).status).toBe(200); +it('publishes an approved head through the numbered PR route', async () => { + expect((await post()).status).toBe(200); expect(host.mutations).toHaveLength(1); expect(host.mutations[0].sha).toBe(approved); }); @@ -100,7 +99,7 @@ it('reconciles a lost merge response before retry, without double publication', }); it('enqueues with a host head pin and reports queued separately', async () => { host.queue = true; - const response = await post(false, { action: 'enable-auto-merge' }); + const response = await post({ action: 'enable-auto-merge' }); expect(response.status).toBe(200); expect(host.mutations[0].variables).toMatchObject({ input: { expectedHeadOid: approved } }); expect(await response.json()).toMatchObject({ publication: { status: 'queued', mergedSha: null } }); @@ -130,22 +129,22 @@ it('the GitHub provider returns the same durable queue outcome', async () => { expect(host.mutations[0].variables).toMatchObject({ input: { expectedHeadOid: approved } }); }); it('concurrent route confirmations publish only once', async () => { - const responses = await Promise.all([post(), post(true)]); + const responses = await Promise.all([post(), post()]); expect(responses.map(r => r.status).every(s => s === 200 || s === 202)).toBe(true); expect(host.mutations).toHaveLength(1); }); it('records auto-merge enabled separately and pins its host mutation', async () => { - const response = await post(false, { action: 'enable-auto-merge' }); + const response = await post({ action: 'enable-auto-merge' }); expect(response.status).toBe(200); expect(await response.json()).toMatchObject({ publication: { status: 'auto_merge_enabled', approvedSha: approved, mergedSha: null } }); expect(host.mutations[0].variables).toMatchObject({ input: { expectedHeadOid: approved } }); }); -it('middleware still refuses a worker before either hosting route', async () => { +it('middleware still refuses a worker before the hosting route', async () => { const { panelGateMiddleware } = await import('@/middleware'); const { mintPacketWorkerToken } = await import('@/lib/auth/packet-worker-token'); const workerToken = mintPacketWorkerToken(`worker-${number}`); try { - for (const path of [`/api/panel/prs/${number}`, '/api/panel/pr/review']) { + for (const path of [`/api/panel/prs/${number}`]) { const request = new NextRequest(`http://localhost${path}`, { method: 'POST', headers: { authorization: `Bearer ${workerToken}`, host: 'localhost' }, body: '{}' }); expect(panelGateMiddleware(request).status).toBe(403); } @@ -177,8 +176,8 @@ it('retains a persisted packet hold through the numbered PR route', async () => }); it('reconciles a lost queue acknowledgement without enqueuing twice', async () => { host.queue = true; host.lost = true; - expect((await post(false, { action: 'enable-auto-merge' })).status).toBe(202); - const response = await post(false, { action: 'enable-auto-merge' }); + expect((await post({ action: 'enable-auto-merge' })).status).toBe(202); + const response = await post({ action: 'enable-auto-merge' }); expect(response.status).toBe(200); expect(await response.json()).toMatchObject({ publication: { status: 'queued', approvedSha: approved, mergedSha: null } }); expect(host.mutations).toHaveLength(1); @@ -186,7 +185,7 @@ it('reconciles a lost queue acknowledgement without enqueuing twice', async () = it.each([false, true])('refuses a definite GraphQL head mismatch, queue=%s', async queue => { host.queue = queue; host.raceHead = true; - const response = await post(false, { action: 'enable-auto-merge' }); + const response = await post({ action: 'enable-auto-merge' }); expect(response.status).toBe(409); expect(host.merged).toBe(false); expect(host.mutations).toHaveLength(1); @@ -195,8 +194,8 @@ it.each([false, true])('refuses a definite GraphQL head mismatch, queue=%s', asy it('keeps an indeterminate GraphQL execution error unknown without retrying the mutation', async () => { host.internalError = true; - expect((await post(false, { action: 'enable-auto-merge' })).status).toBe(202); - expect((await post(false, { action: 'enable-auto-merge' })).status).toBe(202); + expect((await post({ action: 'enable-auto-merge' })).status).toBe(202); + expect((await post({ action: 'enable-auto-merge' })).status).toBe(202); expect(host.mutations).toHaveLength(1); }); @@ -210,11 +209,11 @@ it('settles an unknown publication after the head moves and permits a fresh deci host.lostBeforeApply = true; expect((await post()).status).toBe(202); host.head = 'd'.repeat(40); - expect((await post(false, { commitSha: host.head })).status).toBe(409); + expect((await post({ commitSha: host.head })).status).toBe(409); expect(receipt()).toMatchObject({ status: 'refused', reason: expect.stringContaining('head changed') }); expect(host.mutations).toHaveLength(1); host.lostBeforeApply = false; - expect((await post(false, { commitSha: host.head })).status).toBe(200); + expect((await post({ commitSha: host.head })).status).toBe(200); expect(host.mutations).toHaveLength(2); }); it('settles a request that did not reach the host only after the bounded window', async () => { @@ -231,9 +230,9 @@ it('settles a request that did not reach the host only after the bounded window' }); it.each([false, true])('settles confirmed removal of deferred publication, queue=%s', async queue => { host.queue = queue; - expect((await post(false, { action: 'enable-auto-merge' })).status).toBe(200); + expect((await post({ action: 'enable-auto-merge' })).status).toBe(200); host.auto = false; host.queued = false; - expect((await post(false, { action: 'enable-auto-merge' })).status).toBe(409); + expect((await post({ action: 'enable-auto-merge' })).status).toBe(409); expect(receipt().status).toBe(queue ? 'refused' : 'disabled'); expect(host.mutations).toHaveLength(1); }); @@ -247,43 +246,38 @@ it('settles a closed unmerged pull request without another mutation', async () = }); it.each(['unknown', 'queued', 'auto_merge_enabled'] as const)('failed reconciliation reads preserve %s evidence', async status => { host.queue = status === 'queued'; host.lostBeforeApply = status === 'unknown'; - await post(false, { action: status === 'unknown' ? 'merge' : 'enable-auto-merge' }); + await post({ action: status === 'unknown' ? 'merge' : 'enable-auto-merge' }); const before = receipt(); host.failRead = status === 'unknown'; host.failStateRead = status !== 'unknown'; - await post(false, { action: status === 'unknown' ? 'merge' : 'enable-auto-merge' }); + await post({ action: status === 'unknown' ? 'merge' : 'enable-auto-merge' }); expect(receipt()).toEqual(before); expect(host.mutations).toHaveLength(1); }); it.each([false, true])('admits missing required checks as pending for auto-merge/queue, queue=%s', async queue => { host.queue = queue; host.missingCheck = true; - const response = await post(false, { action: queue ? 'merge' : 'enable-auto-merge' }); + const response = await post({ action: queue ? 'merge' : 'enable-auto-merge' }); expect(response.status).toBe(200); expect(host.mutations).toHaveLength(1); expect(await response.json()).toMatchObject({ publication: { status: queue ? 'queued' : 'auto_merge_enabled' } }); }); -it.each([false, true])('real operator client records operator on both hosting routes, legacy=%s', async old => { +it('records the real operator principal on the numbered PR route', async () => { const { panelGateMiddleware } = await import('@/middleware'); - const request = requestFor(old, { principal: 'anonymous' }); + const request = requestFor({ principal: 'anonymous' }); expect(panelGateMiddleware(request).headers.get('x-middleware-next')).toBe('1'); - const response = old ? await legacy(request) : await publish(request, { params: Promise.resolve({ number: String(number) }) }); + const response = await publish(request, { params: Promise.resolve({ number: String(number) }) }); expect(response.status).toBe(200); expect(await response.json()).toMatchObject({ publication: { authorizingPrincipal: 'operator' } }); }); -it.each([false, true])('preserves device bearer hosting access and evidence, legacy=%s', async old => { +it('refuses a device bearer at the numbered PR route', async () => { const { panelGateMiddleware } = await import('@/middleware'); const token = 'hosting-device-fixture-0123456789'; writeFileSync(join(getDataDir(), 'mobile-device-tokens'), createHash('sha256').update(token).digest('hex') + '\n'); - const request = requestFor(old, { principal: 'operator' }, token); - const gate = panelGateMiddleware(request); - if (!old) { expect(gate.status).toBe(403); expect(host.mutations).toHaveLength(0); return; } - expect(gate.headers.get('x-middleware-next')).toBe('1'); - const response = await legacy(request); - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ publication: { authorizingPrincipal: 'device', approvedSha: approved } }); - expect(host.mutations[0].sha).toBe(approved); + const request = requestFor({ principal: 'operator' }, token); + expect(panelGateMiddleware(request).status).toBe(403); + expect(host.mutations).toHaveLength(0); }); -it.each([false, true])('normalizes caller SHA before gating and publication, legacy=%s', async old => { - const response = await post(old, { commitSha: approved.toUpperCase() }); +it('normalizes caller SHA before gating and publication', async () => { + const response = await post({ commitSha: approved.toUpperCase() }); expect(response.status).toBe(200); expect(host.mutations[0].sha).toBe(approved); expect(receipt().approvedSha).toBe(approved); @@ -294,7 +288,7 @@ it('records the queue method rather than a caller-selected method', async () => expect(receipt().method).toBe('queue'); }); it('does not report an explicit merge as accepted when auto-merge is in effect', async () => { - expect((await post(false, { action: 'enable-auto-merge' })).status).toBe(200); + expect((await post({ action: 'enable-auto-merge' })).status).toBe(200); const response = await post(); expect(response.status).toBe(409); expect(await response.json()).toMatchObject({ publication: { status: 'auto_merge_enabled', action: 'enable-auto-merge' }, error: expect.stringContaining('explicit merge was not sent') }); @@ -313,7 +307,7 @@ it('checks the winning claim SHA when concurrent callers approved different head await ready; try { host.head = 'd'.repeat(40); - expect((await post(false, { commitSha: host.head })).status).toBe(200); + expect((await post({ commitSha: host.head })).status).toBe(200); } finally { release(); } const response = await first; expect(response.status).toBe(409); @@ -329,8 +323,8 @@ it('a late response cannot return a newer head publication as its own success', await ready; try { host.head = 'd'.repeat(40); - expect((await post(false, { commitSha: host.head })).status).toBe(409); - expect((await post(false, { commitSha: host.head })).status).toBe(200); + expect((await post({ commitSha: host.head })).status).toBe(409); + expect((await post({ commitSha: host.head })).status).toBe(200); } finally { release(); } expect((await first).status).toBe(409); expect(host.mutations).toHaveLength(2); @@ -342,12 +336,12 @@ it('late reconciliation cannot return a newer head publication as success', asyn const ready = new Promise(resolve => { entered = resolve; }); const resumed = new Promise(resolve => { release = resolve; }); host.holdStateRead = async () => { entered(); await resumed; }; - const first = post(false, { action: 'enable-auto-merge' }); + const first = post({ action: 'enable-auto-merge' }); await ready; try { host.head = 'd'.repeat(40); host.auto = false; - expect((await post(false, { commitSha: host.head })).status).toBe(409); - expect((await post(false, { commitSha: host.head })).status).toBe(200); + expect((await post({ commitSha: host.head })).status).toBe(409); + expect((await post({ commitSha: host.head })).status).toBe(200); } finally { release(); } expect((await first).status).toBe(409); expect(host.mutations).toHaveLength(2); diff --git a/tests/integration-weights.json b/tests/integration-weights.json index db9ee0bb12..2fe077bbb5 100644 --- a/tests/integration-weights.json +++ b/tests/integration-weights.json @@ -4,7 +4,6 @@ "cli/src/commands/serve-processes.test.ts": 2, "cli/src/commands/team.test.ts": 2, "src/app/api/automations/connected/route.test.ts": 5, - "src/app/api/codex/send/route.test.ts": 2, "src/app/api/customize/actions/github-source.test.ts": 6, "src/app/api/customize/actions/route.test.ts": 9, "src/app/api/customize/actions/state.test.ts": 9, @@ -26,8 +25,6 @@ "src/app/api/v2/keys/route.launch.test.ts": 25, "src/app/api/v2/keys/route.master-key.test.ts": 2, "src/app/api/v2/proxy/cli/route.test.ts": 2, - "src/app/api/worktrees/merge/route-real-path.test.ts": 33, - "src/app/api/worktrees/merge/route.test.ts": 5, "src/app/api/worktrees/retention-usage/route-path-selection.test.ts": 4, "src/app/api/worktrees/retention-usage/route.test.ts": 3, "src/app/api/worktrees/route-real-path.test.ts": 8, @@ -735,7 +732,6 @@ "tests/provider-key-chat-routes-real-path.test.ts": 2, "tests/provider-key-child-boundary-real-path.test.ts": 3, "tests/provider-key-codex-subscription-only-real-path.test.ts": 2, - "tests/provider-key-deferred-mcp-real-path.test.ts": 2, "tests/provider-key-file-billing-disabled-real-path.test.ts": 3, "tests/provider-key-model-probe-real-path.test.ts": 2, "tests/provider-key-refresh-real-path.test.ts": 22, @@ -926,7 +922,6 @@ "tests/viewer-redaction-real-path.test.ts": 114, "tests/viewer-redaction-review-real-path.test.ts": 21, "tests/viewer-remote-redaction-real-path.test.ts": 5, - "tests/viewer-session-redaction-real-path.test.ts": 2, "tests/visualization-browser-real-path.test.ts": 2, "tests/visualization-mcp-real-path.test.ts": 8, "tests/visualization-reload-real-path.test.ts": 55, diff --git a/tests/knowledge-source-direct-writers-real-path.test.ts b/tests/knowledge-source-direct-writers-real-path.test.ts index 670663d646..0234320e24 100644 --- a/tests/knowledge-source-direct-writers-real-path.test.ts +++ b/tests/knowledge-source-direct-writers-real-path.test.ts @@ -11,7 +11,7 @@ const f = vi.hoisted(() => { const fs = process.getBuiltinModule('node:fs'); const p = process.getBuiltinModule('node:path'); const root = fs.realpathSync(fs.mkdtempSync(p.join(process.getBuiltinModule('node:os').tmpdir(), 'o8-source-writers-'))); process.env.O8_DATA_DIR = p.join(root, 'data'); process.env.CORTEX_IDE_DATA_DIR = process.env.O8_DATA_DIR; - return { root, launched: vi.fn(), claude: vi.fn(), spawned: vi.fn(), failGitProbe: false, gitCalls: 0 }; + return { root, launched: vi.fn(), spawned: vi.fn(), failGitProbe: false, gitCalls: 0 }; }); vi.mock('@/lib/skeleton/autoscan', () => ({ triggerScan: vi.fn() })); vi.mock('@/lib/cortex/knowledge/reconcile', () => ({ reconcileKnowledgeSources: async () => {} })); @@ -21,10 +21,6 @@ vi.mock('@/lib/runtime/actions', async original => ({ ...await original ({ - ensureSession: (_key: string, cwd: string) => { f.claude(cwd); writeFileSync(path.join(cwd, 'note.md'), 'Claude wrote'); return { sessionId: 'fixture', cwd }; }, - sendMessage: async () => {}, -})); vi.mock('@/lib/providers/child-process', async original => ({ ...await original(), execFileSync: (...args: Parameters) => { if (args[0] === 'git') f.gitCalls += 1; @@ -46,10 +42,7 @@ const asset = await import('@/app/api/repo-spec/asset/route'); const editor = await import('@/app/api/panel/file-io/route'); const commit = await import('@/app/api/review/commit/route'); const branches = await import('@/app/api/panel/branches/route'); -const checkout = await import('@/app/api/panel/branches/checkout/route'); -const dev = await import('@/app/api/panel/dev-server/route'); const runtime = await import('@/app/api/runtime/launch/route'); -const claude = await import('@/app/api/claude-code/send/route'); const token = getOrCreateWsToken(); const require = createRequire(import.meta.url); const sourceRoot = process.cwd(); @@ -71,12 +64,12 @@ async function protect(root: string) { beforeEach(async () => { await updateOperatorDefaults({ knowledgeSources: [] }); for (const entry of await listRepos()) await removeRepo(entry.id); - f.launched.mockClear(); f.claude.mockClear(); f.spawned.mockClear(); + f.launched.mockClear(); f.spawned.mockClear(); f.failGitProbe = false; }); afterAll(() => { closeDb(); rmSync(f.root, { recursive: true, force: true }); }); -it.each(['spec', 'annotation', 'asset', 'editor', 'commit', 'create branch', 'delete branch', 'checkout', 'dev server', 'Claude'] as const)( +it.each(['spec', 'annotation', 'asset', 'editor', 'commit', 'create branch', 'delete branch'] as const)( 'refuses the direct %s writer while leaving source files and Git identity untouched', async writer => { const vault = repo(); await protect(vault); const before = git(vault, 'rev-parse', 'HEAD'); const specUrl = `/api/repo-spec?repoPath=${encodeURIComponent(vault)}`; @@ -87,10 +80,7 @@ it.each(['spec', 'annotation', 'asset', 'editor', 'commit', 'create branch', 'de else if (writer === 'editor') response = await editor.PUT(req('/api/panel/file-io', { path: path.join(vault, 'note.md'), content: 'must not edit' }, 'PUT')); else if (writer === 'commit') { writeFileSync(path.join(vault, 'new.md'), 'uncommitted'); response = await commit.POST(req('/api/review/commit', { workspace: vault, message: 'must not commit' })); } else if (writer === 'create branch') response = await branches.POST(req('/api/panel/branches', { path: vault, branch: 'new-branch' })); - else if (writer === 'delete branch') response = await branches.DELETE(req('/api/panel/branches', { path: vault, branch: 'other', force: true }, 'DELETE')); - else if (writer === 'checkout') response = await checkout.POST(req('/api/panel/branches/checkout', { repoPath: vault, branch: 'other' })); - else if (writer === 'dev server') response = await dev.POST(req('/api/panel/dev-server', { repoPath: vault, command: 'fixture-not-executed' })); - else response = await claude.POST(req('/api/claude-code/send', { cwd: vault, tabId: `fixture-${sequence}`, message: 'fixture' })); + else response = await branches.DELETE(req('/api/panel/branches', { path: vault, branch: 'other', force: true }, 'DELETE')); const body = await response.text(); expect(readFileSync(path.join(vault, 'note.md'), 'utf8')).toBe('retained'); expect(readFileSync(path.join(vault, 'o8.md'), 'utf8')).toBe('# Retained\n'); @@ -100,7 +90,7 @@ it.each(['spec', 'annotation', 'asset', 'editor', 'commit', 'create branch', 'de expect(git(vault, 'branch', '--list', 'other')).toContain('other'); expect(git(vault, 'branch', '--list', 'new-branch')).toBe(''); expect(response.status, body).toBe(403); expect(body).toContain('read-only'); - expect(f.spawned).not.toHaveBeenCalled(); expect(f.claude).not.toHaveBeenCalled(); + expect(f.spawned).not.toHaveBeenCalled(); }, ); @@ -170,54 +160,6 @@ it('guards default-cwd discard through a fresh server process running inside the expect(result.status, result.body).toBe(403); }); -it.each(['gitfile', 'relative core.worktree', 'GIT_DIR', 'GIT_WORK_TREE', 'both environment roots'] as const)( - 'refuses checkout redirected into protected notes by %s without changing any bytes', async mode => { - const writable = repo(); - git(writable, 'checkout', 'other'); writeFileSync(path.join(writable, 'note.md'), 'replacement from other branch'); - git(writable, 'add', '.'); git(writable, 'commit', '-m', 'other branch'); git(writable, 'checkout', 'main'); - const vault = path.join(f.root, `worktree-notes-${++sequence}`); mkdirSync(vault); - writeFileSync(path.join(vault, 'note.md'), 'retained'); writeFileSync(path.join(vault, 'o8.md'), '# Retained\n'); - await protect(vault); - const alias = path.join(f.root, `git-alias-${sequence}`); mkdirSync(alias); - const admin = path.join(writable, '.git'); - const oldGitDir = process.env.GIT_DIR, oldWorkTree = process.env.GIT_WORK_TREE; - let cwd = alias; - if (mode !== 'GIT_WORK_TREE') git(writable, 'config', 'core.worktree', mode === 'relative core.worktree' ? path.relative(admin, vault) : vault); - if (mode === 'gitfile' || mode === 'relative core.worktree') writeFileSync(path.join(alias, '.git'), `gitdir: ${admin}\n`); - if (mode === 'GIT_DIR' || mode === 'both environment roots') process.env.GIT_DIR = admin; - if (mode === 'GIT_WORK_TREE' || mode === 'both environment roots') { process.env.GIT_WORK_TREE = vault; cwd = mode === 'GIT_WORK_TREE' ? writable : alias; } - const retained = ['note.md', 'o8.md'].map(file => readFileSync(path.join(vault, file))); - const head = readFileSync(path.join(admin, 'HEAD')), index = readFileSync(path.join(admin, 'index')); - try { - const response = await checkout.POST(req('/api/panel/branches/checkout', { repoPath: cwd, branch: 'other', force: true })); - expect.soft(readFileSync(path.join(vault, 'note.md'))).toEqual(retained[0]); - expect.soft(readFileSync(path.join(vault, 'o8.md'))).toEqual(retained[1]); - expect.soft(readFileSync(path.join(admin, 'HEAD'))).toEqual(head); - expect.soft(readFileSync(path.join(admin, 'index'))).toEqual(index); - expect(response.status, await response.text()).toBe(403); - } finally { - if (oldGitDir === undefined) delete process.env.GIT_DIR; else process.env.GIT_DIR = oldGitDir; - if (oldWorkTree === undefined) delete process.env.GIT_WORK_TREE; else process.env.GIT_WORK_TREE = oldWorkTree; - } - }, -); - -it('allows an external gitfile checkout whose effective worktree is separate from the source', async () => { - const writable = repo(); - git(writable, 'checkout', 'other'); writeFileSync(path.join(writable, 'note.md'), 'permitted replacement'); - git(writable, 'add', '.'); git(writable, 'commit', '-m', 'other branch'); git(writable, 'checkout', 'main'); - const worktree = path.join(f.root, `allowed-worktree-${++sequence}`); mkdirSync(worktree); - writeFileSync(path.join(worktree, 'note.md'), 'retained'); writeFileSync(path.join(worktree, 'o8.md'), '# Retained\n'); - const vault = repo(); await protect(vault); - git(writable, 'config', 'core.worktree', worktree); - const alias = path.join(f.root, `allowed-alias-${sequence}`); mkdirSync(alias); - writeFileSync(path.join(alias, '.git'), `gitdir: ${path.join(writable, '.git')}\n`); - const response = await checkout.POST(req('/api/panel/branches/checkout', { repoPath: alias, branch: 'other', force: true })); - expect(response.status, await response.text()).toBe(200); - expect(readFileSync(path.join(worktree, 'note.md'), 'utf8')).toBe('permitted replacement'); - expect(readFileSync(path.join(vault, 'note.md'), 'utf8')).toBe('retained'); -}); - it('refuses a commit whose environment redirects Git objects into protected notes', async () => { const writable = repo(), vault = repo(); const objects = path.join(vault, 'objects'); mkdirSync(objects); await protect(vault); @@ -275,37 +217,6 @@ it.each(['refs', 'refs/heads', 'logs', 'logs/refs/heads', 'packed-refs', 'index' }, ); -it.each(['GIT_TRACE', 'GIT_TRACE_SETUP', 'GIT_TRACE_PERFORMANCE', 'GIT_TRACE2', 'GIT_TRACE2_EVENT', 'GIT_TRACE2_PERF', 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_COUNT', 'GIT_PAGER'])( - 'refuses inherited %s before the guard itself can run Git or modify notes', async name => { - const writable = repo(); const vault = path.join(f.root, `trace-notes-${++sequence}`); mkdirSync(vault); - const note = path.join(vault, 'note.md'); writeFileSync(note, '# Retained trace canary\n'); await protect(vault); - // The old guard ultimately refuses this worktree, but its earlier probe - // must not append trace output on the way to that refusal. - git(writable, 'config', 'core.worktree', vault); - const retained = readFileSync(note); const previous = process.env[name]; - process.env[name] = note; f.gitCalls = 0; - try { - const response = await checkout.POST(req('/api/panel/branches/checkout', { repoPath: writable, branch: 'other', force: true })); - expect.soft(readFileSync(note)).toEqual(retained); - expect.soft(f.gitCalls, 'a guard probe inherited caller-controlled Git behavior').toBe(0); - expect(response.status, await response.text()).toBe(403); - } finally { - if (previous === undefined) delete process.env[name]; else process.env[name] = previous; - } - }, -); - -it('keeps guard probes read-only when local Git config enables trace2 output', async () => { - const writable = repo(); const vault = path.join(f.root, `config-trace-${++sequence}`); mkdirSync(vault); - const note = path.join(vault, 'note.md'); writeFileSync(note, '# Retained configuration trace canary\n'); await protect(vault); - git(writable, 'config', 'core.worktree', vault); - git(writable, 'config', 'trace2.eventTarget', note); - const retained = readFileSync(note); - const response = await checkout.POST(req('/api/panel/branches/checkout', { repoPath: writable, branch: 'other', force: true })); - expect.soft(readFileSync(note)).toEqual(retained); - expect(response.status, await response.text()).toBe(403); -}); - it.each(['refs/heads', 'logs/refs/heads'])('refuses source admission when a registered repo redirects %s into it', async storage => { const writable = repo(); const vault = path.join(f.root, `admission-notes-${++sequence}`); mkdirSync(vault); const note = path.join(vault, 'note.md'); writeFileSync(note, '# Retained admission canary\n'); diff --git a/tests/knowledge-source-write-boundaries-real-path.test.ts b/tests/knowledge-source-write-boundaries-real-path.test.ts index 562d1a9f67..3095fc14bc 100644 --- a/tests/knowledge-source-write-boundaries-real-path.test.ts +++ b/tests/knowledge-source-write-boundaries-real-path.test.ts @@ -41,7 +41,6 @@ vi.mock('@/lib/providers/child-process', async original => { const { updateOperatorDefaults } = await import('@/lib/operator/defaults'); const { addRepo, updateRepo, listRepos, listReposFresh, removeRepo } = await import('@/lib/repos/registry'); -const { POST: send } = await import('@/app/api/codex/send/route'); const { POST: reposPost } = await import('@/app/api/panel/repos/route'); const { POST: save, GET: read } = await import('@/app/api/v2/files/route'); const { getOrCreateWsToken } = await import('@/lib/ws-auth'); @@ -78,18 +77,6 @@ beforeEach(async () => { }); afterAll(() => { closeDb(); vi.unstubAllEnvs(); rmSync(f.root, { recursive: true, force: true }); }); -it.each([false, true])('refuses a protected literal trailing-space send before any child writes (resume: %s)', async resume => { - const sibling = repo(); - const original = repo(); const vault = `${sibling} `; renameSync(original, vault); - await source(vault); - const response = await send(request('/api/codex/send', { cwd: vault, message: 'fixture', ...(resume ? { threadId: 'fixture-thread' } : {}) })); - const body = await response.text(); - expect(readFileSync(path.join(sibling, 'note.md'), 'utf8')).toBe('# Preserved notes\n'); - expect(readFileSync(path.join(vault, 'note.md'), 'utf8')).toBe('# Preserved notes\n'); - expect(response.status, body).toBe(400); - expect(body).toContain('read-only'); -}); - it('refuses a case-only clone into an offline source before Git writes the destination', async () => { const origin = repo(); const developer = path.join(f.root, 'Developer'); mkdirSync(developer, { recursive: true }); const vault = path.join(developer, `Notes-${++seq}`); mkdirSync(vault); @@ -109,16 +96,12 @@ it('refuses a case-only clone into an offline source before Git writes the desti } }); -it.each((['send', 'registry add', 'registry update', 'workspace save'] as const).flatMap(entry => +it.each((['registry add', 'registry update', 'workspace save'] as const).flatMap(entry => ([['space', ' '], ['carriage return', '\r']] as const).map(([label, suffix]) => [entry, label, suffix] as const), ))('keeps an unprotected literal path through %s (%s)', async (entry, _label, suffix) => { const sibling = repo(); const original = repo(); const literal = `${sibling}${suffix}`; renameSync(original, literal); const registered = await addRepo(sibling); - if (entry === 'send') { - const response = await send(request('/api/codex/send', { cwd: literal, message: 'fixture' })); - expect(response.status, await response.text()).toBe(200); - expect(readFileSync(path.join(literal, 'note.md'), 'utf8')).toBe('CLI wrote here'); - } else if (entry === 'registry add') { + if (entry === 'registry add') { const response = await reposPost(request('/api/panel/repos', { action: 'add', localPath: literal })); expect(response.status, await response.clone().text()).toBe(201); expect((await response.json()).repo.localPath).toBe(literal); @@ -135,7 +118,7 @@ it.each((['send', 'registry add', 'registry update', 'workspace save'] as const) }); const spellings = ['tilde', 'padded tilde', 'relative', 'symlink', 'symlink parent traversal', 'trailing separators', 'case alias'] as const; -const entries = ['send', 'registry add', 'registry update', 'clone', 'workspace save'] as const; +const entries = ['registry add', 'registry update', 'clone', 'workspace save'] as const; it.each(spellings.flatMap(spelling => entries.map(entry => [spelling, entry] as const)))( 'excludes a source spelled with %s through %s', async (spelling, entry) => { const original = repo(); @@ -165,8 +148,7 @@ it.each(spellings.flatMap(spelling => entries.map(entry => [spelling, entry] as } } let response: Response; - if (entry === 'send') response = await send(request('/api/codex/send', { cwd: input, message: 'fixture' })); - else if (entry === 'registry add') response = await reposPost(request('/api/panel/repos', { action: 'add', localPath: input })); + if (entry === 'registry add') response = await reposPost(request('/api/panel/repos', { action: 'add', localPath: input })); else if (entry === 'registry update') response = await reposPost(request('/api/panel/repos', { action: 'update', id: registered.id, localPath: input })); else if (entry === 'clone') { // Clone has no caller-supplied destination. Its fixed ~/Developer root @@ -193,18 +175,6 @@ it.each(spellings.flatMap(spelling => entries.map(entry => [spelling, entry] as }, ); -it.each(['root', 'descendant', 'alias', 'resume'] as const)('refuses a direct %s send before an offline CLI can modify the source', async mode => { - const folder = repo(); await source(folder); - let cwd = folder; - if (mode === 'descendant') { cwd = path.join(folder, 'child'); mkdirSync(cwd); writeFileSync(path.join(cwd, 'note.md'), '# Preserved notes\n'); } - if (mode === 'alias') { cwd = path.join(f.root, `alias-${++seq}`); symlinkSync(folder, cwd, 'dir'); } - const response = await send(request('/api/codex/send', { cwd, message: 'fixture', ...(mode === 'resume' ? { threadId: 'fixture-thread' } : {}) })); - const body = await response.text(); - expect(readFileSync(path.join(cwd, 'note.md'), 'utf8')).toBe('# Preserved notes\n'); - expect(response.status, body).toBe(400); - expect(body).toContain('read-only'); -}); - it.each(['route', 'registry'] as const)('refuses registry repoint through the %s entry point', async entry => { const original = repo(); const vault = repo(); const registered = await addRepo(original); await source(vault); @@ -274,12 +244,9 @@ it('preserves literal whitespace in configured roots when guarding a default-wor } }); -it('retains normal writable repository sends, updates and file saves', async () => { +it('retains normal writable repository updates and file saves', async () => { const first = repo(); const second = repo(); const vault = repo(); await source(vault); const registered = await addRepo(first); - const response = await send(request('/api/codex/send', { cwd: first, message: 'fixture' })); - expect(response.status).toBe(200); await response.text(); - expect(readFileSync(path.join(first, 'note.md'), 'utf8')).toBe('CLI wrote here'); await updateRepo(registered.id, { localPath: second }); expect((await save(request('/api/v2/files', { workspace: second, path: 'note.md', content: 'permitted' }))).status).toBe(200); expect(readFileSync(path.join(second, 'note.md'), 'utf8')).toBe('permitted'); diff --git a/tests/panel-json-body-real-path.test.ts b/tests/panel-json-body-real-path.test.ts index bc1d414005..886d4f3f14 100644 --- a/tests/panel-json-body-real-path.test.ts +++ b/tests/panel-json-body-real-path.test.ts @@ -3,11 +3,6 @@ import { getOrCreateWsToken } from '@/lib/ws-auth'; import { expect, it } from 'vitest'; import * as route0 from '@/app/api/panel/branches/route'; -import * as route1 from '@/app/api/panel/branches/checkout/route'; -import * as route2 from '@/app/api/panel/dev-server/route'; -import * as route3 from '@/app/api/panel/ide-surface/route'; -import * as route4 from '@/app/api/panel/terminal-exec/route'; -import * as route5 from '@/app/api/panel/assign-issue/route'; import * as route6 from '@/app/api/panel/issues/create/route'; import * as route7 from '@/app/api/panel/issues/enhance/route'; import * as route8 from '@/app/api/panel/terminal-state/route'; @@ -16,12 +11,6 @@ import * as route9 from '@/app/api/panel/workspaces/route'; const routes = [ ['POST /api/panel/branches', route0.POST], ['DELETE /api/panel/branches', route0.DELETE], - ['POST /api/panel/branches/checkout', route1.POST], - ['POST /api/panel/dev-server', route2.POST], - ['DELETE /api/panel/dev-server', route2.DELETE], - ['POST /api/panel/ide-surface', route3.POST], - ['POST /api/panel/terminal-exec', route4.POST], - ['POST /api/panel/assign-issue', route5.POST], ['POST /api/panel/issues/create', route6.POST], ['POST /api/panel/issues/enhance', route7.POST], ['POST /api/panel/terminal-state', route8.POST], diff --git a/tests/panel-raster-image-serving-real-path.test.ts b/tests/panel-raster-image-serving-real-path.test.ts index ec2cdef086..03b13935c3 100644 --- a/tests/panel-raster-image-serving-real-path.test.ts +++ b/tests/panel-raster-image-serving-real-path.test.ts @@ -6,11 +6,11 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; // Real files served through the real panel preview routes. #4773 routed every // image through the UTF-8 text viewer, so panel raster previews (serve-image, -// file-preview, file-asset) were refused with HTTP 415. These cases pin that +// file-asset) were refused with HTTP 415. These cases pin that // valid PNGs are served again while a non-image renamed .png stays refused and // the SVG text path is unchanged. -// file-preview and file-asset read from the registered repo root; serve-image +// file-asset reads from the registered repo root, and serve-image // confines to HOME/tmp, so its fixture lives under HOME to pass on macOS and CI. const repoRoot = mkdtempSync(join(tmpdir(), 'o8-panel-repo-')); const homeRoot = mkdtempSync(join(homedir(), '.o8-panel-serve-')); @@ -21,7 +21,6 @@ vi.mock('@/lib/llm/repo-scope', () => ({ })); const { GET: serveImage } = await import('@/app/api/panel/serve-image/route'); -const { GET: filePreview } = await import('@/app/api/panel/file-preview/route'); const { GET: fileAsset } = await import('@/app/api/panel/file-asset/route'); // A real 1x1 PNG; the routes verify its signature, header and trailer. @@ -69,18 +68,10 @@ describe('panel routes serve verified raster images', () => { expect(Buffer.from(await response.arrayBuffer()).equals(PNG)).toBe(true); }); - it('file-preview returns a persisted PNG as image/png with the original bytes', async () => { - const response = await filePreview(repoRequest('panel/file-preview', 'valid.png')); - expect(response.status).toBe(200); - expect(response.headers.get('Content-Type')).toBe('image/png'); - expect(Buffer.from(await response.arrayBuffer()).equals(PNG)).toBe(true); - }); - it('refuses a non-image renamed .png through every raster route', async () => { const responses = [ await serveImage(serveRequest('disguised.png')), await fileAsset(repoRequest('panel/file-asset', 'disguised.png')), - await filePreview(repoRequest('panel/file-preview', 'disguised.png')), ]; for (const response of responses) { expect(response.status).toBe(415); @@ -89,12 +80,9 @@ describe('panel routes serve verified raster images', () => { }); it('keeps the SVG text path unchanged (not routed through the raster verifier)', async () => { - // serve-image serves SVG as inspected UTF-8 text; file-preview returns it as JSON. + // serve-image serves SVG as inspected UTF-8 text. const served = await serveImage(serveRequest('vector.svg')); expect(served.status).toBe(200); expect(served.headers.get('Content-Type')).toContain('image/svg+xml'); - const previewed = await filePreview(repoRequest('panel/file-preview', 'vector.svg')); - expect(previewed.status).toBe(200); - expect((await previewed.json()).type).toBe('svg'); }); }); diff --git a/tests/plugin-principal-real-path.test.ts b/tests/plugin-principal-real-path.test.ts index 8f73ded475..bf92aa5d61 100644 --- a/tests/plugin-principal-real-path.test.ts +++ b/tests/plugin-principal-real-path.test.ts @@ -157,7 +157,7 @@ describe('plugin principal through the real API and persisted state', () => { }); it('refuses approval, merge, unrestricted MCP, and every other route even when public', async () => { - for (const path of ['/api/panel/approvals', '/api/worktrees/merge', '/api/mcp', '/api/mobile/enroll', '/api/plugins/audit', '/api/plugins/mcp/extra']) { + for (const path of ['/api/panel/approvals', '/api/mcp', '/api/mobile/enroll', '/api/plugins/audit', '/api/plugins/mcp/extra']) { expect(panelGateMiddleware(request('approve', {}, token(), path)).status).toBe(403); } for (const name of ['approve_and_merge', 'o8_exec', 'approve']) { diff --git a/tests/pr-first-publication-real-path.test.ts b/tests/pr-first-publication-real-path.test.ts index 074ea641d4..66b65015df 100644 --- a/tests/pr-first-publication-real-path.test.ts +++ b/tests/pr-first-publication-real-path.test.ts @@ -1,10 +1,9 @@ import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterAll, expect, it, vi } from 'vitest'; -import { NextRequest } from 'next/server'; vi.mock('@/lib/realtime/publisher', () => ({ publishRealtimeMutation: vi.fn(async () => {}), requestRealtimeRefresh: vi.fn() })); const root = mkdtempSync(join(tmpdir(), 'o8-pr-first-publication-')); Object.assign(process.env, { O8_DATA_DIR: root, CORTEX_IDE_DATA_DIR: root, CORTEX_IDE_DB_PATH: join(root, 'test.db'), WS_TOKEN: 'policy-operator-fixture-token', O8_SKIP_PRELAUNCH_TYPECHECK: '1' }); @@ -12,7 +11,6 @@ writeFileSync(join(root, 'mobile-device-tokens'), `${createHash('sha256').update const { createProject } = await import('@/lib/projects/store'); const { createLane, getLane, getLaneEvents } = await import('@/lib/lane/registry'); const { getWorktreeManager } = await import('@/lib/worktree/launch'); -const { handlePost } = await import('@/app/api/worktrees/merge/handler'); const { dispatchSecondPassMerge } = await import('@/lib/lane/second-pass-merge-dispatch'); const { closeDb } = await import('@/lib/db'); afterAll(() => { closeDb(); rmSync(root, { recursive: true, force: true }); }); @@ -27,14 +25,6 @@ async function fixture() { const lane = createLane({ repoPath: repo, projectId: project.id, branch: worktree.branch, worktreePath: worktree.path, baseBranch: 'main', runtime: 'codex', packetId }); return { repo, worktree, lane, base: git(repo, 'rev-parse', 'main') }; } -it.each(['policy-operator-fixture-token', 'policy-device-fixture-token'])('worktree merge route refuses PR-first publication for %s', async token => { - const f = await fixture(); - const merge = vi.fn(async () => ({ action: 'merge' as const, ok: true, note: 'unexpected integration' })); - const response = await handlePost(new NextRequest('http://localhost/api/worktrees/merge', { method: 'POST', headers: { host: 'localhost', authorization: `Bearer ${token}` }, body: JSON.stringify({ repo: f.repo, worktreeId: f.worktree.id, action: 'merge' }) }), { mergeToTarget: merge }); - expect(response.status).toBe(409); - expect(await response.json()).toMatchObject({ reason: 'pr_only', ok: false }); - expect(merge).not.toHaveBeenCalled(); expect(git(f.repo, 'rev-parse', 'main')).toBe(f.base); expect(existsSync(f.worktree.path)).toBe(true); -}); it.each([null, 'https://github.com/example/project.git', 'https://gitlab.com/example/project.git', 'https://code.example.test/example/project.git'])('delivery guidance is true for origin %s and automatic agreement settles without merge retries', async origin => { const f = await fixture(); if (origin) git(f.repo, 'remote', 'add', 'origin', origin); diff --git a/tests/principal-authz.test.ts b/tests/principal-authz.test.ts index b0dc636421..05d01edd88 100644 --- a/tests/principal-authz.test.ts +++ b/tests/principal-authz.test.ts @@ -68,7 +68,6 @@ const sessionRules = await import('@/app/api/orchestrator/session-rules/route'); const merge = await import('@/app/api/orchestrator/merge/route'); const mergePreview = await import('@/app/api/orchestrator/merge-preview/route'); const workspace = await import('@/app/api/orchestrator/workspace/route'); -const devServer = await import('@/app/api/panel/dev-server/route'); const fileIo = await import('@/app/api/panel/file-io/route'); const repoSpecAsset = await import('@/app/api/repo-spec/asset/route'); const lanes = await import('@/app/api/lanes/route'); @@ -813,20 +812,6 @@ describe('principal-authz — session rules writes are operator-only (#1329 HIGH }); }); -describe('principal-authz — shell/RCE primitive is operator-only (HIGH-3 dev-server)', () => { - const url = 'http://localhost:3001/api/panel/dev-server'; - - it('WORKER → 403 before any shell spawn', async () => { - const res = await devServer.POST(req(url, { principal: 'worker', body: { repoPath: '/tmp', command: 'echo hi' } })); - expect(res.status).toBe(403); - }); - - it('OPERATOR → NOT 403 (passes the principal gate; missing fields → 400)', async () => { - const res = await devServer.POST(req(url, { principal: 'operator', body: {} })); - expect(res.status).toBe(400); // reached real handler: repoPath/command required - }); -}); - describe('principal-authz — worker file access is confined to registered repos (HIGH-6)', () => { const url = 'http://localhost:3001/api/panel/file-io'; @@ -914,7 +899,6 @@ describe('principal-authz — fail-closed: unknown/absent principal is denied on 'http://192.168.1.50:3001/api/orchestrator/rerun-with-feedback', 'http://192.168.1.50:3001/api/orchestrator/session-rules', 'http://192.168.1.50:3001/api/orchestrator/merge', - 'http://192.168.1.50:3001/api/panel/dev-server', 'http://192.168.1.50:3001/api/panel/file-io', ]; diff --git a/tests/provider-key-chat-routes-real-path.test.ts b/tests/provider-key-chat-routes-real-path.test.ts index 79e5ad7ddd..8651f4272b 100644 --- a/tests/provider-key-chat-routes-real-path.test.ts +++ b/tests/provider-key-chat-routes-real-path.test.ts @@ -14,11 +14,9 @@ state.dir = mkdtempSync(join(tmpdir(), 'o8-key-chat-routes-')); const { mutateProviderKey } = await import('@/lib/providers/key-store'); const keys = await import('@/app/api/v2/keys/route'); const billing = await import('@/lib/providers/runtime-billing'); -const codexSend = await import('@/app/api/codex/send/route'); const proxy = await import('@/app/api/v2/proxy/cli/route'); const request = (path: string, body: unknown, method = 'POST') => new NextRequest(`http://localhost/api/${path}`, { method, headers: { host: 'localhost' }, body: JSON.stringify(body) }); const targets = [ - ['workspace-codex', 'codex', 'openai', 'OPENAI_API_KEY'], ['proxy-codex', 'codex', 'openai', 'OPENAI_API_KEY'], ['proxy-gemini', 'gemini', 'gemini', 'GEMINI_API_KEY'], ['proxy-opencode', 'opencode', 'openai', 'OPENAI_API_KEY'], @@ -41,31 +39,29 @@ beforeEach(() => { }); afterAll(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); rmSync(state.dir, { recursive: true, force: true }); }); async function save(provider: string) { if (provider === 'gemini') { mutateProviderKey('GEMINI_API_KEY', { key: 'fixture-saved-chat-key' }); return; } expect((await keys.POST(request('v2/keys', { provider, key: 'fixture-saved-chat-key' }))).status).toBe(200); } -async function chat(target: string, runtime: string) { - const response = target === 'workspace-codex' - ? await codexSend.POST(request('codex/send', { message: 'fixture' })) - : await proxy.POST(request('v2/proxy/cli', { runtime, model: 'fixture', repoPath: state.dir, messages: [{ role: 'user', content: 'fixture' }] })); +async function chat(runtime: string) { + const response = await proxy.POST(request('v2/proxy/cli', { runtime, model: 'fixture', repoPath: state.dir, messages: [{ role: 'user', content: 'fixture' }] })); expect(response.status).toBe(200); await response.text(); expect(state.envs.length).toBeGreaterThan(0); } it('preserves deferred save-to-ambient behavior while the real ordinary chat stays subscription billed', async () => { await save('openai'); expect((await keys.GET(new NextRequest('http://localhost/api/v2/keys', { headers: { host: 'localhost' } }))).status).toBe(200); expect(process.env.OPENAI_API_KEY).toBe('fixture-saved-chat-key'); expect(process.env.CODEX_API_KEY).toBe(''); - await chat('workspace-codex', 'codex'); + await chat('codex'); expect(state.envs.at(-1)?.OPENAI_API_KEY || null).toBeNull(); }); -it.each(targets.flatMap(target => (['subscription', 'api'] as const).map(mode => [...target, mode] as const)))('%s (%s, %s, %s) applies %s billing at the real chat spawn', async (target, runtime, provider, canonical, mode) => { +it.each(targets.flatMap(target => (['subscription', 'api'] as const).map(mode => [...target, mode] as const)))('%s (%s, %s, %s) applies %s billing at the real chat spawn', async (_target, runtime, provider, canonical, mode) => { if (runtime === 'codex' && mode === 'api') expect(() => billing.saveRuntimeBillingMode(runtime, mode)).toThrow(); else expect(() => billing.saveRuntimeBillingMode(runtime, mode)).not.toThrow(); - await save(provider); await chat(target, runtime); + await save(provider); await chat(runtime); expect(state.envs.at(-1)?.[canonical] || null).toBe(runtime !== 'codex' && mode === 'api' ? 'fixture-saved-chat-key' : null); }); -it.each(targets.flatMap(target => ['disable', 'remove'].map(action => [...target, action] as const)))('%s (%s, %s, %s) strips keys after API %s', async (target, runtime, provider, _canonical, action) => { +it.each(targets.flatMap(target => ['disable', 'remove'].map(action => [...target, action] as const)))('%s (%s, %s, %s) strips keys after API %s', async (_target, runtime, provider, _canonical, action) => { if (runtime === 'codex') expect(() => billing.saveRuntimeBillingMode(runtime, 'api')).toThrow(); else expect(() => billing.saveRuntimeBillingMode(runtime, 'api')).not.toThrow(); await save(provider); for (const name of names) vi.stubEnv(name, 'fixture-stale-alias'); if (provider === 'gemini') mutateProviderKey('GEMINI_API_KEY', action === 'disable' ? { enabled: false } : { key: null }); else expect((await (action === 'disable' ? keys.PATCH(request('v2/keys', { provider, enabled: false }, 'PATCH')) : keys.DELETE(request('v2/keys', { provider }, 'DELETE')))).status).toBe(200); - await chat(target, runtime); + await chat(runtime); const aliases = provider === 'openai' ? ['OPENAI_API_KEY', 'CODEX_API_KEY'] : ['GEMINI_API_KEY', 'GOOGLE_AI_API_KEY']; for (const env of state.envs) for (const name of aliases) expect(env[name] || null, name).toBeNull(); }); diff --git a/tests/provider-key-deferred-mcp-real-path.test.ts b/tests/provider-key-deferred-mcp-real-path.test.ts deleted file mode 100644 index bb1fe3be61..0000000000 --- a/tests/provider-key-deferred-mcp-real-path.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { afterAll, expect, it, vi } from 'vitest'; -import { mkdtempSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { NextRequest } from 'next/server'; -const state = vi.hoisted(() => ({ dir: '' })); -vi.mock('@/lib/data-dir-migration', () => ({ getDataDir: () => state.dir })); -state.dir = mkdtempSync(join(tmpdir(), 'o8-deferred-mcp-')); -vi.stubEnv('O8_MASTER_KEY', Buffer.alloc(32, 115).toString('base64url')); -vi.stubEnv('OPENAI_API_KEY', ''); -vi.stubGlobal('fetch', vi.fn(async () => Response.json({ data: {} }))); -const keys = await import('@/app/api/v2/keys/route'); -const { testMcpConnection } = await import('@/lib/mcp/test-connection'); -afterAll(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); rmSync(state.dir, { recursive: true, force: true }); }); -it('does not inherit a saved provider key at the deferred MCP entry point and keeps explicit service auth', async () => { - expect((await keys.POST(new NextRequest('http://localhost/api/v2/keys', { method: 'POST', headers: { host: 'localhost' }, body: JSON.stringify({ provider: 'openai', key: 'fixture-deferred-provider' }) }))).status).toBe(200); - const peer = `const send=m=>process.stdout.write(JSON.stringify(m)+'\\n');require('node:readline').createInterface({input:process.stdin}).on('line',line=>{const m=JSON.parse(line);if(m.id)send({jsonrpc:'2.0',id:m.id,result:m.method==='tools/list'?{tools:[{name:'fixture',description:JSON.stringify({key:process.env.OPENAI_API_KEY,service:process.env.BRAVE_API_KEY})}]}:{}});});`; - const result = await testMcpConnection({ transport: 'stdio', command: process.execPath, args: ['-e', peer], env: { BRAVE_API_KEY: 'fixture-brave' } }); - expect(result.ok).toBe(true); - if (result.ok) expect(JSON.parse(result.tools[0].description!)).toEqual({ service: 'fixture-brave' }); -}); diff --git a/tests/revoked-packet-worker-gate-real-path.test.ts b/tests/revoked-packet-worker-gate-real-path.test.ts index 09c3ca0841..2d1606cecd 100644 --- a/tests/revoked-packet-worker-gate-real-path.test.ts +++ b/tests/revoked-packet-worker-gate-real-path.test.ts @@ -19,30 +19,21 @@ it('refuses a packet worker at the gate once the operator revokes it', async () const { mintPacketWorkerToken } = await import('@/lib/auth/packet-worker-token'); const { getSqlite } = await import('@/lib/db'); const { panelGateMiddleware } = await import('@/middleware'); - const { POST } = await import('@/app/api/panel/workers/route'); + const { createToken, revokeToken } = await import('@/lib/worker/tokens'); const token = mintPacketWorkerToken('fixture-revoked-at-gate'); const gate = (path: string) => panelGateMiddleware(new NextRequest(`http://127.0.0.1:3000${path}`, { headers: { host: '127.0.0.1:3000', authorization: `Bearer ${token}`, 'x-o8-client-addr': '127.0.0.1' } })); for (const path of WORKER_READS) expect(gate(path).headers.get('x-middleware-next'), path).toBe('1'); - // The operator's revoke action in the Workers panel. const { id } = getSqlite().prepare('SELECT id FROM worker_tokens WHERE token_hash = ?').get(sha256(token)) as { id: string }; - const revoked = await POST(new Request('http://127.0.0.1:3000/api/panel/workers', { - method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ action: 'revoke_token', id }) })); - expect(revoked.status).toBe(200); + expect(revokeToken(id)).toBe(true); for (const path of WORKER_READS) { const response = gate(path); expect(response.status, path).toBe(401); expect((await response.json()).detail, path).toMatch(GATE_REFUSAL); } - // A credential the Workers panel creates with the packet scope but no packet stays out of the - // file, after the next rewrite too, so the gate never treats it as a packet worker. - const created = await POST(new Request('http://127.0.0.1:3000/api/panel/workers', { - method: 'POST', headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ action: 'create_token', label: 'fixture packetless', scope: 'local-packet' }) })); - expect(created.status).toBe(201); - const { plaintextToken } = await created.json() as { plaintextToken: string }; + const { plaintextToken } = createToken({ label: 'fixture packetless', scope: 'local-packet' }); mintPacketWorkerToken('fixture-after-packetless'); for (const path of WORKER_READS) { const response = panelGateMiddleware(new NextRequest(`http://127.0.0.1:3000${path}`, { diff --git a/tests/stream-terminal-callers-real-path.test.ts b/tests/stream-terminal-callers-real-path.test.ts index 85477288d0..7910c73de4 100644 --- a/tests/stream-terminal-callers-real-path.test.ts +++ b/tests/stream-terminal-callers-real-path.test.ts @@ -14,7 +14,6 @@ vi.mock('@/lib/runtimes/shared/cli-locate', async (importOriginal) => ({ const { askClaudeOneShot } = await import('@/lib/claude-code/one-shot-repl'); const { askClaudeWarm, prewarmClaudeRepl, resetWarmReplPool } = await import('@/lib/claude-code/warm-repl-pool'); const { ensureSession, sendMessage, killSession } = await import('@/lib/claude-code/interactive-session'); -const { handleClaudeCodeSend } = await import('@/app/api/claude-code/send/streaming-spawn'); const root = mkdtempSync(path.join(os.tmpdir(), 'o8-stream-callers-')); let caseDir = ''; @@ -159,27 +158,4 @@ describe.skipIf(process.platform === 'win32')('terminal results through real str expect(second.events.filter((event) => event.type === 'done')).toHaveLength(1); expect(second.session?.sessionId).toBe('synthetic-session'); }); - - it.each(['success', 'failure', 'failure-trailing'])('the send route reports %s without a false successful close', async (mode) => { - const r = request(mode); - const tabId = `route-tab-${ordinal}`; - tabs.add(tabId); - const response = await handleClaudeCodeSend(new Request('http://localhost/api/claude-code/send', { - method: 'POST', - body: JSON.stringify({ tabId, cwd: caseDir, message: r.prompt, model: 'synthetic-model' }), - })); - expect(response.status).toBe(200); - const body = response.text(); - await r.waitForStop(); - r.release(); - const events = (await body).split('\n\n').filter(Boolean) - .map((line) => JSON.parse(line.slice('data: '.length)) as { type: string; exitCode?: number }); - if (mode === 'success') { - expect(events.filter((event) => event.type === 'done')).toHaveLength(1); - expect(events.at(-1)).toMatchObject({ type: 'close', exitCode: 0 }); - } else { - expect(events.some((event) => event.type === 'done' || event.type === 'close')).toBe(false); - expect(events.at(-1)).toMatchObject({ type: 'error' }); - } - }); }); diff --git a/tests/terminal-visibility-real-path.test.ts b/tests/terminal-visibility-real-path.test.ts index 74daa3c539..3e2f7ab09b 100644 --- a/tests/terminal-visibility-real-path.test.ts +++ b/tests/terminal-visibility-real-path.test.ts @@ -707,7 +707,6 @@ describe.runIf(tmuxAvailable)('terminal visibility through the real WebSocket an blockedUi.socket.close(); for (const [path, body] of [ ['/terminal-voice-input', { sessionName: controlSessionName, text: 'O8_VOICE_MUST_NOT_WRITE' }], - ['/terminal-exec', { sessionName: controlSessionName, command: 'O8_EXEC_MUST_NOT_WRITE' }], ] as const) { const response = await fetch(`http://127.0.0.1:${wsPort}${path}`, { method: 'POST', diff --git a/tests/test-classification.json b/tests/test-classification.json index 2e71518882..d57a245f3b 100644 --- a/tests/test-classification.json +++ b/tests/test-classification.json @@ -51,12 +51,6 @@ "executable-fixture" ] }, - { - "path": "src/app/api/codex/send/route.test.ts", - "reasons": [ - "child-process" - ] - }, { "path": "src/app/api/customize/actions/github-source.test.ts", "reasons": [ @@ -222,23 +216,6 @@ "child-process" ] }, - { - "path": "src/app/api/worktrees/merge/route-real-path.test.ts", - "reasons": [ - "apfs-tool", - "child-process", - "executable-fixture", - "git-cli", - "real-path", - "worktree-api" - ] - }, - { - "path": "src/app/api/worktrees/merge/route.test.ts", - "reasons": [ - "worktree-api" - ] - }, { "path": "src/app/api/worktrees/retention-usage/route-path-selection.test.ts", "reasons": [ @@ -7265,12 +7242,6 @@ "real-path" ] }, - { - "path": "tests/provider-key-deferred-mcp-real-path.test.ts", - "reasons": [ - "real-path" - ] - }, { "path": "tests/provider-key-file-billing-disabled-real-path.test.ts", "reasons": [ @@ -9056,13 +9027,6 @@ "real-path" ] }, - { - "path": "tests/viewer-session-redaction-real-path.test.ts", - "reasons": [ - "network-listener", - "real-path" - ] - }, { "path": "tests/visualization-browser-real-path.test.ts", "reasons": [ @@ -9203,7 +9167,6 @@ "path": "tests/worker-environment-npx-registry-real-path.test.ts", "reasons": [ "child-process", - "network-listener", "real-path" ] }, @@ -9402,7 +9365,6 @@ "path": "tests/workspace-preservation-cli-real-path.test.ts", "reasons": [ "child-process", - "executable-fixture", "git-cli", "network-listener", "real-path", diff --git a/tests/viewer-redaction-real-path.test.ts b/tests/viewer-redaction-real-path.test.ts index d1dcdb39be..bf72490fe9 100644 --- a/tests/viewer-redaction-real-path.test.ts +++ b/tests/viewer-redaction-real-path.test.ts @@ -19,19 +19,14 @@ const routes = [ ['/api/v2/files?preview=1', () => import('@/app/api/v2/files/route')], ['/api/panel/file-io', () => import('@/app/api/panel/file-io/route')], ['/api/panel/file-diff', () => import('@/app/api/panel/file-diff/route')], - ['/api/panel/worktree-diff', () => import('@/app/api/panel/worktree-diff/route')], ['/api/worktrees/diff', () => import('@/app/api/worktrees/diff/route')], ['/api/worktrees/diff?selected=1', () => import('@/app/api/worktrees/diff/route')], ['/api/lanes/[id]/diff', () => import('@/app/api/lanes/[id]/diff/route')], - ['/api/panel/commit-diff', () => import('@/app/api/panel/commit-diff/route')], ['/api/panel/commits/[hash]', () => import('@/app/api/panel/commits/[hash]/route')], ['/api/panel/commits/[hash]/file', () => import('@/app/api/panel/commits/[hash]/file/route')], ['/api/panel/commits', () => import('@/app/api/panel/commits/route')], ['/api/panel/git-log', () => import('@/app/api/panel/git-log/route')], ['/api/panel/git/log', () => import('@/app/api/panel/git/log/route')], - ['/api/review/file', () => import('@/app/api/review/file/route')], - ['/api/review/diff', () => import('@/app/api/review/diff/route')], - ['/api/panel/file-preview', () => import('@/app/api/panel/file-preview/route')], ['/api/mobile/sync', () => import('@/app/api/mobile/sync/route')], ['/api/orchestrator/review-state', () => import('@/app/api/orchestrator/review-state/route')], ] as const; @@ -93,10 +88,9 @@ describe('each credential shape through every persisted viewer route and native const baseBranch = `viewer-base-${index}`; git('branch', baseBranch); const file = `control-${index}.txt`; - const svg = `control-${index}.svg`; const content = `π 🔒 safe heading\n${item.text}\n`; - writeFileSync(join(root, file), content); writeFileSync(join(root, svg), ``); - git('add', '--', file, svg); git('commit', '-q', '-m', item.text); + writeFileSync(join(root, file), content); + git('add', '--', file); git('commit', '-q', '-m', item.text); const sha = git('rev-parse', 'HEAD'); writeFileSync(join(root, file), `${content}${item.text}\nvisible edit\n`); const { createLane } = await import('@/lib/lane/registry'); @@ -106,7 +100,7 @@ describe('each credential shape through every persisted viewer route and native invalidateReviewSnapshotCache(); for (const [route, load] of routes) { const url = new URL(route.replace('[id]', laneId).replace('[hash]', sha), origin); - const params = { workspace: root, repoPath: root, worktreePath: root, baseBranch, sha, packetId, limit: '1', path: route === '/api/panel/file-io' ? join(root, file) : route === '/api/panel/file-preview' ? svg : file }; + const params = { workspace: root, repoPath: root, worktreePath: root, baseBranch, sha, packetId, limit: '1', path: route === '/api/panel/file-io' ? join(root, file) : file }; for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value); if (url.searchParams.has('selected')) url.searchParams.set('file', file); const init = { headers: { host: '127.0.0.1', authorization }, ...(route === '/api/mobile/sync' ? { method: 'POST', body: JSON.stringify({ review: { includeFile: file } }) } : {}) }; @@ -120,7 +114,7 @@ describe('each credential shape through every persisted viewer route and native expect(remote.status, route).toBe(200); assertMasked(await remote.text(), `${route}: native`); } expect(readFileSync(join(root, file), 'utf8')).toContain(item.text); - git('add', '--', file, svg); git('commit', '-q', '-m', 'fixture baseline'); + git('add', '--', file); git('commit', '-q', '-m', 'fixture baseline'); }); it('redacts stored approval diff previews through direct and native reads', async () => { diff --git a/tests/viewer-redaction-review-real-path.test.ts b/tests/viewer-redaction-review-real-path.test.ts index 645a5fb415..535b3247f1 100644 --- a/tests/viewer-redaction-review-real-path.test.ts +++ b/tests/viewer-redaction-review-real-path.test.ts @@ -32,12 +32,9 @@ const rotated = 'fixture-review-rotated-' + 'y'.repeat(32); const git = (...args: string[]) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim(); const directReads = [ ['/api/v2/files', () => import('@/app/api/v2/files/route')], - ['/api/review/file', () => import('@/app/api/review/file/route')], ['/api/panel/file-content', () => import('@/app/api/panel/file-content/route')], ['/api/panel/file-diff', () => import('@/app/api/panel/file-diff/route')], - ['/api/panel/commit-diff', () => import('@/app/api/panel/commit-diff/route')], ['/api/panel/commits/[hash]', () => import('@/app/api/panel/commits/[hash]/route')], - ['/api/panel/worktree-diff', () => import('@/app/api/panel/worktree-diff/route')], ['/api/worktrees/diff', () => import('@/app/api/worktrees/diff/route')], ] as const; @@ -133,21 +130,15 @@ describe('security review regressions through persisted viewer routes', () => { it('refuses recoverable credentials in valid binary previews, including byte ranges', async () => { const png = makePng(operator); writeFileSync(join(root, 'metadata.png'), png); - const { GET: preview } = await import('@/app/api/panel/file-preview/route'); const { GET: asset } = await import('@/app/api/panel/file-asset/route'); - for (const [route, handler] of [['/api/panel/file-preview', preview], ['/api/panel/file-asset', asset]] as const) { - const req = request(route, { path: 'metadata.png' }); - await inspect(await handler(req), operator, route); await inspect(await fetch(req), operator, route); - } + const full = request('/api/panel/file-asset', { path: 'metadata.png' }); + await inspect(await asset(full), operator); await inspect(await fetch(full), operator); const start = png.indexOf(operator); const req = request('/api/panel/file-asset', { path: 'metadata.png' }, { headers: { range: `bytes=${start}-${start + operator.length - 1}` } }); await inspect(await asset(req), operator); await inspect(await fetch(req), operator); }); - it('redacts readme and refuses credential-bearing raw SVG bytes and value-only ranges', async () => { - writeFileSync(join(root, 'README.md'), `# Public\nPASSWORD=${operator}\n`); - const { GET: readme } = await import('@/app/api/panel/readme/route'); - const req = request('/api/panel/readme'); await inspect(await readme(req), operator); await inspect(await fetch(req), operator); + it('refuses credential-bearing raw SVG bytes and value-only ranges', async () => { const svg = ``; writeFileSync(join(root, 'control.svg'), svg); const { GET: asset } = await import('@/app/api/panel/file-asset/route'); @@ -162,7 +153,6 @@ describe('security review regressions through persisted viewer routes', () => { const svg = ``; writeFileSync(join(root, 'embedded.svg'), svg); for (const [route, handler] of [ - ['/api/panel/file-preview', (await import('@/app/api/panel/file-preview/route')).GET], ['/api/panel/file-asset', (await import('@/app/api/panel/file-asset/route')).GET], ['/api/v2/files', (await import('@/app/api/v2/files/route')).GET], ] as const) { @@ -190,7 +180,6 @@ describe('security review regressions through persisted viewer routes', () => { const cases = [ ['/api/panel/serve-image', { path: join(imageRoot, 'alias.png') }, (await import('@/app/api/panel/serve-image/route')).GET], ['/api/mobile/media', { path: join(imageRoot, 'alias.png') }, (await import('@/app/api/mobile/media/route')).GET], - ['/api/panel/report-artifact', { id: 'art-viewer-report' }, (await import('@/app/api/panel/report-artifact/route')).GET], ['/api/panel/threads/artifact', { id: 'art-viewer-report' }, (await import('@/app/api/panel/threads/artifact/route')).GET], ['/api/panel/threads/artifact', { id: 'art-viewer-image' }, (await import('@/app/api/panel/threads/artifact/route')).GET], ['/api/repo-spec', { repoPath: root }, (await import('@/app/api/repo-spec/route')).GET], @@ -211,12 +200,10 @@ describe('security review regressions through persisted viewer routes', () => { ensureArtifactBucket(null); const id = 'art-viewer-corpus'; const relPath = artifactRelPath(null, id, 'txt'); writeFileSync(artifactAbsPath(relPath), item.text); recordArtifact({ id, kind: 'report', source: 'manual', relPath, mimeType: 'text/plain' }); const cases = [ - ['/api/panel/readme', {}, (await import('@/app/api/panel/readme/route')).GET], ['/api/repo-spec', { repoPath: root }, (await import('@/app/api/repo-spec/route')).GET], ['/api/panel/file-asset', { path: 'alias.svg' }, (await import('@/app/api/panel/file-asset/route')).GET], ['/api/panel/serve-image', { path: join(imageRoot, 'alias.svg') }, (await import('@/app/api/panel/serve-image/route')).GET], ['/api/mobile/media', { path: join(imageRoot, 'alias.svg') }, (await import('@/app/api/mobile/media/route')).GET], - ['/api/panel/report-artifact', { id }, (await import('@/app/api/panel/report-artifact/route')).GET], ['/api/panel/threads/artifact', { id }, (await import('@/app/api/panel/threads/artifact/route')).GET], ] as const; for (const [route, params, handler] of cases) { diff --git a/tests/viewer-session-redaction-real-path.test.ts b/tests/viewer-session-redaction-real-path.test.ts deleted file mode 100644 index a1c80a7809..0000000000 --- a/tests/viewer-session-redaction-real-path.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { viewerCredentialCorpus } from './fixtures/viewer-credential-corpus'; -import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; -import { createServer, type Server } from 'node:http'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { NextRequest } from 'next/server'; -import { afterAll, beforeAll, expect, it, vi } from 'vitest'; - -const fixture = vi.hoisted(() => ({ home: '' })); -// Relocate the user-state boundary; the readers and persisted JSONL files are real. -vi.mock('os', async importOriginal => { - const original = await importOriginal(); - return { ...original, default: { ...original, homedir: () => fixture.home }, homedir: () => fixture.home }; -}); -let server: Server; let origin: string; -const authority = 'fixture-session-authority-' + 'z'.repeat(32); -beforeAll(async () => { - fixture.home = mkdtempSync(join(tmpdir(), 'o8-viewer-session-')); - const { WS_TOKEN_PATH } = await import('@/lib/ws-auth'); writeFileSync(WS_TOKEN_PATH, authority); - const { handleNativeHttp } = await import('@/lib/ws-server/native-http-routes'); - server = createServer(async (req, res) => { if (!await handleNativeHttp(req, res)) res.writeHead(404).end(); }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); if (!address || typeof address === 'string') throw new Error('Listener did not bind'); - origin = `http://127.0.0.1:${address.port}`; -}); -afterAll(async () => { - if (server?.listening) await new Promise(resolve => server.close(() => resolve())); - rmSync(fixture.home, { recursive: true, force: true }); -}); - -it.each(['patch', 'edit'])('withholds uncertified %s fragments from persisted session previews', async format => { - const secret = 'fixture-unlabelled-fragment\n' + viewerCredentialCorpus.map(item => item.text).join('\n'); - let load: () => Promise<{ GET: (req: NextRequest) => Promise }>; - if (format === 'patch') { - const directory = join(fixture.home, '.codex', 'sessions', '2026', '01', '01'); mkdirSync(directory, { recursive: true }); - writeFileSync(join(directory, 'fixture.jsonl'), JSON.stringify({ payload: { type: 'custom_tool_call', name: 'apply_patch', input: `*** Begin Patch\n*** Update File: fixture.txt\n@@\n-old\n${secret.split('\n').map(line => '+' + line).join('\n')}\n*** End Patch` } })); - load = () => import('@/app/api/codex/diffs/route'); - } else { - const directory = join(fixture.home, '.claude', 'projects', 'fixture'); mkdirSync(directory, { recursive: true }); - writeFileSync(join(directory, 'fixture.jsonl'), JSON.stringify({ message: { content: [{ type: 'tool_use', name: 'Edit', input: { file_path: 'fixture.txt', old_string: 'old', new_string: secret } }] } })); - load = () => import('@/app/api/claude-code/diffs/route'); - } - const route = format === 'patch' ? '/api/codex/diffs' : '/api/claude-code/diffs'; - const req = new NextRequest(`${origin}${route}?limit=20`, { headers: { authorization: `Bearer ${authority}` } }); - for (const response of [await (await load()).GET(req), await fetch(req)]) { - expect(response.status).toBe(200); - const body = await response.json(); expect(body.diffs).toHaveLength(1); - expect(JSON.stringify(body)).not.toContain('fixture-unlabelled-fragment'); - for (const item of viewerCredentialCorpus) expect(JSON.stringify(body)).not.toContain(item.clear); - expect(body.redaction.spans).toEqual(expect.arrayContaining([expect.objectContaining({ path: '/diffs/0/newText', kind: 'credential' })])); - } -}); diff --git a/tests/worker-environment-launch-boundary-real-path.test.ts b/tests/worker-environment-launch-boundary-real-path.test.ts index 790048fc6d..21120d908f 100644 --- a/tests/worker-environment-launch-boundary-real-path.test.ts +++ b/tests/worker-environment-launch-boundary-real-path.test.ts @@ -17,7 +17,6 @@ const peer = join(root, 'peer.cjs'); const receipt = join(root, 'receipt.json'); const { managedCommandLaunch } = await import('@/lib/terminal/managed-command-launch'); const { sanitizePtyEnv } = await import('@/lib/ws-server/pty-support'); -const { testMcpConnection } = await import('@/lib/mcp/test-connection'); const { callCodebaseMemoryTool } = await import('@/lib/codebase-memory/mcp-client'); const processBoundary = await import('@/lib/providers/child-process'); const { childEnvironment } = await import('@/lib/providers/spawn-environment'); @@ -64,25 +63,11 @@ describe('shared process environment boundary', () => { await completed(fixtureSpawn(launch.file, launch.args, { env: launch.env, stdio: 'ignore' })); expect(observed()).toEqual({ leaked: false, service: true, task: true }); }); - it('Check connection does not promote ambient values into explicit server overrides', async () => { - const result = await testMcpConnection({ transport: 'stdio', command: process.execPath, args: [peer], env: { FIXTURE_SERVICE_TOKEN: 'explicit-service' } }, 3000); - expect(result.ok).toBe(true); - expect(observed().service).toBe(true); - expect(observed().leaked, 'parent canaries must not reach Check connection').toBe(false); - }); it('codebase-memory MCP uses the same ambient boundary', async () => { const result = await callCodebaseMemoryTool({ binPath: peer, cwd: root, toolName: 'fixture', timeoutMs: 3000 }); expect(result.ok).toBe(true); expect(observed().leaked, 'parent canaries must not reach memory MCP').toBe(false); }); - it('MCP connection checks keep service auth without authorizing provider slots', async () => { - const input = { transport: 'stdio' as const, command: process.execPath, args: [peer, '--provider-capture'], - env: { FIXTURE_SERVICE_TOKEN: 'explicit-service', OPENAI_API_KEY: 'fixture-explicit-provider' } }; - expect((await testMcpConnection(input, 3000)).ok).toBe(true); - expect(observed().service).toBe(true); - expect(observed().provider, 'a provider slot needs runtime billing authority').toBe(false); - expect(observed().leaked).toBe(false); - }); it.each(['spawn', 'spawnSync', 'execFile', 'execFileSync', 'exec', 'execSync', 'fork'] as const)('%s defaults to an allowlist without runtime identity', async operation => { const args = [peer, '--capture']; if (operation === 'spawn') await completed(processBoundary.spawn(process.execPath, args, { stdio: 'ignore' })); diff --git a/tests/worker-environment-npx-registry-real-path.test.ts b/tests/worker-environment-npx-registry-real-path.test.ts index e456f96972..bcff1273ce 100644 --- a/tests/worker-environment-npx-registry-real-path.test.ts +++ b/tests/worker-environment-npx-registry-real-path.test.ts @@ -1,156 +1,21 @@ -import { execFileSync } from 'node:child_process'; -import { createHash, randomBytes } from 'node:crypto'; -import { createServer } from 'node:http'; -import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import path from 'node:path'; -import { NextRequest } from 'next/server'; -import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest'; +import { randomBytes } from 'node:crypto'; +import { rmSync } from 'node:fs'; +import { afterAll, expect, it, vi } from 'vitest'; const f = vi.hoisted(() => { const fs = process.getBuiltinModule('node:fs'); const p = process.getBuiltinModule('node:path'); return { root: fs.realpathSync.native(fs.mkdtempSync(p.join(process.getBuiltinModule('node:os').tmpdir(), 'o8-npx-registry-'))) }; }); vi.mock('@/lib/data-dir-migration', () => ({ getDataDir: () => f.root, migrateDataDirOnce: () => {} })); -const { POST } = await import('@/app/api/panel/mcp-test/route'); -const { getOrCreateWsToken } = await import('@/lib/ws-auth'); -const { closeDb } = await import('@/lib/db'); -const token = getOrCreateWsToken(); -const registryToken = randomBytes(24).toString('hex'); -const blocked = ['NPM_TOKEN', 'NODE_AUTH_TOKEN', 'NPM_CONFIG__AUTH', 'npm_config__authToken', - 'NPM_CONFIG_UNRELATED_SECRET', 'NPM_CONFIG_NODE_OPTIONS', 'O8_UNRELATED_EXPORTED_SECRET']; -const settings = ['userconfig', 'globalconfig', 'registry', 'cache', 'prefix', 'proxy', 'https_proxy', 'noproxy', - 'ca', 'cafile', 'strict_ssl', 'fetch_retries', 'fetch_retry_factor', 'fetch_retry_mintimeout', - 'fetch_retry_maxtimeout', 'fetch_timeout', 'offline', 'prefer_offline', 'prefer_online']; -const requests: Array<{ url: string; authenticated: boolean; status: number }> = []; -let registry: string; -let archive: Buffer; -let sequence = 0; -const server = createServer((req, res) => { - const authenticated = req.headers.authorization === `Bearer ${registryToken}`; - const url = req.url ?? ''; - const status = !authenticated || !url.startsWith('/registry/') ? 401 : 200; - requests.push({ url, authenticated, status }); - if (status === 401) { res.writeHead(401, { 'www-authenticate': 'Bearer' }).end('private fixture requires authentication'); return; } - if (url === '/registry/check-connection-1.0.0.tgz') { - res.writeHead(200, { 'content-type': 'application/octet-stream' }).end(archive); return; - } - res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ - name: '@o8-fixture/check-connection', 'dist-tags': { latest: '1.0.0' }, - time: { created: '2020-01-01T00:00:00.000Z', modified: '2020-01-01T00:00:00.000Z', '1.0.0': '2020-01-01T00:00:00.000Z' }, - versions: { '1.0.0': { name: '@o8-fixture/check-connection', version: '1.0.0', - bin: { 'o8-registry-mcp': 'peer.cjs' }, dist: { tarball: `${registry}check-connection-1.0.0.tgz`, - integrity: `sha512-${createHash('sha512').update(archive).digest('base64')}` } } }, - })); -}); -beforeAll(async () => { - const pkg = path.join(f.root, 'package'); mkdirSync(pkg); - writeFileSync(path.join(pkg, 'package.json'), JSON.stringify({ name: '@o8-fixture/check-connection', version: '1.0.0', bin: { 'o8-registry-mcp': 'peer.cjs' } })); - writeFileSync(path.join(pkg, 'peer.cjs'), `#!${process.execPath} -const fs=require('node:fs'); -const names=${JSON.stringify(settings.map(name => `npm_config_${name}`))}; -fs.writeFileSync(process.env.O8_FIXTURE_RECEIPT,JSON.stringify({ - config:Object.fromEntries(Object.entries(process.env).filter(([name])=>names.includes(name.toLowerCase())).map(([name,value])=>[name.toLowerCase(),value])), - blockedPresent:${JSON.stringify(blocked)}.some(name=>name in process.env), -})); -require('node:readline').createInterface({input:process.stdin}).on('line',line=>{ - const m=JSON.parse(line); if(!m.id)return; - const result=m.method==='tools/list'?{tools:[{name:'private_registry_fixture',inputSchema:{type:'object'}}]}:{protocolVersion:'2024-11-05',capabilities:{},serverInfo:{name:'private-fixture',version:'1.0.0'}}; - process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n'); -}); -`, { mode: 0o700 }); - const tarball = path.join(f.root, 'fixture.tgz'); - execFileSync('tar', ['-czf', tarball, '-C', f.root, 'package']); archive = readFileSync(tarball); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const address = server.address(); if (!address || typeof address === 'string') throw new Error('Missing registry fixture port'); - registry = `http://127.0.0.1:${address.port}/registry/`; -}); -afterEach(() => vi.unstubAllEnvs()); -afterAll(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())); closeDb(); rmSync(f.root, { recursive: true, force: true }); }); - -function fixture() { - const root = path.join(f.root, String(++sequence)); mkdirSync(root); - for (const name of Object.keys(process.env).filter(name => /^npm_config_/i.test(name))) vi.stubEnv(name, undefined); - vi.stubEnv('HOME', root); vi.stubEnv('USERPROFILE', root); - vi.stubEnv('O8_WORKER_ENV_INHERIT', '0'); vi.stubEnv('O8_WORKER_ENV_ALLOW', ''); - vi.stubEnv('NO_PROXY', '127.0.0.1,localhost'); vi.stubEnv('no_proxy', '127.0.0.1,localhost'); - for (const name of blocked) vi.stubEnv(name, 'fixture-unapproved-parent-value'); - const userconfig = path.join(root, 'user.npmrc'), globalconfig = path.join(root, 'global.npmrc'); - const auth = `//${new URL(registry).host}/:_authToken=${registryToken}\n`; - // Every fallback is loopback too, so losing the registry setting cannot reach npmjs. - const fallback = `registry=${registry.replace('/registry/', '/denied/')}\n`; - writeFileSync(userconfig, fallback + auth, { mode: 0o600 }); writeFileSync(globalconfig, '', { mode: 0o600 }); - writeFileSync(path.join(root, 'ca.pem'), ''); - requests.length = 0; - return { root, userconfig, globalconfig, auth, receipt: path.join(root, 'receipt.json') }; -} -async function check(receipt: string, env: Record = {}, explicitRegistry = true) { - const response = await POST(new NextRequest('http://localhost/api/panel/mcp-test', { - method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, - body: JSON.stringify({ inline: { transport: 'stdio', command: 'npx', - args: ['--yes', '--no-audit', '--no-fund', '--no-update-notifier', '--loglevel=error', '--fetch-retries=0', '--fetch-timeout=5000', - ...(explicitRegistry ? [`--registry=${registry}`] : []), '--package=@o8-fixture/check-connection@1.0.0', 'o8-registry-mcp'], - env: { O8_FIXTURE_RECEIPT: receipt, ...env } } }), - })); - expect(response.status).toBe(200); - return response.json() as Promise<{ ok: boolean; toolCount?: number; stderr?: string; error?: string }>; -} -function successful(result: { ok: boolean; toolCount?: number; stderr?: string; error?: string }, receipt: string) { - expect(result.ok, result.stderr ?? result.error).toBe(true); expect(result.toolCount).toBe(1); - expect(requests.some(req => req.url.endsWith('.tgz') && req.authenticated)).toBe(true); - expect(requests.every(req => req.status === 200)).toBe(true); - const observed = JSON.parse(readFileSync(receipt, 'utf8')) as { config: Record; blockedPresent: boolean }; - expect(observed.blockedPresent, 'unapproved parent values reached the npx-launched MCP server').toBe(false); - return observed; -} - -it('uses explicit npm configuration to authenticate a real npx Check connection', async () => { - const f = fixture(); successful(await check(f.receipt, { NPM_CONFIG_USERCONFIG: f.userconfig }), f.receipt); -}, 30_000); - -it.each(['NPM_CONFIG_USERCONFIG', 'npm_config_userconfig', 'NPM_CONFIG_GLOBALCONFIG', 'npm_config_globalconfig'])( - 'keeps ambient %s for a real private-registry npx Check connection', async name => { - const f = fixture(); - if (/globalconfig/i.test(name)) { writeFileSync(f.userconfig, ''); writeFileSync(f.globalconfig, f.auth, { mode: 0o600 }); } - vi.stubEnv(name, /globalconfig/i.test(name) ? f.globalconfig : f.userconfig); - successful(await check(f.receipt), f.receipt); - }, 30_000, -); - -it.each(['NPM_CONFIG_REGISTRY', 'npm_config_registry'])( - 'keeps ambient %s instead of the denied loopback fallback', async name => { - const f = fixture(); vi.stubEnv(name, registry); - successful(await check(f.receipt, { NPM_CONFIG_USERCONFIG: f.userconfig }, false), f.receipt); - }, 30_000, -); - -it('keeps npm cache, prefix, proxy, CA and fetch settings without allowing arbitrary npm exports', async () => { - const f = fixture(); - const values: Record = { userconfig: f.userconfig, globalconfig: f.globalconfig, registry, - cache: path.join(f.root, 'cache'), prefix: path.join(f.root, 'prefix'), - proxy: registry, https_proxy: registry, noproxy: '127.0.0.1', ca: '', cafile: path.join(f.root, 'ca.pem'), strict_ssl: 'true', - fetch_retries: '0', fetch_retry_factor: '2', fetch_retry_mintimeout: '10', fetch_retry_maxtimeout: '20', fetch_timeout: '5000', - offline: 'false', prefer_offline: 'false', prefer_online: 'true' }; - for (const [key, value] of Object.entries(values)) vi.stubEnv(`NPM_CONFIG_${key.toUpperCase()}`, value); - const observed = successful(await check(f.receipt), f.receipt); - for (const [key, value] of Object.entries(values)) expect(observed.config[`npm_config_${key}`], key).toBe(value); - expect(existsSync(path.join(f.root, 'cache', '_cacache'))).toBe(true); -}, 30_000); - -it('fails with a real registry 401 when configuration has no credentials', async () => { - const f = fixture(); writeFileSync(f.userconfig, ''); - const result = await check(f.receipt, { NPM_CONFIG_USERCONFIG: f.userconfig }); - expect(result.ok).toBe(false); expect(result.stderr).toContain('401'); - expect(requests.some(req => req.status === 401 && !req.authenticated)).toBe(true); - expect(existsSync(f.receipt)).toBe(false); -}, 30_000); +afterAll(() => rmSync(f.root, { recursive: true, force: true })); it('still removes saved provider material renamed to an approved npm configuration key', async () => { - fixture(); vi.stubEnv('O8_MASTER_KEY', randomBytes(32).toString('base64url')); + vi.stubEnv('O8_MASTER_KEY', randomBytes(32).toString('base64url')); const { mutateProviderKey } = await import('@/lib/providers/key-store'); const { execFileSync } = await import('@/lib/providers/child-process'); const saved = randomBytes(24).toString('hex'); mutateProviderKey('OPENAI_API_KEY', { key: saved }); vi.stubEnv('NPM_CONFIG_CACHE', saved); try { expect(execFileSync(process.execPath, ['-e', 'process.stdout.write(String("NPM_CONFIG_CACHE" in process.env))'], { encoding: 'utf8' })).toBe('false'); - } finally { mutateProviderKey('OPENAI_API_KEY', { key: null }); } + } finally { mutateProviderKey('OPENAI_API_KEY', { key: null }); vi.unstubAllEnvs(); } }); diff --git a/tests/workspace-preservation-cli-real-path.test.ts b/tests/workspace-preservation-cli-real-path.test.ts index 0726865b97..aa0ede160a 100644 --- a/tests/workspace-preservation-cli-real-path.test.ts +++ b/tests/workspace-preservation-cli-real-path.test.ts @@ -1,7 +1,7 @@ import { execFileSync, spawn } from 'node:child_process'; import { createHash } from 'node:crypto'; import { createServer, type Server } from 'node:http'; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; @@ -652,31 +652,6 @@ describe('workspace preservation compiled CLI and persisted owner', () => { finished = true; }, 30_000); - it('refuses newer ignored content when replaying discard from its old retiring archive', async () => { - finished = false; - const repo = await addRepo(repoPath); - const source = await ownedWorkspace(repo, 'preservation-discard-replay', 'main'); - mkdirSync(path.join(source.workspacePath, '.o8')); - const proof = path.join(source.workspacePath, '.o8', 'proof.bin'); - writeFileSync(proof, Buffer.from([0, 255, 81]), { mode: 0o400 }); - const { prepareWorkspaceMaterializationRetirement } = await import('@/lib/workspace/workspace-materialization-retirement'); - await prepareWorkspaceMaterializationRetirement(repo.localPath, source.workspacePath, 'discard'); - expect(getWorkspaceSnapshot(repo.id, 'preservation-discard-replay')?.state).toBe('retiring'); - chmodSync(proof, 0o600); - const newer = Buffer.from([9, 255, 0, 82]); - writeFileSync(proof, newer); - writeFileSync(path.join(source.workspacePath, '.o8', 'newer-note.md'), 'Newer unique recovery bytes.'); - closeDb(); - const { discardExactManagedWorktree } = await import('@/lib/workspace/exact-discard'); - const { probeOwnedSessionProcessQuiescence } = await import('@/lib/workspace/process-probes'); - await expect(discardExactManagedWorktree({ lane: source.lane, worktreeId: source.worktreeId, - isolationKind: 'git-worktree', processProbe: probeOwnedSessionProcessQuiescence })).rejects.toThrow(); - expect(readFileSync(proof)).toEqual(newer); - expect(readFileSync(path.join(source.workspacePath, '.o8', 'newer-note.md'), 'utf8')).toBe('Newer unique recovery bytes.'); - expect(git(source.workspacePath, 'rev-parse', 'HEAD')).toBe(git(repo.localPath, 'rev-parse', 'main')); - finished = true; - }, 30_000); - it('keeps an earlier rolled-back archive historical after confirmed missing-source cleanup', async () => { finished = false; const repo = await addRepo(repoPath); From 08a0f3b5b586d87734d416632995900b2fe4982f Mon Sep 17 00:00:00 2001 From: LavonTMCQ Date: Fri, 20 Nov 2026 22:12:52 -0500 Subject: [PATCH 2/3] test: bind dossier read fixture to its packet project --- tests/principal-authz.test.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/principal-authz.test.ts b/tests/principal-authz.test.ts index 05d01edd88..be595c220a 100644 --- a/tests/principal-authz.test.ts +++ b/tests/principal-authz.test.ts @@ -473,7 +473,18 @@ describe('principal-authz — recurring problem dossiers are worker-readable onl const url = 'http://localhost:3001/api/panel/problem-dossiers?includeSuppressed=true'; it('WORKER GET passes the capability gate and reaches the production route', async () => { - const request = req(url, { principal: 'worker', method: 'GET' }); + const { createLane } = await import('@/lib/lane/registry'); + const packetId = 'pkt-problem-dossier-reader'; + createLane({ + label: 'Problem dossier reader', + packetId, + projectId: 'problem-dossier-fixture', + repoPath: dataDir, + branch: 'fixture/problem-dossier-reader', + baseBranch: 'main', + runtime: 'codex', + }); + const request = req(url, { principal: 'worker', method: 'GET', workerToken: mintPacketWorkerToken(packetId) }); expect(panelGateMiddleware(request).status).toBe(200); const response = await problemDossiers.GET(request); From 08a0fe5e9d891d1638a1ee2850593188c8bb6e71 Mon Sep 17 00:00:00 2001 From: LavonTMCQ Date: Fri, 20 Nov 2026 22:25:37 -0500 Subject: [PATCH 3/3] test: keep the fixture HTTP server responsive during CLI calls --- tests/terminal-visibility-real-path.test.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/terminal-visibility-real-path.test.ts b/tests/terminal-visibility-real-path.test.ts index 3e2f7ab09b..ac9342b1ec 100644 --- a/tests/terminal-visibility-real-path.test.ts +++ b/tests/terminal-visibility-real-path.test.ts @@ -4,6 +4,7 @@ import { createServer, type Server } from 'node:http'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { promisify } from 'node:util'; import { WebSocket } from 'ws'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { dashSessionNameForOwnerKey, dashTmuxArgs } from '@/lib/ws-server/dash-terminal-persistence'; @@ -600,20 +601,20 @@ describe.runIf(tmuxAvailable)('terminal visibility through the real WebSocket an O8_API_TOKEN: token, }; delete cliEnv.O8_WORKER_TOKEN; - const cli = (...args: string[]) => execFileSync( + const cli = (...args: string[]) => promisify(execFile)( process.execPath, [cliBundle, 'terminal', ...args], { cwd: process.cwd(), env: cliEnv, encoding: 'utf8', timeout: 15_000 }, - ); - const listed = JSON.parse(cli('list')) as { sessions: Array<{ id: string }> }; + ).then(({ stdout }) => stdout); + const listed = JSON.parse(await cli('list')) as { sessions: Array<{ id: string }> }; expect(listed.sessions.some((session) => session.id === cliSessionName)).toBe(true); - const snapshot = JSON.parse(cli('show', cliSessionName, '--lines', '80')) as { + const snapshot = JSON.parse(await cli('show', cliSessionName, '--lines', '80')) as { session: { id: string; cols: number; rows: number }; text: string; }; expect(snapshot.session.id).toBe(cliSessionName); expect(snapshot.session.cols).toBeGreaterThan(0); expect(snapshot.text).toContain('O8_CLI_BEFORE_RESTART'); - const oneLine = JSON.parse(cli('show', cliSessionName, '--lines', '1')) as { text: string }; + const oneLine = JSON.parse(await cli('show', cliSessionName, '--lines', '1')) as { text: string }; expect(oneLine.text.trimEnd().split('\n')).toHaveLength(1); const observed = spawn(process.execPath, [