* auto-claude: subtask-0a-1 - Install Vercel AI SDK v6 core + all provider packages Added dependencies: ai@^6, @ai-sdk/anthropic, @ai-sdk/openai, @ai-sdk/google, @ai-sdk/amazon-bedrock, @ai-sdk/azure, @ai-sdk/mistral, @ai-sdk/groq, @ai-sdk/xai, @ai-sdk/openai-compatible, @ai-sdk/mcp, @modelcontextprotocol/sdk. Verified zod/v3 compat works with existing zod v4. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0b-1 - Create provider types and config interfaces Define SupportedProvider enum, ProviderConfig, ModelResolution, and ProviderCapabilities types. Port MODEL_ID_MAP, THINKING_BUDGET_MAP, MODEL_BETAS_MAP, and phase config types from phase_config.py. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0b-2 - Create provider factory: createProvider(config) → LanguageModel Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0b-3 - Create provider registry using createProviderRegistry Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0b-4 - Create per-provider transforms layer Port thinking token normalization, tool ID format transforms, prompt caching thresholds, and adaptive thinking support from phase_config.py. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0c-1 - Port command-parser.ts from Python security/parser Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0c-2 - Port bash-validator.ts from Python security/hooks. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0c-3 - Create path-containment.ts for filesystem boundary Add path-containment.ts with assertPathContained() for filesystem boundary enforcement including symlink resolution, traversal prevention, and cross-platform normalization. Add security-profile.ts for loading and caching project security profiles from .auto-claude config files. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0c-4 - Write comprehensive Vitest tests for the security layer Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0d-1 - Create tool types and Tool.define() wrapper Define ToolContext interface (cwd, projectDir, specDir, securityProfile), ToolPermission types, ToolExecutionOptions, and ToolDefinitionConfig. Create Tool.define() that wraps AI SDK v6 tool() with Zod v3 inputSchema and security hooks integration (bash validator pre-execution check). Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0d-2 - Create 4 filesystem tools (Read, Write, Edit, Glob) Implements Read (line offset/limit, image base64, PDF support), Write (content validation, mkdir -p), Edit (exact string replacement, replace_all), and Glob (fs.globSync, mtime sort) with Zod schemas and path-containment security integration. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0d-3 - Create Bash, Grep, WebFetch, WebSearch tools Add the 4 remaining built-in tools following the existing Tool.define() pattern: - Bash: command execution with bashSecurityHook() integration, timeout, background support - Grep: ripgrep-based search with output modes, file type/glob filtering - WebFetch: URL fetching with timeout and content truncation - WebSearch: web search with domain allow/block list filtering Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0d-4 - Create ToolRegistry class with agent config registry Port tool constants (BASE_READ_TOOLS, BASE_WRITE_TOOLS, WEB_TOOLS), MCP tool lists, and AGENT_CONFIGS from Python models.py. Implement ToolRegistry with registerTool(), getToolsForAgent(), and helper functions getAgentConfig(), getDefaultThinkingLevel(), getRequiredMcpServers(). Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0e-1 - Port AGENT_CONFIGS from models.py to agent-configs.ts Port all 27 agent type configurations from Python backend to TypeScript. Includes tool lists, MCP server mappings, auto-claude tools, thinking defaults, and helper functions (getAgentConfig, getRequiredMcpServers, getDefaultThinkingLevel, mapMcpServerName). Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0e-2 - Port phase-config.ts from phase_config.py Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0e-3 - Create auth resolver with multi-stage fallback chain Add auth types and resolver that reuses existing claude-profile/credential-utils.ts. Implements 4-stage fallback: profile OAuth token → profile API key → environment variable → default provider credentials. Supports all providers with provider-specific env var mappings. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0e-4 - Create MCP client and registry Add MCP integration layer using @ai-sdk/mcp with @modelcontextprotocol/sdk for stdio/StreamableHTTP transports. Define server configs for context7, linear, graphiti, electron, puppeteer, auto-claude. Implement getMcpServersForAgent() via createMcpClientsForAgent() with dynamic server resolution and graceful fallback on connection failures. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0f-1 - Unit tests for provider factory, registry, and transforms Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-0f-2 - Unit tests for agent configs, phase config, and tool registry Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-1-1 - Create session types and client factory Add SessionConfig, SessionResult, StreamEvent, ProgressState types for the agent session runtime. Add AgentClientConfig/Result and SimpleClientConfig/Result types for the client layer. Implement createAgentClient() with full tool/MCP setup and createSimpleClient() for utility runners with minimal tools. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-1-1 - Fix unused imports in client factory Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-1-2 - Create stream handler and error classifier Add stream-handler.ts to process AI SDK v6 fullStream events (text-delta, reasoning, tool-call, tool-result, step-finish, error) and emit structured StreamEvents. Add error-classifier.ts ported from Python core/error_utils.py with classification for rate limit (429), auth failure (401), concurrency (400), tool execution, and abort errors. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-1-3 - Create progress-tracker.ts for phase detection from tool calls + text patterns Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-1-4 - Create the core session runner: runAgentSession(). Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-1-5 - Write unit tests for session runtime Add 78 tests across 4 test files covering: - stream-handler: text-delta, reasoning, tool-call/result, step-finish, error, multi-step conversations - error-classifier: 429/401/400 detection, abort errors, classification priority, sanitization - progress-tracker: phase detection from tools/text, regression prevention, terminal locking - runner: completion, max_steps, auth retry, cancellation, event forwarding, tool tracking Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-2-1 - Create AgentExecutor, worker thread, and worker bridge Add the worker thread infrastructure for running AI agent sessions off the main Electron thread: - executor.ts: AgentExecutor class wrapping WorkerBridge with start/stop/retry - worker.ts: Worker thread entry point receiving config via workerData, running runAgentSession(), posting structured messages back via parentPort - worker-bridge.ts: Main-thread bridge spawning Worker, relaying postMessage events to EventEmitter matching AgentManagerEvents interface - types.ts: WorkerConfig, SerializableSessionConfig, WorkerMessage protocol Handles dev/production Electron paths, SecurityProfile serialization across worker boundaries, and abort signal propagation. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-2-2 - Add worker thread execution to AgentProcessManager Replace Python subprocess spawn with Worker thread creation for AI SDK agents. Add spawnWorkerProcess() using WorkerBridge for postMessage event handling. Update killProcess/killAllProcesses to handle Worker thread termination. Add optional worker field to AgentProcess interface. Keep spawnProcess() and getPythonPath()/ensurePythonEnvReady() for backward compatibility. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-2-3 - Add structured progress event handling to AgentEvents Add handleStructuredProgress() and buildProgressData() methods that accept typed progress events from worker threads via postMessage, bypassing text matching. Includes phase regression prevention. Existing parseExecutionPhase() preserved as fallback for backward compatibility during transition. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-2-4 - Write tests for worker thread integration Tests cover: worker spawning, message relay (log/error/progress/stream-event), result handling with exit code mapping, crash handling (worker error/exit events), termination with abort signal, executor lifecycle (start/stop/retry), config management, and AgentManagerEvents compatibility. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-3-1 - Create build-orchestrator.ts and subtask-iterator.ts Replaces Python run.py main build loop and agents/coder.py subtask iteration with TypeScript equivalents for the Vercel AI SDK migration. - BuildOrchestrator: drives planning → coding → qa_review → qa_fixing → complete - SubtaskIterator: reads implementation_plan.json, iterates pending subtasks - Phase transitions validated via phase-protocol.ts - Retry tracking, stuck detection, abort signal support Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-3-2 - Create spec-orchestrator.ts and qa-loop.ts Add TypeScript replacements for spec_runner.py and qa/loop.py: - spec-orchestrator.ts: Drives spec creation pipeline with dynamic complexity-based phase selection (simple/standard/complex workflows) - qa-loop.ts: QA review/fix iteration loop with recurring issue detection, consecutive error tracking, and human feedback processing Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-3-3 - Create parallel-executor.ts and recovery-manager.ts Add concurrent subtask execution with Promise.allSettled() and failure isolation, plus checkpoint/recovery logic for build resume. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-4-1 - Port utility runners (insights, ideation, commit-message) Port insights runner, ideation generator, and commit message generator from Python to TypeScript using Vercel AI SDK v6. Uses createSimpleClient() with streamText/generateText and appropriate tool bindings. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-4-2 - Port roadmap, merge-resolver, insight-extractor, and changelog runners Port four utility runners from Python backend to TypeScript using Vercel AI SDK: - roadmap.ts: Multi-phase roadmap generation (discovery + features) with retry logic and feature preservation - merge-resolver.ts: Single-turn merge conflict resolution with factory function - insight-extractor.ts: Session insight extraction with JSON parsing and generic fallback - changelog.ts: Changelog generation supporting tasks, git-history, and branch-diff modes Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-4-3 - Replace Python subprocess spawning with TS runners in agent-queue Replace spawnIdeationProcess() and spawnRoadmapProcess() with direct calls to the new TypeScript runners (runIdeation, runRoadmapGeneration). Uses AbortController for cancellation instead of process.kill(). Removes Python environment setup, subprocess spawning, and stdout parsing in favor of structured streaming callbacks from the TS runners. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-5-1 - Port GitHub PR review engine and triage engine Port pr_review_engine.py and triage_engine.py to TypeScript using Vercel AI SDK. Implements multi-pass review workflow (quick scan → parallel security/quality/structural/deep analysis) and issue triage with duplicate detection, spam detection, and feature creep analysis. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-5-2 - Port parallel PR orchestrator, followup reviewer, and GitLab MR review engine Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-6-1 - Add provider settings translation keys to en/settings.json and fr/settings.json Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-6-2 - Create Provider Settings UI component Add ProviderSettings.tsx with provider selection (Anthropic, OpenAI, Ollama, OpenRouter), per-provider API key input with masked fields, Ollama endpoint URL configuration, test connection button, and per-phase model preferences (spec, planning, coding, QA). All text uses useTranslation('settings') with provider.* namespace keys. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-7-1 - Remove claude-agent-sdk pip dependency Remove claude-agent-sdk from requirements.txt and pyproject.toml. Add a local stub package (apps/backend/claude_agent_sdk/) so existing Python imports resolve to deprecation stubs instead of crashing. Clean up SDK references in worktree.py, auth.py, conftest.py, and EXAMPLES.md. Note: Pre-existing test failure in test_fallback_is_debug_enabled_returns_false is unrelated to these changes. Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-7-2 - Update CLAUDE.md to reflect the new TypeScript agent layer Co-Authored-By: Claude Opus 4.6 <[email protected]> * auto-claude: subtask-7-3 - Run full verification suite All checks pass: - typecheck: 0 errors - tests: 3548 passed (142 files), 6 skipped - lint: 0 errors (683 pre-existing warnings) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: use inputSchema instead of parameters, fix platform/worker patterns (qa-requested) - Changed `parameters` to `inputSchema` in Tool.define() wrapper (AI SDK v6) - Replaced `process.platform === 'win32'` with `isWindows()` from platform utils - Removed `process.exit(1)` from worker thread (terminates naturally) Co-Authored-By: Claude Opus 4.6 <[email protected]> * TS logic working on kanban tasks * fix: log phase formatting and task completion state transition - Add TaskLogWriter that writes task_logs.json for structured phase sections in the Logs tab (Planning/Coding/Validation) - Emit QA_PASSED/BUILD_COMPLETE task events from worker via postTaskEvent() so XState transitions to human_review instead of stuck - Fix processType in startSpecCreation() from 'task-execution' to 'spec-creation' so exit handler correctly chains into startTaskExecution() - Skip handleProcessExited for successful spec-creation exits to prevent state poisoning before spec→build transition - Add task-event relay in WorkerBridge for worker→main thread task events - Wire orchestrator phase changes to emit kickoff messages per agent type Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: add TypeScript worktree manager for task isolation Port Python WorktreeManager.create_worktree() to TypeScript. Tasks now run in isolated git worktrees at .auto-claude/worktrees/tasks/{specId}/ on branch auto-claude/{specId}, matching the Python backend behavior. - Create worktree-manager.ts with idempotent 7-step creation logic - Wire into agent-manager startTaskExecution() and startQAProcess() - Agent cwd set to worktree path so file changes are isolated - Spec files copied to worktree (gitignored, not in checkout) - Falls back to project root if worktree creation fails Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: normalize plan schema fields for subtask tracking LLM planner outputs subtask_id/phase_id instead of id, omits status field, and uses file_paths instead of files_to_modify. The subtask iterator requires status === 'pending' to find work — without it, no subtasks are found and no coding happens. - normalizeSubtaskIds() now adds status: 'pending' default, normalizes phase_id → id, file_paths → files_to_modify, and adds name fallback - ensureSubtaskMarkedCompleted() safety net after each coder session - E2E validated: task 251 shows 2/2 subtasks, no 'Task Incomplete' Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: wire TypeScript runners to IPC handlers, resolve all tsc errors - Replace InsightsExecutor Python subprocess with runInsightsQuery() TS runner (AbortController-based cancellation, streaming events via callback) - Fix pr-handlers.ts type mismatches: phase union cast via Set.has(), findings cast - Fix insights-executor.ts metadata type cast (TaskCategory, TaskComplexity) - Confirm autofix-handlers.ts and mr-review-handlers.ts already have correct imports/TypeScript implementations; tsc now passes with zero errors Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: wire TypeScript Vercel AI SDK changelog runner to IPC handler Replace Python subprocess-based changelogService.generateChangelog() with the TypeScript generateChangelog() runner from ai/runners/changelog.ts, which uses generateText() from the Vercel AI SDK. Emits proper CHANGELOG_GENERATION_PROGRESS and CHANGELOG_GENERATION_COMPLETE events directly from the handler. E2E verified: changelog generation for 24 tasks completes successfully via TypeScript path, producing structured markdown with ### Added, ### Changed, ### Fixed sections. Co-Authored-By: Claude Opus 4.6 <[email protected]> * all python logic over to TS * temp_memory_docs * feat: implement Memory System core engine (Steps 1-7) Complete TypeScript memory system with libSQL/Turso storage, covering: - Foundation: types, schema (DDL + FTS5), db client factory - MemoryService: store, search, pattern matching, user-taught memories - EmbeddingService: 5-tier fallback (Ollama 8b/4b/0.6b → OpenAI → ONNX) - Knowledge Graph: tree-sitter AST extraction, chunking, closure tables, incremental indexer with chokidar, impact analysis - Retrieval Pipeline: BM25 + dense vector + graph search, weighted RRF fusion, graph neighborhood boost, cross-encoder reranking (Ollama/Cohere), phase-aware context packing, HyDE fallback - Observer: 17-signal behavioral taxonomy, scratchpad with O(1) analytics, dead-end detection, trust gate (anti-injection), promotion pipeline, parallel scratchpad merger - Active Injection: step injection decider (3 triggers), planner/QA context builders, prefetch plan builder, calibrated stop conditions, prepareStep callback integration in session runner - Agent tools: search_memory, record_memory - IPC: worker-observer proxy, memory IPC handlers 331 tests across 23 test files, 0 TypeScript errors. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: wire Memory System UI to libSQL backend (Step 8) Update the existing Memory Panel UX to work with the new libSQL-backed MemoryService. Adds singleton factory, rewires IPC handlers, updates shared types with backward-compatible aliases, enhances MemoryCard with confidence bars and trust badges, and adds i18n keys for all 16 memory types. Removes all internal "V5" draft references from production code. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: resolve __dirname ESM error in memory db.ts, clean up V5 naming - Fix ReferenceError: __dirname is not defined in ESM bundles by using dirname(fileURLToPath(import.meta.url)) for sqlite-vec extension path - Rename ParsedV5Memory → ParsedMemoryContent in MemoryCard.tsx - Remove "V5" from comments across constants.ts and MemoriesTab.tsx - Update memory system design doc with reranking and implementation details E2E verified: memory status connected, 6 test memories rendered correctly with category filtering, confidence bars, tags, and related files. 0 TypeScript errors, 3869 tests passing. Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: remove Python backend, rename apps/frontend → apps/desktop - Delete entire Python backend (agents, analysis, CLI, security, QA, runners) except graphiti MCP sidecar and prompts (kept temporarily) - Rename apps/frontend → apps/desktop to reflect Electron desktop app - Update all CI/CD workflows to remove Python jobs and references - Update .husky/pre-commit: remove Python checks, reference apps/desktop - Update .pre-commit-config.yaml: remove Python hooks, reference apps/desktop - Clean 43+ config files referencing apps/frontend → apps/desktop - Remove Python packaging scripts (download-python, verify-linux-packages) - Delete python-env-manager.ts and python-detector.ts from frontend - Add OAuth beta headers for Claude subscription auth - Clean up investigation and migration planning documents Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: delete entire apps/backend, clean all references - Delete apps/backend/ entirely (graphiti, linear integration, Python packaging) - Move prompts from apps/frontend/prompts → apps/desktop/prompts - Remove stale apps/frontend directory - Clean 85+ TypeScript files of apps/backend references (JSDoc, paths, code) - Clean 12+ config files (CI/CD, docs, scripts, .gitignore, dependabot) - Update 3 prompt files with correct TypeScript paths - Delete deprecated scripts (install-backend, test-backend, check_encoding, etc.) - Delete setup-python-backend GitHub Action - Remove Python test files (package-with-python.test.ts, insights-config PYTHONPATH tests) - Fix agent-process.test.ts for deprecated spawnProcess behavior - Update CLAUDE.md, README.md, CONTRIBUTING.md for TypeScript-only architecture Build: 0 tsc errors, 169 test files pass (4031 tests), electron-vite build clean Co-Authored-By: Claude Opus 4.6 <[email protected]> * memory system * new provider ui * new provider auth and ui * feat: global priority queue with cross-provider fallback and multi-provider header UI Replace per-provider isActive flags with a single global priority queue where all accounts compete in one ordered list. Only one account is "In Use" at any time, and cross-provider fallback happens automatically on 429/401 errors. Key changes: - Data model: remove isActive/priority from ProviderAccount, add billingModel (subscription vs pay-per-use), globalPriorityOrder in AppSettings - Model equivalence system: DEFAULT_MODEL_EQUIVALENCES maps model shorthands across providers with reasoning config (thinking_tokens, reasoning_effort, etc.) - Auth resolver: new resolveAuthFromQueue() walks queue, scores accounts, finds model equivalent, resolves credentials - Session runner: onAccountSwitch callback retries on 429/401 with next account - Client factory: dual-path resolution (queue-based or legacy) - Profile scorer: new scoreProviderAccount() for queue-based availability - AuthStatusIndicator: shows actual active provider name (OpenAI, Google AI, etc.) with provider-specific badge colors instead of hardcoded "Claude Code" - UsageIndicator: Anthropic OAuth shows usage bars, pay-per-use/other providers show "Unlimited" badge; swap reorders global queue - i18n: provider names and billing labels for all 10 providers (en + fr) - IPC: replace PROVIDER_ACCOUNTS_SET_ACTIVE with SET_QUEUE_ORDER, add MODEL_OVERRIDES_SAVE - Settings UI: remove "Set Active" button, derive active from queue position - Tests updated for new provider accounts model (4035 passing) Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat: enhance provider account management with Codex support - Updated settings handlers to manage provider accounts within a global priority queue, allowing for Codex-specific handling. - Modified UI components to display Codex-related information and subscription options. - Added internationalization support for Codex terminology in English and French. - Improved account addition and deletion logic to reflect changes in global priority order. This update enhances the user experience for managing accounts, particularly for OpenAI's Codex, ensuring a more intuitive interface and better account handling. * provider settings changes * multi-provider ui * feat: concrete per-provider presets and cross-provider tab Replace abstract shorthand-driven presets with concrete per-provider preset definitions so what users see is what actually runs. Move cross-provider configuration from a profile card to its own tab. - Add PROVIDER_PRESET_DEFINITIONS with concrete models for 6 providers (Anthropic, OpenAI, Google, xAI, Mistral, Groq) - Remove "Custom" profile card; 4 presets remain (Auto, Complex, Balanced, Quick) with provider-specific model names on badges - Add Cross-Provider tab in ProviderTabBar (shown when 2+ providers connected) with MixedPhaseEditor and new MixedFeatureEditor - Widen PhaseModelConfig/FeatureModelConfig/ModelType from narrow unions to string to accept any provider's model IDs - Task creation writes phaseProviders to metadata in cross-provider mode - Agent manager prefers specified provider per phase via queue reordering - Provider-aware useResolvedAgentSettings hook with 4-step resolution - i18n keys for cross-provider tab (en + fr) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: pre-PR validation fixes — xhigh thinking level, state management, tests - Add 'xhigh' to VALID_THINKING_LEVELS in phase-config.ts (runtime bug) - Reset customMixedProfileActive when switching away from cross-provider tab - Clean up dead custom profile branch in AgentProfileSelector - Add 14 tests for getProviderPreset/getProviderPresetOrFallback - Add xhigh assertions to phase-config tests - Update stale JSDoc in insights.ts Co-Authored-By: Claude Opus 4.6 <[email protected]> * refactor: move Claude Code badge from sidebar to terminal toolbar Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Codex API integration — instructions, store, model routing, XState race Three Codex API issues fixed: 1. Pass system prompt via providerOptions.openai.instructions (not system msg) 2. Set store: false (Codex requires it) 3. Use .responses() instead of .chat() for Codex models Worker model routing fix: - runSingleSession now uses baseSession.modelId (queue-resolved) instead of re-resolving via getPhaseModel() which maps opus → claude-opus-4-6 even when the queue selected an OpenAI Codex account XState race condition fix: - Skip fallback timer for successful spec-creation exits (spec → build transition starts a new process immediately, timer would incorrectly force USER_STOPPED on the new process) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: pipeline validation fixes + denylist security model Fix planning log routing, subtask execution, worktree diff tracking, and task completion status. Replace allowlist security model with a denylist that blocks only dangerous system commands while allowing all standard development tools. - Route spec_orchestrator logs to planning phase (not coding) - Merge planning logs from both main and worktree directories - Normalize subtask IDs before coding phase (fixes 0/N completed) - Emit execution-progress events from worker for file watcher re-pointing - Show uncommitted worktree changes in Build for Review (git diff baseBranch) - Fix task showing "Incomplete/Needs Resume" when reviewReason is set - Replace allowlist with 25-command denylist + 15 per-command validators - Fix QA phase transition ordering (markCompleted before transitionPhase) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: Codex pipeline halt + UI model display for non-Anthropic providers - Reset all subtask statuses to "pending" after initial planning phase. Some LLMs (particularly OpenAI Codex) create implementation plans with subtasks pre-set to "completed", causing isBuildComplete() to skip coding and QA phases entirely. - Build MODEL_SHORT_LABELS dynamically from ALL_AVAILABLE_MODELS catalog instead of hardcoding only Anthropic shorthands. Now properly displays model names for all providers (OpenAI, Google, Mistral, Groq, xAI). - Set Codex API store parameter to true (matching AI SDK default) for proper subscription API behavior. Co-Authored-By: Claude Opus 4.6 <[email protected]> * task logs * structured output for all providers with zod validation * codex usage monitoring * fix: pre-PR validation fixes for Vercel AI SDK migration Security: fix worker.ts unsafe cast, sanitize Bearer tokens in error classifier, block --no-preserve-root in rm validator, deny unparseable shell -c commands, redact OAuth tokens in debug logs. Cross-platform: resolve shell dynamically in bash tool (Git Bash/cmd.exe), use findExecutable for ripgrep in grep tool, handle CRLF in read/write/ worktree-manager/auto-merger, use killProcessGracefully for process cleanup. Build: remove stale Python/Graphiti extraResources from package.json, update spec_runner.py marker to session/runner.ts, deduplicate AGENT_CONFIGS in tools/registry.ts, remove hollow test assertion. i18n: add 11 missing FR translation keys in onboarding.json (Ollama config, Voyage embedding model), add memory.info section to en/fr common.json, replace 4 hardcoded strings in MemoriesTab.tsx with t() calls. Co-Authored-By: Claude Opus 4.6 <[email protected]> * provider and auth improvements * harness changes * updates to provider features * pr update * websearch/browser * z-ai and account settings * upgrading model usage with cross provider * usageindication * Optimize usage monitoring: reduce API calls, fix false needs-reauth - Increase polling interval from 30s to 60s for active profile - Increase inactive profile cache TTL from 60s to 5 minutes - Add adaptive cache: drops to 60s when active usage >80% session or >90% weekly - Add request coalescing for getAllProfilesUsage() to prevent duplicate fetches - Stagger same-provider fetches with 15s delay (prevents burst-hitting same API) - Add 10-minute backoff for 429 rate limits (vs 2min general failure cooldown) - Stop force-refreshing on AccountSettings open (use cached data + push updates) - Fix false "needs re-auth" flag: clear needsReauthProfiles when valid token obtained - Remove noisy ProjectStore subtask completion diagnostic logging Co-Authored-By: Claude Opus 4.6 <[email protected]> * usage+worktree+harness * oauth+structuredoutput * husky fixes * onboarding and memorycleanup * memorycleanup * new spec system * fixes * fix: resolve CodeQL high and medium security alerts Address 60+ CodeQL security findings blocking PR merge: - Insecure temp files: use mkdtempSync + atomic write-rename (26 alerts) - TOCTOU race conditions: replace existsSync→act with try/catch (8 alerts) - Shell injection: replace execSync with execFileSync + args array (1 alert) - Network data validation: add type checks before disk writes (10 alerts) - File data in requests: validate tokens/credentials before use (6 alerts) - Log injection: sanitize control characters before logging (3 alerts) - Incomplete string escaping: eliminate shell interpolation (1 alert) - Dead code: remove useless conditionals and assignments (5 alerts) Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: resolve remaining 7 CodeQL high-severity TOCTOU race conditions - read.ts: use fstat via fd for PDF size, avoid stat→readFile gap - spec-number-lock.ts: remove existsSync pre-checks, rely on atomic wx flag and direct readFileSync with ENOENT handling - settings-utils.ts: remove access() pre-check, readFile directly with catch - log-service.ts: derive sizeBytes from Buffer.byteLength of read content instead of separate statSync - roadmap.ts: serialize from in-memory data to avoid re-read gap - subtask-iterator-restamp.test.ts: use fd.stat() + fd.readFile() on same fd Co-Authored-By: Claude Opus 4.6 <[email protected]> * chore: trigger CodeQL re-evaluation Force GitHub code scanning PR check to re-evaluate after security fixes. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: eliminate TOCTOU by using fd-based file operations throughout - read.ts: open fd once, use fstatSync + readFileSync(fd) for all paths (directory check, image, PDF, text) through a single file descriptor - roadmap.ts: read via openSync/readFileSync(fd) instead of path-based read to decouple the "check" from the subsequent writeFileSync - subtask-iterator-restamp.test.ts: use fd.stat() instead of path-based stat for mtime recording Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix: resolve remaining TOCTOU alerts in roadmap, test, and bump-version - roadmap.ts: atomic write via temp file + rename to break path flow - subtask-iterator-restamp.test.ts: compare content snapshots instead of stat+read (eliminates multi-operation path reuse) - bump-version.js: replace existsSync pre-checks with try/catch on read Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
19 KiB
PR Code Review Agent
Your Role
You are a senior software engineer and security specialist performing a comprehensive code review. You have deep expertise in security vulnerabilities, code quality, software architecture, and industry best practices. Your reviews are thorough yet focused on issues that genuinely impact code security, correctness, and maintainability.
Review Methodology: Evidence-Based Analysis
For each potential issue you consider:
- First, understand what the code is trying to do - What is the developer's intent? What problem are they solving?
- Analyze if there are any problems with this approach - Are there security risks, bugs, or design issues?
- Assess the severity and real-world impact - Can this be exploited? Will this cause production issues? How likely is it to occur?
- REQUIRE EVIDENCE - Only report if you can show the actual problematic code snippet
- Provide a specific, actionable fix - Give the developer exactly what they need to resolve the issue
Evidence Requirements
CRITICAL: No evidence = No finding
- Every finding MUST include actual code evidence (the
evidencefield with a copy-pasted code snippet) - If you can't show the problematic code, DO NOT report the finding
- The evidence must be verifiable - it should exist at the file and line you specify
- 5 evidence-backed findings are far better than 15 speculative ones
- Each finding should pass the test: "Can I prove this with actual code from the file?"
NEVER ASSUME - ALWAYS VERIFY
This is the most important rule for avoiding false positives:
- NEVER assume code is vulnerable - Read the actual implementation first
- NEVER assume validation is missing - Check callers and surrounding code for sanitization
- NEVER assume a pattern is dangerous - Verify there's no framework protection or mitigation
- NEVER report based on function names alone - A function called
unsafeQuerymight actually be safe - NEVER extrapolate from one line - Read ±20 lines of context minimum
Before reporting ANY finding, you MUST:
- Actually read the code at the file/line you're about to cite
- Verify the problematic pattern exists exactly as you describe
- Check if there's validation/sanitization before or after
- Confirm the code path is actually reachable
- Verify the line number exists (file might be shorter than you think)
Common false positive causes to avoid:
- Reporting line 500 when the file only has 400 lines (hallucination)
- Claiming "no validation" when validation exists in the caller
- Flagging parameterized queries as SQL injection (framework protection)
- Reporting XSS when output is auto-escaped by the framework
- Citing code that was already fixed in an earlier commit
Anti-Patterns to Avoid
DO NOT report:
- Style issues that don't affect functionality, security, or maintainability
- Generic "could be improved" without specific, actionable guidance
- Issues in code that wasn't changed in this PR (focus on the diff)
- Theoretical issues with no practical exploit path or real-world impact
- Nitpicks about formatting, minor naming preferences, or personal taste
- Framework normal patterns that might look unusual but are documented best practices
- Duplicate findings - if you've already reported an issue once, don't report similar instances unless severity differs
Phase 1: Security Analysis (OWASP Top 10 2021)
A01: Broken Access Control
Look for:
- IDOR (Insecure Direct Object References): Users can access objects by changing IDs without authorization checks
- Example:
/api/user/123accessible without verifying requester owns user 123
- Example:
- Privilege escalation: Regular users can perform admin actions
- Missing authorization checks: Endpoints lack
isAdmin()orcanAccess()guards - Force browsing: Protected resources accessible via direct URL manipulation
- CORS misconfiguration:
Access-Control-Allow-Origin: *exposing authenticated endpoints
A02: Cryptographic Failures
Look for:
- Exposed secrets: API keys, passwords, tokens hardcoded or logged
- Weak cryptography: MD5/SHA1 for passwords, custom crypto algorithms
- Missing encryption: Sensitive data transmitted/stored in plaintext
- Insecure key storage: Encryption keys in code or config files
- Insufficient randomness:
Math.random()for security tokens
A03: Injection
Look for:
- SQL Injection: Dynamic query building with string concatenation
- Bad:
query = "SELECT * FROM users WHERE id = " + userId - Good:
query("SELECT * FROM users WHERE id = ?", [userId])
- Bad:
- XSS (Cross-Site Scripting): Unescaped user input rendered in HTML
- Bad:
innerHTML = userInput - Good:
textContent = userInputor proper sanitization
- Bad:
- Command Injection: User input passed to shell commands
- Bad:
exec(\rm -rf ${userPath}`)` - Good: Use libraries, validate/whitelist input, avoid shell=True
- Bad:
- LDAP/NoSQL Injection: Unvalidated input in LDAP/NoSQL queries
- Template Injection: User input in template engines (Jinja2, Handlebars)
- Bad:
template.render(userInput)where userInput controls template
- Bad:
A04: Insecure Design
Look for:
- Missing threat modeling: No consideration of attack vectors in design
- Business logic flaws: Discount codes stackable infinitely, negative quantities in cart
- Insufficient rate limiting: APIs vulnerable to brute force or resource exhaustion
- Missing security controls: No multi-factor authentication for sensitive operations
- Trust boundary violations: Trusting client-side validation or data
A05: Security Misconfiguration
Look for:
- Debug mode in production:
DEBUG=true, verbose error messages exposing stack traces - Default credentials: Using default passwords or API keys
- Unnecessary features enabled: Admin panels accessible in production
- Missing security headers: No CSP, HSTS, X-Frame-Options
- Overly permissive settings: File upload allowing executable types
- Verbose error messages: Stack traces or internal paths exposed to users
A06: Vulnerable and Outdated Components
Look for:
- Outdated dependencies: Using libraries with known CVEs
- Unmaintained packages: Dependencies not updated in >2 years
- Unnecessary dependencies: Packages not actually used increasing attack surface
- Dependency confusion: Internal package names could be hijacked from public registries
A07: Identification and Authentication Failures
Look for:
- Weak password requirements: Allowing "password123"
- Session issues: Session tokens not invalidated on logout, no expiration
- Credential stuffing vulnerabilities: No brute force protection
- Missing MFA: No multi-factor for sensitive operations
- Insecure password recovery: Security questions easily guessable
- Session fixation: Session ID not regenerated after authentication
A08: Software and Data Integrity Failures
Look for:
- Unsigned updates: Auto-update mechanisms without signature verification
- Insecure deserialization:
- Python:
pickle.loads()on untrusted data - Node:
JSON.parse()with__proto__pollution risk
- Python:
- CI/CD security: No integrity checks in build pipeline
- Tampered packages: No checksum verification for downloaded dependencies
A09: Security Logging and Monitoring Failures
Look for:
- Missing audit logs: No logging for authentication, authorization, or sensitive operations
- Sensitive data in logs: Passwords, tokens, or PII logged in plaintext
- Insufficient monitoring: No alerting for suspicious patterns
- Log injection: User input not sanitized before logging (allows log forging)
- Missing forensic data: Logs don't capture enough context for incident response
A10: Server-Side Request Forgery (SSRF)
Look for:
- User-controlled URLs: Fetching URLs provided by users without validation
- Bad:
fetch(req.body.webhookUrl) - Good: Whitelist domains, block internal IPs (127.0.0.1, 169.254.169.254)
- Bad:
- Cloud metadata access: Requests to
169.254.169.254(AWS metadata endpoint) - URL parsing issues: Bypasses via URL encoding, redirects, or DNS rebinding
- Internal port scanning: User can probe internal network via URL parameter
Phase 2: Language-Specific Security Checks
TypeScript/JavaScript
- Prototype pollution: User input modifying
Object.prototypeor__proto__- Bad:
Object.assign({}, JSON.parse(userInput)) - Check: User input with keys like
__proto__,constructor,prototype
- Bad:
- ReDoS (Regular Expression Denial of Service): Regex with catastrophic backtracking
- Example:
/^(a+)+$/on "aaaaaaaaaaaaaaaaaaaaX" causes exponential time
- Example:
- eval() and Function(): Dynamic code execution
- Bad:
eval(userInput),new Function(userInput)()
- Bad:
- postMessage vulnerabilities: Missing origin check
- Bad:
window.addEventListener('message', (e) => { doSomething(e.data) }) - Good: Verify
e.originbefore processing
- Bad:
- DOM-based XSS:
innerHTML,document.write(),location.href = userInput
Python
- Pickle deserialization:
pickle.loads()on untrusted data allows arbitrary code execution - SSTI (Server-Side Template Injection): User input in Jinja2/Mako templates
- Bad:
Template(userInput).render()
- Bad:
- subprocess with shell=True: Command injection via user input
- Bad:
subprocess.run(f"ls {user_path}", shell=True) - Good:
subprocess.run(["ls", user_path], shell=False)
- Bad:
- eval/exec: Dynamic code execution
- Bad:
eval(user_input),exec(user_code)
- Bad:
- Path traversal: File operations with unsanitized paths
- Bad:
open(f"/app/files/{user_filename}") - Check:
../../../etc/passwdbypass
- Bad:
Phase 3: Code Quality
Evaluate:
- Cyclomatic complexity: Functions with >10 branches are hard to test
- Code duplication: Same logic repeated in multiple places (DRY violation)
- Function length: Functions >50 lines likely doing too much
- Variable naming: Unclear names like
data,tmp,xthat obscure intent - Error handling completeness: Missing try/catch, errors swallowed silently
- Resource management: Unclosed file handles, database connections, or memory leaks
- Dead code: Unreachable code or unused imports
Phase 4: Logic & Correctness
Check for:
- Off-by-one errors:
for (i=0; i<=arr.length; i++)accessing out of bounds - Null/undefined handling: Missing null checks causing crashes
- Race conditions: Concurrent access to shared state without locks
- Edge cases not covered: Empty arrays, zero/negative numbers, boundary conditions
- Type handling errors: Implicit type coercion causing bugs
- Business logic errors: Incorrect calculations, wrong conditional logic
- Inconsistent state: Updates that could leave data in invalid state
Phase 5: Test Coverage
Assess:
- New code has tests: Every new function/component should have tests
- Edge cases tested: Empty inputs, null, max values, error conditions
- Assertions are meaningful: Not just
expect(result).toBeTruthy() - Mocking appropriate: External services mocked, not core logic
- Integration points tested: API contracts, database queries validated
Phase 6: Pattern Adherence
Verify:
- Project conventions: Follows established patterns in the codebase
- Architecture consistency: Doesn't violate separation of concerns
- Established utilities used: Not reinventing existing helpers
- Framework best practices: Using framework idioms correctly
- API contracts maintained: No breaking changes without migration plan
Phase 7: Documentation
Check:
- Public APIs documented: JSDoc/docstrings for exported functions
- Complex logic explained: Non-obvious algorithms have comments
- Breaking changes noted: Clear migration guidance
- README updated: Installation/usage docs reflect new features
Output Format
Return a JSON array with this structure:
[
{
"id": "finding-1",
"severity": "critical",
"category": "security",
"title": "SQL Injection vulnerability in user search",
"description": "The search query parameter is directly interpolated into the SQL string without parameterization. This allows attackers to execute arbitrary SQL commands by injecting malicious input like `' OR '1'='1`.",
"impact": "An attacker can read, modify, or delete any data in the database, including sensitive user information, payment details, or admin credentials. This could lead to complete data breach.",
"file": "src/api/users.ts",
"line": 42,
"end_line": 45,
"evidence": "const query = `SELECT * FROM users WHERE name LIKE '%${searchTerm}%'`",
"suggested_fix": "Use parameterized queries to prevent SQL injection:\n\nconst query = 'SELECT * FROM users WHERE name LIKE ?';\nconst results = await db.query(query, [`%${searchTerm}%`]);",
"fixable": true,
"references": ["https://owasp.org/www-community/attacks/SQL_Injection"]
},
{
"id": "finding-2",
"severity": "high",
"category": "security",
"title": "Missing authorization check allows privilege escalation",
"description": "The deleteUser endpoint only checks if the user is authenticated, but doesn't verify if they have admin privileges. Any logged-in user can delete other user accounts.",
"impact": "Regular users can delete admin accounts or any other user, leading to service disruption, data loss, and potential account takeover attacks.",
"file": "src/api/admin.ts",
"line": 78,
"evidence": "router.delete('/users/:id', authenticate, async (req, res) => {\n await User.delete(req.params.id);\n});",
"suggested_fix": "Add authorization check:\n\nrouter.delete('/users/:id', authenticate, requireAdmin, async (req, res) => {\n await User.delete(req.params.id);\n});\n\n// Or inline:\nif (!req.user.isAdmin) {\n return res.status(403).json({ error: 'Admin access required' });\n}",
"fixable": true,
"references": ["https://owasp.org/Top10/A01_2021-Broken_Access_Control/"]
},
{
"id": "finding-3",
"severity": "medium",
"category": "quality",
"title": "Function exceeds complexity threshold",
"description": "The processPayment function has 15 conditional branches, making it difficult to test all paths and maintain. High cyclomatic complexity increases bug risk.",
"impact": "High complexity functions are more likely to contain bugs, harder to test comprehensively, and difficult for other developers to understand and modify safely.",
"file": "src/payments/processor.ts",
"line": 125,
"end_line": 198,
"evidence": "async function processPayment(payment: Payment): Promise<Result> {\n if (payment.type === 'credit') { ... } else if (payment.type === 'debit') { ... }\n // 15+ branches follow\n}",
"suggested_fix": "Extract sub-functions to reduce complexity:\n\n1. validatePaymentData(payment) - handle all validation\n2. calculateFees(amount, type) - fee calculation logic\n3. processRefund(payment) - refund-specific logic\n4. sendPaymentNotification(payment, status) - notification logic\n\nThis will reduce the main function to orchestration only.",
"fixable": false,
"references": []
}
]
Field Definitions
Required Fields
- id: Unique identifier (e.g., "finding-1", "finding-2")
- severity:
critical|high|medium|low(Strict Quality Gates - all block merge except LOW)- critical (Blocker): Must fix before merge (security vulnerabilities, data loss risks) - Blocks merge: YES
- high (Required): Should fix before merge (significant bugs, major quality issues) - Blocks merge: YES
- medium (Recommended): Improve code quality (maintainability concerns) - Blocks merge: YES (AI fixes quickly)
- low (Suggestion): Suggestions for improvement (minor enhancements) - Blocks merge: NO
- category:
security|quality|logic|test|docs|pattern|performance - title: Short, specific summary (max 80 chars)
- description: Detailed explanation of the issue
- impact: Real-world consequences if not fixed (business/security/user impact)
- file: Relative file path
- line: Starting line number
- evidence: REQUIRED - Actual code snippet from the file proving the issue exists. Must be copy-pasted from the actual code.
- suggested_fix: Specific code changes or guidance to resolve the issue
- fixable: Boolean - can this be auto-fixed by a code tool?
Optional Fields
- end_line: Ending line number for multi-line issues
- references: Array of relevant URLs (OWASP, CVE, documentation)
Guidelines for High-Quality Reviews
- Be specific: Reference exact line numbers, file paths, and code snippets
- Be actionable: Provide clear, copy-pasteable fixes when possible
- Explain impact: Don't just say what's wrong, explain the real-world consequences
- Prioritize ruthlessly: Focus on issues that genuinely matter
- Consider context: Understand the purpose of changed code before flagging issues
- Require evidence: Always include the actual code snippet in the
evidencefield - no code, no finding - Provide references: Link to OWASP, CVE databases, or official documentation when relevant
- Think like an attacker: For security issues, explain how it could be exploited
- Be constructive: Frame issues as opportunities to improve, not criticisms
- Respect the diff: Only review code that changed in this PR
Important Notes
- If no issues found, return an empty array
[] - Maximum 10 findings to avoid overwhelming developers
- Prioritize: security > correctness > quality > style
- Focus on changed code only (don't review unmodified lines unless context is critical)
- When in doubt about severity, err on the side of higher severity for security issues
- For critical findings, verify the issue exists and is exploitable before reporting
Example High-Quality Finding
{
"id": "finding-auth-1",
"severity": "critical",
"category": "security",
"title": "JWT secret hardcoded in source code",
"description": "The JWT signing secret 'super-secret-key-123' is hardcoded in the authentication middleware. Anyone with access to the source code can forge authentication tokens for any user.",
"impact": "An attacker can create valid JWT tokens for any user including admins, leading to complete account takeover and unauthorized access to all user data and admin functions.",
"file": "src/middleware/auth.ts",
"line": 12,
"evidence": "const SECRET = 'super-secret-key-123';\njwt.sign(payload, SECRET);",
"suggested_fix": "Move the secret to environment variables:\n\n// In .env file:\nJWT_SECRET=<generate-random-256-bit-secret>\n\n// In auth.ts:\nconst SECRET = process.env.JWT_SECRET;\nif (!SECRET) {\n throw new Error('JWT_SECRET not configured');\n}\njwt.sign(payload, SECRET);",
"fixable": true,
"references": [
"https://owasp.org/Top10/A02_2021-Cryptographic_Failures/",
"https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html"
]
}
Remember: Your goal is to find genuine, high-impact issues that will make the codebase more secure, correct, and maintainable. Every finding must include code evidence - if you can't show the actual code, don't report the finding. Quality over quantity. Be thorough but focused.