Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

v2.5.0 batch 3: codex helper layer (11 new files + 9 tests)

purple89ef62340fe3
diff --git a/src/api/agents/__tests__/architect.test.ts b/src/api/agents/__tests__/architect.test.ts
new file mode 100644
index 00000000..53306d1f
--- /dev/null
+++ b/src/api/agents/__tests__/architect.test.ts
@@ -0,0 +1,174 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const chatWithTools = vi.fn()
+
+vi.mock('../../providers', () => ({
+ getProviderForModel: (name: string) => ({
+ provider: { chatWithTools },
+ modelId: name.includes('::') ? name.split('::')[1] : name,
+ }),
+}))
+
+import {
+ planWithArchitect,
+ renderArchitectPlanSection,
+ ARCHITECT_SYSTEM_PROMPT,
+} from '../architect'
+
+describe('architect — renderArchitectPlanSection', () => {
+ it('returns empty string for empty / whitespace plans', () => {
+ expect(renderArchitectPlanSection('')).toBe('')
+ expect(renderArchitectPlanSection(' \n ')).toBe('')
+ })
+
+ it('wraps the plan in a marker the editor can anchor on', () => {
+ const out = renderArchitectPlanSection('## Plan\n1. Do X')
+ expect(out).toMatch(/^\n\nARCHITECT PLAN/)
+ expect(out).toMatch(/Do X/)
+ })
+
+ it('trims surrounding whitespace from the plan', () => {
+ const out = renderArchitectPlanSection('\n\n ## Plan \n\n')
+ expect(out).toMatch(/## Plan/)
+ expect(out.endsWith(' ')).toBe(false)
+ })
+})
+
+describe('architect — planWithArchitect', () => {
+ beforeEach(() => {
+ chatWithTools.mockReset()
+ })
+
+ it('calls the provider with an empty tools array', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'plan body', toolCalls: [] })
+ await planWithArchitect({
+ model: 'anthropic::claude-sonnet-4-5',
+ userInstruction: 'add a button',
+ workingDirectory: '/tmp/repo',
+ })
+ expect(chatWithTools).toHaveBeenCalledOnce()
+ const [, , tools] = chatWithTools.mock.calls[0]
+ expect(tools).toEqual([])
+ })
+
+ it('threads workingDirectory into the system prompt', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'plan body', toolCalls: [] })
+ await planWithArchitect({
+ model: 'ollama::qwen2.5-coder:32b',
+ userInstruction: 'refactor X',
+ workingDirectory: '/Users/me/repo',
+ })
+ const [, messages] = chatWithTools.mock.calls[0]
+ expect(messages[0].role).toBe('system')
+ expect(messages[0].content).toContain(ARCHITECT_SYSTEM_PROMPT)
+ expect(messages[0].content).toContain('Working directory: /Users/me/repo')
+ })
+
+ it('places the user instruction as the final message', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'plan body', toolCalls: [] })
+ await planWithArchitect({
+ model: 'anthropic::claude-sonnet-4-5',
+ userInstruction: 'add a button',
+ workingDirectory: '/tmp/repo',
+ })
+ const [, messages] = chatWithTools.mock.calls[0]
+ const last = messages[messages.length - 1]
+ expect(last).toEqual({ role: 'user', content: 'add a button' })
+ })
+
+ it('includes recent messages between system and user', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'plan body', toolCalls: [] })
+ await planWithArchitect({
+ model: 'anthropic::claude-sonnet-4-5',
+ userInstruction: 'continue',
+ workingDirectory: '/tmp/repo',
+ recentMessages: [
+ { role: 'user', content: 'earlier question' },
+ { role: 'assistant', content: 'earlier answer' },
+ ],
+ })
+ const [, messages] = chatWithTools.mock.calls[0]
+ expect(messages).toHaveLength(4) // system + 2 history + user
+ expect(messages[1].content).toBe('earlier question')
+ expect(messages[2].content).toBe('earlier answer')
+ })
+
+ it('defaults to deterministic temperature for plan stability', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'plan body', toolCalls: [] })
+ await planWithArchitect({
+ model: 'anthropic::claude-sonnet-4-5',
+ userInstruction: 'do',
+ workingDirectory: '/tmp',
+ })
+ const [, , , options] = chatWithTools.mock.calls[0]
+ expect(options.temperature).toBe(0.3)
+ })
+
+ it('passes through a caller-supplied temperature override', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'plan body', toolCalls: [] })
+ await planWithArchitect({
+ model: 'anthropic::claude-sonnet-4-5',
+ userInstruction: 'do',
+ workingDirectory: '/tmp',
+ temperature: 0.9,
+ })
+ const [, , , options] = chatWithTools.mock.calls[0]
+ expect(options.temperature).toBe(0.9)
+ })
+
+ it('trims the returned plan', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: ' \n## Plan\n ', toolCalls: [] })
+ const result = await planWithArchitect({
+ model: 'm',
+ userInstruction: 'i',
+ workingDirectory: '/',
+ })
+ expect(result.plan).toBe('## Plan')
+ })
+
+ it('echoes the chosen model name in the result', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'p', toolCalls: [] })
+ const result = await planWithArchitect({
+ model: 'anthropic::claude-opus-4-1',
+ userInstruction: 'i',
+ workingDirectory: '/',
+ })
+ expect(result.modelUsed).toBe('anthropic::claude-opus-4-1')
+ })
+
+ it('reports wall time as tookMs', async () => {
+ chatWithTools.mockImplementationOnce(async () => {
+ await new Promise((r) => setTimeout(r, 5))
+ return { content: 'p', toolCalls: [] }
+ })
+ const result = await planWithArchitect({
+ model: 'm',
+ userInstruction: 'i',
+ workingDirectory: '/',
+ })
+ expect(result.tookMs).toBeGreaterThanOrEqual(0)
+ })
+
+ it('handles null/undefined content from the provider as an empty plan', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: null, toolCalls: [] })
+ const result = await planWithArchitect({
+ model: 'm',
+ userInstruction: 'i',
+ workingDirectory: '/',
+ })
+ expect(result.plan).toBe('')
+ })
+
+ it('propagates the AbortSignal to the provider', async () => {
+ chatWithTools.mockResolvedValueOnce({ content: 'p', toolCalls: [] })
+ const ctrl = new AbortController()
+ await planWithArchitect({
+ model: 'm',
+ userInstruction: 'i',
+ workingDirectory: '/',
+ signal: ctrl.signal,
+ })
+ const [, , , options] = chatWithTools.mock.calls[0]
+ expect(options.signal).toBe(ctrl.signal)
+ })
+})
diff --git a/src/api/agents/__tests__/bg-tasks.test.ts b/src/api/agents/__tests__/bg-tasks.test.ts
new file mode 100644
index 00000000..352945b7
--- /dev/null
+++ b/src/api/agents/__tests__/bg-tasks.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backendCall = vi.fn()
+
+vi.mock('../../backend', () => ({
+ backendCall: (...args: unknown[]) => backendCall(...args),
+}))
+
+import {
+ bgStart,
+ bgStatus,
+ bgKill,
+ bgList,
+ renderBgStatusOneLine,
+ type BgTaskStatus,
+} from '../bg-tasks'
+
+beforeEach(() => backendCall.mockReset())
+
+describe('bgStart', () => {
+ it('rejects empty commands without hitting the bridge', async () => {
+ await expect(bgStart({ command: '' })).rejects.toThrow(/command is required/)
+ expect(backendCall).not.toHaveBeenCalled()
+ })
+
+ it('forwards command + optional cwd + shell to the bridge', async () => {
+ backendCall.mockResolvedValueOnce({ id: 'abc' })
+ await bgStart({ command: 'sleep 5', cwd: '/tmp', shell: 'bash' })
+ expect(backendCall).toHaveBeenCalledOnce()
+ expect(backendCall.mock.calls[0]).toEqual([
+ 'shell_task_start',
+ { command: 'sleep 5', cwd: '/tmp', shell: 'bash' },
+ ])
+ })
+})
+
+describe('bgStatus / bgKill / bgList — JSON shape pass-through', () => {
+ it('bgStatus returns the bridge payload verbatim', async () => {
+ const payload: BgTaskStatus = {
+ id: 'abc',
+ command: 'sleep 1',
+ cwd: null,
+ started_at: 100,
+ finished_at: 102,
+ exit_code: 0,
+ running: false,
+ cancelled: false,
+ output_tail: 'ok',
+ }
+ backendCall.mockResolvedValueOnce(payload)
+ expect(await bgStatus('abc')).toEqual(payload)
+ expect(backendCall.mock.calls[0]).toEqual(['shell_task_status', { id: 'abc' }])
+ })
+
+ it('bgKill returns the cancelled flag', async () => {
+ backendCall.mockResolvedValueOnce({ ok: true, cancelled: true })
+ const r = await bgKill('abc')
+ expect(r).toEqual({ ok: true, cancelled: true })
+ })
+
+ it('bgList returns the tasks array', async () => {
+ backendCall.mockResolvedValueOnce({ tasks: [] })
+ expect(await bgList()).toEqual({ tasks: [] })
+ })
+})
+
+describe('renderBgStatusOneLine', () => {
+ function makeStatus(overrides: Partial<BgTaskStatus> = {}): BgTaskStatus {
+ return {
+ id: 'abcdef1234567890',
+ command: 'sleep 5',
+ cwd: null,
+ started_at: 1700000000,
+ finished_at: null,
+ exit_code: null,
+ running: true,
+ cancelled: false,
+ output_tail: '',
+ ...overrides,
+ }
+ }
+
+ it('reports running with elapsed seconds for live tasks', () => {
+ const out = renderBgStatusOneLine(makeStatus())
+ expect(out).toMatch(/^\[abcdef12\]/)
+ expect(out).toMatch(/running/)
+ expect(out).toMatch(/sleep 5/)
+ })
+
+ it('reports ok for exit_code 0', () => {
+ const out = renderBgStatusOneLine(
+ makeStatus({ running: false, finished_at: 1700000005, exit_code: 0 }),
+ )
+ expect(out).toMatch(/ok/)
+ expect(out).toMatch(/\(5s\)/)
+ })
+
+ it('reports exit N for non-zero exits', () => {
+ const out = renderBgStatusOneLine(
+ makeStatus({ running: false, finished_at: 1700000010, exit_code: 2 }),
+ )
+ expect(out).toMatch(/exit 2/)
+ })
+
+ it('reports cancelled when the flag is set, regardless of exit_code', () => {
+ const out = renderBgStatusOneLine(
+ makeStatus({
+ running: false,
+ finished_at: 1700000010,
+ exit_code: null,
+ cancelled: true,
+ }),
+ )
+ expect(out).toMatch(/cancelled/)
+ })
+})
diff --git a/src/api/agents/__tests__/git-tools.test.ts b/src/api/agents/__tests__/git-tools.test.ts
new file mode 100644
index 00000000..a91af08c
--- /dev/null
+++ b/src/api/agents/__tests__/git-tools.test.ts
@@ -0,0 +1,169 @@
+import { describe, it, expect } from 'vitest'
+import {
+ parseGitStatus,
+ renderGitStatus,
+ parseGitLog,
+ shellQuote,
+ buildGitCommitCommand,
+ buildGhPrCreateCommand,
+} from '../git-tools'
+
+describe('parseGitStatus', () => {
+ it('reads branch + ahead/behind from porcelain v2 headers', () => {
+ const raw = [
+ '# branch.oid abc123',
+ '# branch.head feature/foo',
+ '# branch.upstream origin/feature/foo',
+ '# branch.ab +3 -1',
+ ].join('\n')
+ const r = parseGitStatus(raw)
+ expect(r.branch).toBe('feature/foo')
+ expect(r.ahead).toBe(3)
+ expect(r.behind).toBe(1)
+ expect(r.entries).toEqual([])
+ expect(r.clean).toBe(true)
+ })
+
+ it('reports detached HEAD as branch null', () => {
+ const raw = '# branch.head (detached)\n'
+ expect(parseGitStatus(raw).branch).toBeNull()
+ })
+
+ it('parses untracked files (??)', () => {
+ const raw = '# branch.head main\n? src/new.ts\n? README.md\n'
+ const r = parseGitStatus(raw)
+ expect(r.entries).toHaveLength(2)
+ expect(r.entries[0].path).toBe('src/new.ts')
+ expect(r.entries[0].code).toBe('??')
+ expect(r.entries[0].staged).toBe(false)
+ expect(r.clean).toBe(false)
+ })
+
+ it('parses staged + unstaged modifications and detects staged flag', () => {
+ const raw = [
+ '# branch.head main',
+ // Format: 1 XY <sub> <mH> <mI> <mW> <hH> <hI> <path>
+ '1 M. N... 100644 100644 100644 abc def src/a.ts',
+ '1 .M N... 100644 100644 100644 abc def src/b.ts',
+ ].join('\n')
+ const r = parseGitStatus(raw)
+ expect(r.entries).toHaveLength(2)
+ expect(r.entries[0].path).toBe('src/a.ts')
+ expect(r.entries[0].staged).toBe(true)
+ expect(r.entries[1].staged).toBe(false)
+ })
+
+ it('treats unmerged paths (u) as conflicts', () => {
+ const raw = '# branch.head main\nu UU N... 100644 100644 100644 100644 a b c src/conflict.ts\n'
+ const r = parseGitStatus(raw)
+ expect(r.entries).toHaveLength(1)
+ expect(r.entries[0].code).toBe('UU')
+ })
+})
+
+describe('renderGitStatus', () => {
+ it('reports a clean tree without bullet list noise', () => {
+ const text = renderGitStatus({
+ branch: 'main',
+ ahead: 0,
+ behind: 0,
+ entries: [],
+ clean: true,
+ })
+ expect(text).toMatch(/Working tree clean/)
+ })
+
+ it('lists per-file entries with their codes', () => {
+ const text = renderGitStatus({
+ branch: 'feat',
+ ahead: 2,
+ behind: 0,
+ entries: [
+ { code: '??', path: 'a', staged: false },
+ { code: 'M.', path: 'b', staged: true },
+ ],
+ clean: false,
+ })
+ expect(text).toMatch(/On branch feat \(ahead 2, behind 0\)/)
+ expect(text).toMatch(/\?\? a/)
+ expect(text).toMatch(/M\. b/)
+ })
+})
+
+describe('parseGitLog', () => {
+ it('extracts {sha, subject} pairs', () => {
+ const raw = ['a63ff74 E2E test pass — fix 6 UX bugs', '81587fa TEST-PLAN.md commit'].join('\n')
+ const r = parseGitLog(raw)
+ expect(r).toEqual([
+ { sha: 'a63ff74', subject: 'E2E test pass — fix 6 UX bugs' },
+ { sha: '81587fa', subject: 'TEST-PLAN.md commit' },
+ ])
+ })
+
+ it('skips empty lines and malformed rows', () => {
+ expect(parseGitLog('\n\nnot a commit\nabc1234 ok\n')).toEqual([
+ { sha: 'abc1234', subject: 'ok' },
+ ])
+ })
+})
+
+describe('shellQuote', () => {
+ it('wraps simple strings in single quotes', () => {
+ expect(shellQuote('hello')).toBe(`'hello'`)
+ })
+
+ it('escapes embedded single quotes', () => {
+ expect(shellQuote(`it's`)).toBe(`'it'\\''s'`)
+ })
+
+ it('keeps quoted variables literal', () => {
+ expect(shellQuote('$(rm -rf /)')).toBe(`'$(rm -rf /)'`)
+ })
+})
+
+describe('buildGitCommitCommand', () => {
+ it('returns empty for missing/empty message', () => {
+ expect(buildGitCommitCommand({ message: '' })).toBe('')
+ expect(buildGitCommitCommand({ message: ' ' })).toBe('')
+ })
+
+ it('falls back to commit-only when no files given', () => {
+ expect(buildGitCommitCommand({ message: 'msg' })).toBe(`git commit -m 'msg'`)
+ })
+
+ it('stages all when allTracked is set', () => {
+ expect(buildGitCommitCommand({ message: 'msg', allTracked: true })).toBe(
+ `git add -A && git commit -m 'msg'`,
+ )
+ })
+
+ it('stages explicit files when provided', () => {
+ expect(buildGitCommitCommand({ message: 'msg', files: ['a', 'b c'] })).toBe(
+ `git add -- 'a' 'b c' && git commit -m 'msg'`,
+ )
+ })
+})
+
+describe('buildGhPrCreateCommand', () => {
+ it('returns empty for missing title', () => {
+ expect(buildGhPrCreateCommand({ title: '', body: '' })).toBe('')
+ })
+
+ it('builds the basic title+body invocation', () => {
+ expect(buildGhPrCreateCommand({ title: 'T', body: 'B' })).toBe(
+ `gh pr create --title 'T' --body 'B'`,
+ )
+ })
+
+ it('appends --base when provided', () => {
+ expect(buildGhPrCreateCommand({ title: 'T', body: 'B', base: 'main' })).toBe(
+ `gh pr create --title 'T' --body 'B' --base 'main'`,
+ )
+ })
+
+ it('quotes multi-line bodies safely', () => {
+ expect(
+ buildGhPrCreateCommand({ title: 'T', body: "line1\nline2 's quote" }),
+ ).toMatch(/--body 'line1\nline2 '\\''s quote'/)
+ })
+})
diff --git a/src/api/agents/__tests__/model-locality.test.ts b/src/api/agents/__tests__/model-locality.test.ts
new file mode 100644
index 00000000..8a5e2f24
--- /dev/null
+++ b/src/api/agents/__tests__/model-locality.test.ts
@@ -0,0 +1,141 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useProviderStore } from '../../../stores/providerStore'
+import {
+ isLocalModel,
+ isLocalModelByName,
+ partitionByLocality,
+} from '../model-locality'
+import type { AIModel } from '../../../types/models'
+
+function model(name: string, provider: AIModel['provider'], extra: Partial<AIModel> = {}): AIModel {
+ return {
+ name,
+ model: name,
+ provider,
+ providerName: provider,
+ type: 'text',
+ size: 0,
+ ...extra,
+ } as AIModel
+}
+
+describe('isLocalModel', () => {
+ beforeEach(() => {
+ // Reset OpenAI provider config to a known state so the
+ // OpenAI-compat branch is deterministic per test.
+ useProviderStore.setState((s) => ({
+ providers: {
+ ...s.providers,
+ openai: {
+ id: 'openai',
+ name: 'LM Studio',
+ baseUrl: 'http://localhost:1234/v1',
+ apiKey: '',
+ enabled: true,
+ isLocal: true,
+ },
+ },
+ }))
+ })
+
+ it('ollama is always local', () => {
+ expect(isLocalModel(model('qwen', 'ollama'))).toBe(true)
+ })
+
+ it('anthropic is never local', () => {
+ expect(isLocalModel(model('claude', 'anthropic'))).toBe(false)
+ })
+
+ it('openai-compat is local when the configured endpoint is local (LM Studio)', () => {
+ expect(isLocalModel(model('qwen-coder', 'openai'))).toBe(true)
+ })
+
+ it('openai-compat is cloud when the configured endpoint is OpenAI/OpenRouter', () => {
+ useProviderStore.setState((s) => ({
+ providers: {
+ ...s.providers,
+ openai: {
+ ...s.providers.openai,
+ baseUrl: 'https://api.openai.com/v1',
+ isLocal: false,
+ },
+ },
+ }))
+ expect(isLocalModel(model('gpt-4o', 'openai'))).toBe(false)
+ })
+})
+
+describe('isLocalModelByName', () => {
+ beforeEach(() => {
+ useProviderStore.setState((s) => ({
+ providers: {
+ ...s.providers,
+ openai: {
+ id: 'openai',
+ name: 'LM Studio',
+ baseUrl: 'http://localhost:1234/v1',
+ apiKey: '',
+ enabled: true,
+ isLocal: true,
+ },
+ },
+ }))
+ })
+
+ it('unprefixed name = legacy Ollama, treated as local', () => {
+ expect(isLocalModelByName('qwen-coder:32b')).toBe(true)
+ })
+
+ it('ollama:: prefix → local', () => {
+ expect(isLocalModelByName('ollama::qwen:7b')).toBe(true)
+ })
+
+ it('anthropic:: prefix → cloud regardless of provider settings', () => {
+ expect(isLocalModelByName('anthropic::claude-sonnet-4-5')).toBe(false)
+ })
+
+ it('openai:: prefix follows the configured isLocal flag', () => {
+ expect(isLocalModelByName('openai::qwen-coder')).toBe(true)
+ useProviderStore.setState((s) => ({
+ providers: {
+ ...s.providers,
+ openai: { ...s.providers.openai, isLocal: false, baseUrl: 'https://openrouter.ai' },
+ },
+ }))
+ expect(isLocalModelByName('openai::deepseek')).toBe(false)
+ })
+
+ it('returns false for empty / nullish names', () => {
+ expect(isLocalModelByName('')).toBe(false)
+ // @ts-expect-error — defensive guard
+ expect(isLocalModelByName(undefined)).toBe(false)
+ })
+})
+
+describe('partitionByLocality', () => {
+ beforeEach(() => {
+ useProviderStore.setState((s) => ({
+ providers: {
+ ...s.providers,
+ openai: {
+ id: 'openai',
+ name: 'LM Studio',
+ baseUrl: 'http://localhost:1234/v1',
+ apiKey: '',
+ enabled: true,
+ isLocal: true,
+ },
+ },
+ }))
+ })
+
+ it('groups Ollama + local OpenAI under local; anthropic under cloud', () => {
+ const out = partitionByLocality([
+ model('qwen', 'ollama'),
+ model('hermes', 'openai'),
+ model('claude', 'anthropic'),
+ ])
+ expect(out.local.map((m) => m.name)).toEqual(['qwen', 'hermes'])
+ expect(out.cloud.map((m) => m.name)).toEqual(['claude'])
+ })
+})
diff --git a/src/api/agents/__tests__/pr-resume.test.ts b/src/api/agents/__tests__/pr-resume.test.ts
new file mode 100644
index 00000000..6bcf3159
--- /dev/null
+++ b/src/api/agents/__tests__/pr-resume.test.ts
@@ -0,0 +1,162 @@
+import { describe, it, expect } from 'vitest'
+import { parsePrUrl, normalisePrJson, renderPrResume } from '../pr-resume'
+
+describe('parsePrUrl', () => {
+ it('accepts the canonical https form', () => {
+ expect(parsePrUrl('https://github.com/anthropics/apps/pull/123')).toEqual({
+ owner: 'anthropics',
+ repo: 'apps',
+ number: 123,
+ })
+ })
+
+ it('accepts http and trailing slash variants', () => {
+ expect(parsePrUrl('http://github.com/foo/bar/pull/1/')).toEqual({
+ owner: 'foo',
+ repo: 'bar',
+ number: 1,
+ })
+ })
+
+ it('accepts the /files tab suffix', () => {
+ expect(parsePrUrl('https://github.com/foo/bar/pull/42/files')).toEqual({
+ owner: 'foo',
+ repo: 'bar',
+ number: 42,
+ })
+ })
+
+ it('strips query strings and fragments', () => {
+ expect(parsePrUrl('https://github.com/foo/bar/pull/42?diff=split#R10')).toEqual({
+ owner: 'foo',
+ repo: 'bar',
+ number: 42,
+ })
+ })
+
+ it('rejects non-PR github URLs', () => {
+ expect(parsePrUrl('https://github.com/foo/bar/issues/1')).toBeNull()
+ expect(parsePrUrl('https://github.com/foo/bar')).toBeNull()
+ expect(parsePrUrl('https://github.com/foo/bar/pull/')).toBeNull()
+ })
+
+ it('rejects non-numeric PR numbers', () => {
+ expect(parsePrUrl('https://github.com/foo/bar/pull/abc')).toBeNull()
+ })
+
+ it('rejects unrelated URLs', () => {
+ expect(parsePrUrl('https://gitlab.com/foo/bar/pull/1')).toBeNull()
+ expect(parsePrUrl('not a url')).toBeNull()
+ expect(parsePrUrl('')).toBeNull()
+ })
+})
+
+describe('normalisePrJson', () => {
+ it('coerces missing fields to safe defaults', () => {
+ const out = normalisePrJson({}, 'https://github.com/x/y/pull/1')
+ expect(out.title).toBe('')
+ expect(out.body).toBe('')
+ expect(out.state).toBe('UNKNOWN')
+ expect(out.comments).toEqual([])
+ expect(out.author).toBeUndefined()
+ })
+
+ it('passes through populated fields', () => {
+ const out = normalisePrJson(
+ {
+ title: 'T',
+ body: 'B',
+ state: 'OPEN',
+ headRefName: 'feat/x',
+ baseRefName: 'main',
+ author: { login: 'alice' },
+ comments: [
+ { author: { login: 'bob' }, body: 'looks good', createdAt: '2026-05-01' },
+ ],
+ },
+ 'https://github.com/x/y/pull/1',
+ )
+ expect(out.title).toBe('T')
+ expect(out.state).toBe('OPEN')
+ expect(out.author).toBe('alice')
+ expect(out.comments).toEqual([
+ { author: 'bob', body: 'looks good', createdAt: '2026-05-01' },
+ ])
+ })
+
+ it('keeps only the last 12 comments', () => {
+ const comments = Array.from({ length: 30 }, (_, i) => ({
+ author: { login: `u${i}` },
+ body: `c${i}`,
+ createdAt: '',
+ }))
+ const out = normalisePrJson({ comments }, 'https://github.com/x/y/pull/1')
+ expect(out.comments).toHaveLength(12)
+ expect(out.comments[0].author).toBe('u18')
+ expect(out.comments[11].author).toBe('u29')
+ })
+
+ it('truncates absurdly long bodies', () => {
+ const big = 'x'.repeat(10_000)
+ const out = normalisePrJson({ body: big }, 'https://github.com/x/y/pull/1')
+ expect(out.body.length).toBeLessThan(big.length)
+ expect(out.body).toMatch(/truncated/)
+ })
+})
+
+describe('renderPrResume', () => {
+ it('renders the header, title, description, comments, and diff', () => {
+ const text = renderPrResume({
+ url: 'https://github.com/x/y/pull/1',
+ title: 'Add foo',
+ body: 'fix the thing',
+ state: 'OPEN',
+ headRefName: 'feat/foo',
+ baseRefName: 'main',
+ author: 'alice',
+ comments: [
+ { author: 'bob', body: 'lgtm', createdAt: '2026-05-01' },
+ ],
+ diff: '--- a/x\n+++ b/x\n@@ -1 +1 @@\n-foo\n+bar\n',
+ })
+ expect(text).toMatch(/# PR https/)
+ expect(text).toMatch(/OPEN/)
+ expect(text).toMatch(/feat\/foo → main/)
+ expect(text).toMatch(/@alice/)
+ expect(text).toMatch(/Add foo/)
+ expect(text).toMatch(/fix the thing/)
+ expect(text).toMatch(/\*\*@bob\*\*/)
+ expect(text).toMatch(/```diff/)
+ expect(text).toMatch(/-foo\n\+bar/)
+ })
+
+ it('drops the comments + diff sections when both are empty', () => {
+ const text = renderPrResume({
+ url: 'https://github.com/x/y/pull/1',
+ title: 'Add foo',
+ body: '',
+ state: 'OPEN',
+ headRefName: 'b',
+ baseRefName: 'main',
+ comments: [],
+ diff: '',
+ })
+ expect(text).not.toMatch(/Latest comments/)
+ expect(text).not.toMatch(/```diff/)
+ })
+
+ it('truncates oversized diffs', () => {
+ const big = 'x'.repeat(20_000)
+ const text = renderPrResume({
+ url: 'https://github.com/x/y/pull/1',
+ title: '',
+ body: '',
+ state: 'OPEN',
+ headRefName: 'b',
+ baseRefName: 'main',
+ comments: [],
+ diff: big,
+ })
+ expect(text).toMatch(/truncated/)
+ })
+})
diff --git a/src/api/agents/__tests__/project-init.test.ts b/src/api/agents/__tests__/project-init.test.ts
new file mode 100644
index 00000000..5485de17
--- /dev/null
+++ b/src/api/agents/__tests__/project-init.test.ts
@@ -0,0 +1,102 @@
+import { describe, it, expect } from 'vitest'
+import {
+ RECIPES,
+ findRecipe,
+ prereqCheckCommand,
+ renderInitPlan,
+ listRecipes,
+} from '../project-init'
+
+describe('RECIPES table', () => {
+ it('exposes every known recipe by its id', () => {
+ for (const [id, recipe] of Object.entries(RECIPES)) {
+ expect(recipe.id).toBe(id)
+ expect(recipe.name).toBeTruthy()
+ expect(recipe.summary).toBeTruthy()
+ expect(recipe.steps.length).toBeGreaterThan(0)
+ }
+ })
+
+ it('every step has a description (commands may be empty for notes)', () => {
+ for (const recipe of Object.values(RECIPES)) {
+ for (const step of recipe.steps) {
+ expect(step.description).toBeTruthy()
+ }
+ }
+ })
+})
+
+describe('findRecipe', () => {
+ it('returns a recipe by id', () => {
+ expect(findRecipe('next-postgres')?.name).toBe('Next.js + Postgres')
+ })
+
+ it('is case-insensitive and trim-tolerant', () => {
+ expect(findRecipe(' Next-Postgres ')?.id).toBe('next-postgres')
+ })
+
+ it('returns null for unknown ids', () => {
+ expect(findRecipe('xyz')).toBeNull()
+ expect(findRecipe('')).toBeNull()
+ })
+})
+
+describe('prereqCheckCommand', () => {
+ it('builds a chain that exits 127 on the first missing tool', () => {
+ const recipe = findRecipe('next-postgres')!
+ const cmd = prereqCheckCommand(recipe)
+ expect(cmd).toMatch(/command -v node/)
+ expect(cmd).toMatch(/command -v pnpm/)
+ expect(cmd).toMatch(/exit 127/)
+ })
+
+ it('handles the no-prereq case without crashing', () => {
+ const cmd = prereqCheckCommand({
+ id: 'x',
+ name: 'X',
+ summary: '',
+ prerequisites: [],
+ steps: [],
+ })
+ expect(cmd).toMatch(/^:/) // no-op shell
+ })
+})
+
+describe('renderInitPlan', () => {
+ it('renders title, summary, prereqs, and each step as a fenced block', () => {
+ const md = renderInitPlan(findRecipe('rust-axum')!)
+ expect(md).toMatch(/^# Rust \+ Axum/)
+ expect(md).toMatch(/Prerequisites:/)
+ expect(md).toMatch(/cargo/)
+ expect(md).toMatch(/```sh/)
+ })
+
+ it('marks optional steps with the optional tag', () => {
+ const md = renderInitPlan(findRecipe('next-postgres')!)
+ expect(md).toMatch(/_\(optional\)_/)
+ })
+
+ it('renders empty commands as a manual step note', () => {
+ const md = renderInitPlan({
+ id: 'x',
+ name: 'X',
+ summary: 's',
+ prerequisites: [],
+ steps: [{ description: 'just think', command: '' }],
+ })
+ expect(md).toMatch(/manual step/)
+ expect(md).not.toMatch(/```sh/)
+ })
+})
+
+describe('listRecipes', () => {
+ it('lists at least the 5 launch recipes with id/name/summary', () => {
+ const list = listRecipes()
+ expect(list.length).toBeGreaterThanOrEqual(5)
+ expect(list.find((r) => r.id === 'next-postgres')).toBeTruthy()
+ expect(list.find((r) => r.id === 'next-supabase')).toBeTruthy()
+ expect(list.find((r) => r.id === 'next-stripe')).toBeTruthy()
+ expect(list.find((r) => r.id === 'rust-axum')).toBeTruthy()
+ expect(list.find((r) => r.id === 'vite-react')).toBeTruthy()
+ })
+})
diff --git a/src/api/agents/__tests__/repo-map.test.ts b/src/api/agents/__tests__/repo-map.test.ts
new file mode 100644
index 00000000..588e62fa
--- /dev/null
+++ b/src/api/agents/__tests__/repo-map.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const backendCall = vi.fn()
+
+vi.mock('../../backend', () => ({
+ backendCall: (...args: unknown[]) => backendCall(...args),
+}))
+
+import { fetchRepoMap, renderRepoMapSection, type RepoMapResult } from '../repo-map'
+
+beforeEach(() => {
+ backendCall.mockReset()
+})
+
+describe('fetchRepoMap', () => {
+ it('returns an empty map when no working directory is given', async () => {
+ const result = await fetchRepoMap({ workingDirectory: '' })
+ expect(result).toEqual({ files: [], count: 0 })
+ expect(backendCall).not.toHaveBeenCalled()
+ })
+
+ it('calls the bridge repo_map command with the working dir, query and limit', async () => {
+ backendCall.mockResolvedValueOnce({
+ files: [{ path: 'a.ts', score: 0.5, snippet: '// a' }],
+ count: 1,
+ })
+ await fetchRepoMap({
+ workingDirectory: '/Users/me/repo',
+ query: 'auth',
+ limit: 50,
+ })
+ expect(backendCall).toHaveBeenCalledOnce()
+ expect(backendCall.mock.calls[0]).toEqual([
+ 'repo_map',
+ { workingDirectory: '/Users/me/repo', query: 'auth', limit: 50 },
+ ])
+ })
+
+ it('defaults the limit to 20 when caller omits it', async () => {
+ backendCall.mockResolvedValueOnce({ files: [], count: 0 })
+ await fetchRepoMap({ workingDirectory: '/r' })
+ const args = backendCall.mock.calls[0][1] as Record<string, unknown>
+ expect(args.limit).toBe(20)
+ })
+
+ it('coerces a non-array files field into an empty array', async () => {
+ backendCall.mockResolvedValueOnce({ files: null, count: 0 } as unknown)
+ const result = await fetchRepoMap({ workingDirectory: '/r' })
+ expect(result.files).toEqual([])
+ })
+})
+
+describe('renderRepoMapSection', () => {
+ function map(files: number): RepoMapResult {
+ return {
+ count: files,
+ files: Array.from({ length: files }, (_, i) => ({
+ path: `src/f${i}.ts`,
+ score: 1 / (i + 1),
+ snippet: `// file ${i}`,
+ })),
+ }
+ }
+
+ it('returns empty string for an empty map (no header without content)', () => {
+ expect(renderRepoMapSection({ files: [], count: 0 })).toBe('')
+ })
+
+ it('renders a header + one bullet per file', () => {
+ const out = renderRepoMapSection(map(2))
+ expect(out).toMatch(/REPO MAP/)
+ expect(out).toMatch(/- src\/f0\.ts/)
+ expect(out).toMatch(/- src\/f1\.ts/)
+ })
+
+ it('respects maxChars by truncating later entries', () => {
+ const out = renderRepoMapSection(map(200), { maxChars: 250 })
+ // Header itself is ~150 chars; only a couple of bullets should survive.
+ const bullets = out.split('\n').filter((l) => l.startsWith('- ')).length
+ expect(bullets).toBeGreaterThan(0)
+ expect(bullets).toBeLessThan(10)
+ expect(out.length).toBeLessThanOrEqual(260)
+ })
+
+ it('omits the snippet trailer when the file has no snippet', () => {
+ const out = renderRepoMapSection({
+ count: 1,
+ files: [{ path: 'src/x.ts', score: 0.1, snippet: '' }],
+ })
+ expect(out).toMatch(/- src\/x\.ts$/m)
+ })
+})
diff --git a/src/api/agents/__tests__/test-runner.test.ts b/src/api/agents/__tests__/test-runner.test.ts
new file mode 100644
index 00000000..10199950
--- /dev/null
+++ b/src/api/agents/__tests__/test-runner.test.ts
@@ -0,0 +1,176 @@
+import { describe, it, expect } from 'vitest'
+import {
+ detectRunnerFromFiles,
+ commandForRunner,
+ parseVitest,
+ parseCargo,
+ parsePytest,
+ parseForRunner,
+ renderResult,
+} from '../test-runner'
+
+describe('detectRunnerFromFiles', () => {
+ it('returns vitest when vitest.config.ts is present', () => {
+ expect(detectRunnerFromFiles(['vitest.config.ts', 'package.json'])).toBe('vitest')
+ })
+
+ it('returns cargo for Cargo.toml', () => {
+ expect(detectRunnerFromFiles(['Cargo.toml'])).toBe('cargo')
+ })
+
+ it('returns pytest for pyproject.toml', () => {
+ expect(detectRunnerFromFiles(['pyproject.toml'])).toBe('pytest')
+ })
+
+ it('returns jest for jest.config.js', () => {
+ expect(detectRunnerFromFiles(['jest.config.js'])).toBe('jest')
+ })
+
+ it('falls back to vitest when only package.json is around', () => {
+ expect(detectRunnerFromFiles(['package.json'])).toBe('vitest')
+ })
+
+ it('returns unknown when nothing matches', () => {
+ expect(detectRunnerFromFiles(['README.md', 'LICENSE'])).toBe('unknown')
+ })
+
+ it('is case-insensitive', () => {
+ expect(detectRunnerFromFiles(['CARGO.TOML'])).toBe('cargo')
+ })
+})
+
+describe('commandForRunner', () => {
+ it('returns a runnable command for every known runner', () => {
+ expect(commandForRunner('vitest')).toMatch(/vitest/)
+ expect(commandForRunner('cargo')).toMatch(/cargo test/)
+ expect(commandForRunner('pytest')).toMatch(/pytest/)
+ expect(commandForRunner('jest')).toMatch(/jest/)
+ })
+
+ it('returns empty string for unknown', () => {
+ expect(commandForRunner('unknown')).toBe('')
+ })
+})
+
+describe('parseVitest', () => {
+ it('extracts the green case', () => {
+ const out = `
+RUN v4.1.6
+ Test Files 10 passed (10)
+ Tests 100 passed (100)
+`
+ const r = parseVitest(out)
+ expect(r.passed).toBe(true)
+ expect(r.passedCount).toBe(100)
+ expect(r.failedCount).toBe(0)
+ expect(r.total).toBe(100)
+ })
+
+ it('extracts failing test names from the verbose reporter', () => {
+ const out = `
+ Test Files 1 failed | 9 passed (10)
+ Tests 2 failed | 98 passed (100)
+ × src/foo.test.ts > module > some test 12ms
+ ✗ src/bar.test.ts > module > other test
+`
+ const r = parseVitest(out)
+ expect(r.passed).toBe(false)
+ expect(r.passedCount).toBe(98)
+ expect(r.failedCount).toBe(2)
+ expect(r.failedTests).toHaveLength(2)
+ expect(r.failedTests[0]).toContain('some test')
+ expect(r.failedTests[1]).toContain('other test')
+ })
+
+ it('treats an empty run as not-passed', () => {
+ const r = parseVitest('')
+ expect(r.passed).toBe(false)
+ expect(r.total).toBe(0)
+ })
+})
+
+describe('parseCargo', () => {
+ it('extracts the green case', () => {
+ const out = `running 80 tests
+test foo ... ok
+test bar ... ok
+test result: ok. 80 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out`
+ const r = parseCargo(out)
+ expect(r.passed).toBe(true)
+ expect(r.passedCount).toBe(80)
+ expect(r.failedCount).toBe(0)
+ })
+
+ it('extracts failures', () => {
+ const out = `test foo ... ok
+test bar ... FAILED
+test baz ... FAILED
+test result: FAILED. 1 passed; 2 failed; 0 ignored`
+ const r = parseCargo(out)
+ expect(r.passed).toBe(false)
+ expect(r.passedCount).toBe(1)
+ expect(r.failedCount).toBe(2)
+ expect(r.failedTests).toEqual(['bar', 'baz'])
+ })
+})
+
+describe('parsePytest', () => {
+ it('green case', () => {
+ const r = parsePytest('======= 12 passed in 0.42s =======')
+ expect(r.passed).toBe(true)
+ expect(r.passedCount).toBe(12)
+ expect(r.failedCount).toBe(0)
+ })
+
+ it('extracts failures', () => {
+ const out = `===== 1 failed, 11 passed in 0.42s =====
+FAILED tests/test_foo.py::test_bar - AssertionError: nope`
+ const r = parsePytest(out)
+ expect(r.passed).toBe(false)
+ expect(r.failedCount).toBe(1)
+ expect(r.passedCount).toBe(11)
+ expect(r.failedTests).toEqual(['tests/test_foo.py::test_bar'])
+ })
+})
+
+describe('parseForRunner', () => {
+ it('routes by runner name', () => {
+ expect(parseForRunner('cargo', 'test result: ok. 1 passed; 0 failed;').runner).toBe('cargo')
+ expect(parseForRunner('pytest', '1 passed in 0s').runner).toBe('pytest')
+ expect(parseForRunner('vitest', 'Tests 1 passed (1)').runner).toBe('vitest')
+ expect(parseForRunner('jest', 'Tests 1 passed (1)').runner).toBe('jest')
+ expect(parseForRunner('unknown', 'whatever').runner).toBe('unknown')
+ })
+})
+
+describe('renderResult', () => {
+ it('renders a passing run as PASSED', () => {
+ const text = renderResult({
+ runner: 'vitest',
+ passed: true,
+ total: 100,
+ passedCount: 100,
+ failedCount: 0,
+ failedTests: [],
+ outputTail: 'Done.',
+ })
+ expect(text).toMatch(/^PASSED \(vitest\)/)
+ expect(text).toMatch(/100\/100/)
+ })
+
+ it('renders a failing run with the failure list', () => {
+ const text = renderResult({
+ runner: 'cargo',
+ passed: false,
+ total: 3,
+ passedCount: 1,
+ failedCount: 2,
+ failedTests: ['a', 'b'],
+ outputTail: 'tail',
+ })
+ expect(text).toMatch(/FAILED \(cargo\)/)
+ expect(text).toMatch(/- a/)
+ expect(text).toMatch(/- b/)
+ expect(text).toMatch(/tail/)
+ })
+})
diff --git a/src/api/agents/__tests__/workspace-resolve.test.ts b/src/api/agents/__tests__/workspace-resolve.test.ts
new file mode 100644
index 00000000..99055859
--- /dev/null
+++ b/src/api/agents/__tests__/workspace-resolve.test.ts
@@ -0,0 +1,56 @@
+import { describe, it, expect } from 'vitest'
+import { resolveWorkspace, resolveWorkspacePath } from '../workspace-resolve'
+
+describe('resolveWorkspace', () => {
+ it('returns null when neither layer has a workspace', () => {
+ expect(resolveWorkspace({ perChat: undefined, defaultWorkspace: null })).toBeNull()
+ })
+
+ it('prefers per-chat over default', () => {
+ const out = resolveWorkspace({
+ perChat: { kind: 'folder', path: '/a' },
+ defaultWorkspace: { kind: 'folder', path: '/b' },
+ })
+ expect(out).toEqual({ kind: 'folder', path: '/a' })
+ })
+
+ it('falls back to default when per-chat is undefined', () => {
+ const out = resolveWorkspace({
+ perChat: undefined,
+ defaultWorkspace: { kind: 'folder', path: '/d' },
+ })
+ expect(out).toEqual({ kind: 'folder', path: '/d' })
+ })
+
+ it('a sandbox per-chat is still a real choice — does NOT fall through to default', () => {
+ const out = resolveWorkspace({
+ perChat: { kind: 'sandbox' },
+ defaultWorkspace: { kind: 'folder', path: '/d' },
+ })
+ expect(out).toEqual({ kind: 'sandbox' })
+ })
+})
+
+describe('resolveWorkspacePath', () => {
+ it('returns null for sandbox per-chat (even with a default folder)', () => {
+ expect(
+ resolveWorkspacePath({
+ perChat: { kind: 'sandbox' },
+ defaultWorkspace: { kind: 'folder', path: '/d' },
+ }),
+ ).toBeNull()
+ })
+
+ it('returns the primary path when one is set', () => {
+ expect(
+ resolveWorkspacePath({
+ perChat: undefined,
+ defaultWorkspace: { kind: 'folder', path: '/d' },
+ }),
+ ).toBe('/d')
+ })
+
+ it('returns null when nothing is set', () => {
+ expect(resolveWorkspacePath({ perChat: undefined, defaultWorkspace: null })).toBeNull()
+ })
+})
diff --git a/src/api/agents/architect.ts b/src/api/agents/architect.ts
new file mode 100644
index 00000000..c5ed44ac
--- /dev/null
+++ b/src/api/agents/architect.ts
@@ -0,0 +1,96 @@
+import type { ChatMessage } from '../providers/types'
+import { getProviderForModel } from '../providers'
+
+export const ARCHITECT_SYSTEM_PROMPT = `You are the Architect — the planning half of a two-model coding system.
+
+Your job: read the user's request and the working directory, then output a CONCRETE, ORDERED PLAN that the Editor model will execute step by step. You have NO tools. You do NOT read or write files. You only plan.
+
+Output format (markdown, nothing else):
+
+## Plan
+
+1. <step> — file(s), change, why
+2. ...
+
+## Files to read first
+
+- path/to/file.ts — why
+- ...
+
+## Done when
+
+- <observable criterion>
+- ...
+
+Rules:
+- Be specific. "Update the API route" is bad. "Edit apps/web/app/api/foo/route.ts to handle POST" is good.
+- Reference exact file paths when the user mentioned them or you can infer them.
+- Maximum 12 numbered steps. Group if needed.
+- Don't write code unless it's essential to convey the change shape.
+- Don't invent files. If you don't know the file, say "find the X file that does Y".
+- Output the plan in the exact format above. Nothing else.`
+
+export interface ArchitectInput {
+ /** Prefixed model name, e.g. `anthropic::claude-sonnet-4-5`. */
+ model: string
+ /** The user's latest instruction. */
+ userInstruction: string
+ /** Resolved cwd; threaded into the system prompt so the planner knows where work happens. */
+ workingDirectory: string
+ /** Optional prior conversation turns for follow-up context (keep small — planner doesn't need full history). */
+ recentMessages?: ChatMessage[]
+ /** Abort signal — wired to the same controller as the editor loop so a cancelled run kills both halves. */
+ signal?: AbortSignal
+ /** Override sampling temperature. Default 0.3 — plans want determinism, not creativity. */
+ temperature?: number
+}
+
+export interface ArchitectResult {
+ /** Raw markdown plan from the architect. */
+ plan: string
+ /** Echo of the model used — for the chat-side reasoning block. */
+ modelUsed: string
+ /** Wall time spent planning, for the same block. */
+ tookMs: number
+}
+
+/**
+ * Run the Architect pass. Returns the markdown plan; no tools are passed
+ * to the provider so the model cannot accidentally start editing files in
+ * this phase. Caller is responsible for showing the plan to the user and
+ * forwarding it into the Editor's system prompt.
+ */
+export async function planWithArchitect(
+ input: ArchitectInput,
+): Promise<ArchitectResult> {
+ const t0 = Date.now()
+ const { provider, modelId } = getProviderForModel(input.model)
+ const messages: ChatMessage[] = [
+ {
+ role: 'system',
+ content: `${ARCHITECT_SYSTEM_PROMPT}\n\nWorking directory: ${input.workingDirectory}`,
+ },
+ ...(input.recentMessages ?? []),
+ { role: 'user', content: input.userInstruction },
+ ]
+ const { content } = await provider.chatWithTools(modelId, messages, [], {
+ temperature: input.temperature ?? 0.3,
+ signal: input.signal,
+ })
+ return {
+ plan: (content ?? '').trim(),
+ modelUsed: input.model,
+ tookMs: Date.now() - t0,
+ }
+}
+
+/**
+ * Render the architect plan as a system-prompt suffix the editor sees.
+ * The marker `ARCHITECT PLAN:` is intentional — it gives the editor a
+ * stable anchor it can refer to ("follow the architect plan above").
+ */
+export function renderArchitectPlanSection(plan: string): string {
+ const trimmed = plan.trim()
+ if (!trimmed) return ''
+ return `\n\nARCHITECT PLAN — follow this plan step by step. The architect produced it before any tool was called. Treat it as authoritative for ordering and scope; deviate only when a step turns out to be impossible or unsafe.\n\n${trimmed}`
+}
diff --git a/src/api/agents/bg-tasks.ts b/src/api/agents/bg-tasks.ts
new file mode 100644
index 00000000..9554fb3c
--- /dev/null
+++ b/src/api/agents/bg-tasks.ts
@@ -0,0 +1,58 @@
+import { backendCall } from '../backend'
+
+export interface BgTaskStatus {
+ id: string
+ command: string
+ cwd: string | null
+ started_at: number
+ finished_at: number | null
+ exit_code: number | null
+ running: boolean
+ cancelled: boolean
+ output_tail: string
+}
+
+export interface BgTaskListResult {
+ tasks: BgTaskStatus[]
+}
+
+/** Starts a long-running shell command in the bridge. Returns the new task id. */
+export async function bgStart(input: {
+ command: string
+ cwd?: string
+ shell?: string
+}): Promise<{ id: string }> {
+ if (!input.command?.trim()) throw new Error('command is required')
+ return backendCall<{ id: string }>('shell_task_start', {
+ command: input.command,
+ cwd: input.cwd,
+ shell: input.shell,
+ })
+}
+
+export async function bgStatus(id: string): Promise<BgTaskStatus> {
+ return backendCall<BgTaskStatus>('shell_task_status', { id })
+}
+
+export async function bgKill(id: string): Promise<{ ok: boolean; cancelled: boolean }> {
+ return backendCall<{ ok: boolean; cancelled: boolean }>('shell_task_kill', { id })
+}
+
+export async function bgList(): Promise<BgTaskListResult> {
+ return backendCall<BgTaskListResult>('shell_task_list', {})
+}
+
+/** Renders a status payload as a one-line summary for the model / UI. */
+export function renderBgStatusOneLine(s: BgTaskStatus): string {
+ const phase = s.running
+ ? 'running'
+ : s.cancelled
+ ? 'cancelled'
+ : s.exit_code === 0
+ ? 'ok'
+ : `exit ${s.exit_code ?? '?'}`
+ const elapsed = s.finished_at
+ ? `${s.finished_at - s.started_at}s`
+ : `${Math.max(0, Math.floor(Date.now() / 1000) - s.started_at)}s`
+ return `[${s.id.slice(0, 8)}] ${phase} (${elapsed}) — ${s.command}`
+}
diff --git a/src/api/agents/git-tools.ts b/src/api/agents/git-tools.ts
new file mode 100644
index 00000000..43ffdc69
--- /dev/null
+++ b/src/api/agents/git-tools.ts
@@ -0,0 +1,150 @@
+/**
+ * Sprint B #5 — Typed wrappers for `git` and `gh`.
+ *
+ * Pure helpers for assembling commands + parsing the porcelain output of
+ * `git status` and the one-line `git log` format. The MCP executors call
+ * shell_execute under the hood but expose this surface to the model so a
+ * "make me a PR" turn is a single typed call instead of a juggled shell
+ * pipeline with bespoke error messages on every step.
+ */
+
+export interface GitStatusEntry {
+ /** Two-letter porcelain code: `??` for untracked, ` M` for unstaged-modified, `M ` for staged-modified, etc. */
+ code: string
+ path: string
+ /** Convenience flag: did the file enter the index? */
+ staged: boolean
+}
+
+export interface GitStatusResult {
+ branch: string | null
+ ahead: number
+ behind: number
+ entries: GitStatusEntry[]
+ /** True iff the working tree has no uncommitted changes (staged or unstaged). */
+ clean: boolean
+}
+
+/**
+ * Parses `git status --porcelain=2 --branch` output. Falls back gracefully
+ * when the user runs older git that lacks `--porcelain=2`; in that case
+ * `branch` stays null and only the entries are populated.
+ */
+export function parseGitStatus(raw: string): GitStatusResult {
+ const lines = raw.split('\n')
+ let branch: string | null = null
+ let ahead = 0
+ let behind = 0
+ const entries: GitStatusEntry[] = []
+ for (const line of lines) {
+ if (!line) continue
+ if (line.startsWith('# branch.head ')) {
+ branch = line.slice('# branch.head '.length).trim()
+ if (branch === '(detached)') branch = null
+ continue
+ }
+ if (line.startsWith('# branch.ab ')) {
+ const m = line.match(/\+(\d+)\s+-(\d+)/)
+ if (m) {
+ ahead = parseInt(m[1], 10)
+ behind = parseInt(m[2], 10)
+ }
+ continue
+ }
+ if (line.startsWith('#')) continue
+ // Porcelain v2 entries start with 1/2/u/?. Cheap parse: extract path
+ // as the trailing whitespace-separated token. Rename entries get the
+ // new path; we drop the old name to keep the model output small.
+ if (line.startsWith('? ')) {
+ entries.push({ code: '??', path: line.slice(2).trim(), staged: false })
+ continue
+ }
+ if (line.startsWith('1 ') || line.startsWith('2 ')) {
+ // Format: `1 XY <sub> ... <path>` where XY are status chars.
+ const parts = line.split(' ')
+ if (parts.length >= 9) {
+ const xy = parts[1] || ' '
+ const path = parts.slice(8).join(' ')
+ const staged = xy[0] !== '.' && xy[0] !== ' '
+ entries.push({ code: xy, path, staged })
+ }
+ continue
+ }
+ if (line.startsWith('u ')) {
+ // Unmerged path — treat as a conflict the model must resolve.
+ const parts = line.split(' ')
+ const path = parts[parts.length - 1]
+ entries.push({ code: 'UU', path, staged: false })
+ }
+ }
+ return { branch, ahead, behind, entries, clean: entries.length === 0 }
+}
+
+export function renderGitStatus(r: GitStatusResult): string {
+ if (!r.entries.length && r.branch) {
+ return `On branch ${r.branch}. Working tree clean.`
+ }
+ const head = r.branch
+ ? `On branch ${r.branch}${r.ahead || r.behind ? ` (ahead ${r.ahead}, behind ${r.behind})` : ''}.`
+ : 'Detached HEAD.'
+ const lines = r.entries.map((e) => ` ${e.code} ${e.path}`)
+ return `${head}\n${lines.join('\n')}`
+}
+
+export interface GitLogEntry {
+ sha: string
+ subject: string
+}
+
+export function parseGitLog(raw: string): GitLogEntry[] {
+ const out: GitLogEntry[] = []
+ for (const line of raw.split('\n')) {
+ if (!line) continue
+ const m = line.match(/^([0-9a-f]{7,40})\s+(.+)$/i)
+ if (m) out.push({ sha: m[1], subject: m[2] })
+ }
+ return out
+}
+
+/**
+ * Shell-quotes a string for POSIX shells. We use single quotes + literal
+ * escaping for embedded single quotes — bullet-proof against most input,
+ * including the model emitting backticks or `$()` it shouldn't.
+ */
+export function shellQuote(s: string): string {
+ return `'${s.replace(/'/g, `'\\''`)}'`
+}
+
+export interface GitCommitArgs {
+ message: string
+ files?: string[]
+ /** Stage every change before committing. Mutually exclusive with files. */
+ allTracked?: boolean
+}
+
+export function buildGitCommitCommand(args: GitCommitArgs): string {
+ if (!args.message?.trim()) return ''
+ const stage = args.allTracked
+ ? 'git add -A'
+ : args.files?.length
+ ? `git add -- ${args.files.map(shellQuote).join(' ')}`
+ : ''
+ const commit = `git commit -m ${shellQuote(args.message)}`
+ return stage ? `${stage} && ${commit}` : commit
+}
+
+export interface GhPrCreateArgs {
+ title: string
+ body: string
+ base?: string
+}
+
+export function buildGhPrCreateCommand(args: GhPrCreateArgs): string {
+ if (!args.title?.trim()) return ''
+ const flags = [
+ `--title ${shellQuote(args.title)}`,
+ `--body ${shellQuote(args.body ?? '')}`,
+ ]
+ if (args.base) flags.push(`--base ${shellQuote(args.base)}`)
+ return `gh pr create ${flags.join(' ')}`
+}
diff --git a/src/api/agents/model-locality.ts b/src/api/agents/model-locality.ts
new file mode 100644
index 00000000..8bd12276
--- /dev/null
+++ b/src/api/agents/model-locality.ts
@@ -0,0 +1,65 @@
+/**
+ * Local vs. cloud classification for the Architect picker.
+ *
+ * LU's promise is "local + uncensored + private". Letting users wire a
+ * third-party cloud (Anthropic / OpenAI / OpenRouter / …) as the
+ * Architect quietly breaks that — every planning step leaves the
+ * machine. The UI now defaults to LOCAL-only and shows a deliberate
+ * opt-in if the user wants to override, with a planned "LU Cloud
+ * Premium" tier as the privacy-preserving alternative (TEE-attested
+ * open-weights hosted by us — coming with Cloud Studio).
+ */
+
+import type { AIModel } from '../../types/models'
+import { useProviderStore } from '../../stores/providerStore'
+
+/**
+ * True when the model runs on the user's own machine (Ollama, LM Studio,
+ * vLLM, llama.cpp, …). False for any cloud endpoint (Anthropic,
+ * OpenRouter, Groq, OpenAI direct, …).
+ *
+ * For OpenAI-compatible providers the answer depends on the configured
+ * `baseUrl` — `localhost:1234` is LM Studio, `api.openai.com` is the
+ * real OpenAI. The provider store carries the `isLocal` flag for that
+ * configured endpoint; we look it up by provider id.
+ */
+export function isLocalModel(model: AIModel): boolean {
+ if (!model) return false
+ if (model.provider === 'ollama') return true
+ if (model.provider === 'anthropic') return false
+ if (model.provider === 'openai') {
+ const cfg = useProviderStore.getState().providers['openai']
+ return cfg?.isLocal === true
+ }
+ return false
+}
+
+/** Same check but operating on a prefixed model name (`anthropic::xyz`). */
+export function isLocalModelByName(name: string): boolean {
+ if (!name) return false
+ const [providerId] = name.split('::')
+ if (providerId === 'ollama' || !name.includes('::')) return true
+ if (providerId === 'anthropic') return false
+ if (providerId === 'openai') {
+ const cfg = useProviderStore.getState().providers['openai']
+ return cfg?.isLocal === true
+ }
+ return false
+}
+
+/**
+ * Splits a model list into [local, cloud]. Used by the Architect
+ * picker to render two groups + the local-first warning text.
+ */
+export function partitionByLocality(models: AIModel[]): {
+ local: AIModel[]
+ cloud: AIModel[]
+} {
+ const local: AIModel[] = []
+ const cloud: AIModel[] = []
+ for (const m of models) {
+ if (isLocalModel(m)) local.push(m)
+ else cloud.push(m)
+ }
+ return { local, cloud }
+}
diff --git a/src/api/agents/pr-resume.ts b/src/api/agents/pr-resume.ts
new file mode 100644
index 00000000..f9c4b8e8
--- /dev/null
+++ b/src/api/agents/pr-resume.ts
@@ -0,0 +1,106 @@
+/**
+ * pr_resume — Claude-Code-style "/resume <pr-url>" support.
+ *
+ * Given a GitHub PR URL, fetches title, body, head ref, latest comments,
+ * and a unified diff via the local `gh` CLI in a single call. The
+ * builtin tool wraps three `gh` invocations + the URL parser so the
+ * model gets a compact, ready-to-paraphrase snapshot of where the PR
+ * left off.
+ *
+ * Pure helpers (parser + renderer) live here so they can be unit-tested
+ * without touching the bridge.
+ */
+
+export interface PrLocator {
+ owner: string
+ repo: string
+ number: number
+}
+
+export interface PrResumePayload {
+ url: string
+ title: string
+ body: string
+ state: string
+ headRefName: string
+ baseRefName: string
+ author?: string
+ comments: Array<{ author: string; body: string; createdAt: string }>
+ diff: string
+}
+
+const PR_URL_RE = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[?#/].*)?$/
+
+export function parsePrUrl(url: string): PrLocator | null {
+ const m = (url ?? '').trim().match(PR_URL_RE)
+ if (!m) return null
+ const num = parseInt(m[3], 10)
+ if (!Number.isFinite(num) || num <= 0) return null
+ return { owner: m[1], repo: m[2], number: num }
+}
+
+/**
+ * Compact a verbose `gh pr view --json` response into a renderer-friendly
+ * shape. The bridge returns a raw JSON blob; this normalises field names
+ * + truncates long comment bodies so the system-prompt section fits.
+ */
+export function normalisePrJson(raw: any, url: string): Omit<PrResumePayload, 'diff'> {
+ const comments: PrResumePayload['comments'] = Array.isArray(raw?.comments)
+ ? raw.comments
+ .slice(-12) // last 12 — older comments are usually stale
+ .map((c: any) => ({
+ author: String(c?.author?.login ?? c?.author ?? 'unknown'),
+ body: clip(String(c?.body ?? ''), 600),
+ createdAt: String(c?.createdAt ?? ''),
+ }))
+ : []
+ return {
+ url,
+ title: String(raw?.title ?? ''),
+ body: clip(String(raw?.body ?? ''), 4000),
+ state: String(raw?.state ?? 'UNKNOWN'),
+ headRefName: String(raw?.headRefName ?? ''),
+ baseRefName: String(raw?.baseRefName ?? ''),
+ author: raw?.author?.login ? String(raw.author.login) : undefined,
+ comments,
+ }
+}
+
+function clip(s: string, n: number): string {
+ if (s.length <= n) return s
+ return `${s.slice(0, n).trimEnd()}\n…(truncated, ${s.length - n} chars dropped)`
+}
+
+/**
+ * Renders the structured PR payload as a markdown summary the model
+ * can use to orient itself. Designed to land at the top of the next
+ * user message so the model has full context for "continue this PR".
+ */
+export function renderPrResume(p: PrResumePayload): string {
+ const head = [
+ `# PR ${p.url}`,
+ `**State:** ${p.state} **Branch:** ${p.headRefName} → ${p.baseRefName}` +
+ (p.author ? ` **Author:** @${p.author}` : ''),
+ '',
+ `## Title`,
+ p.title || '(no title)',
+ '',
+ `## Description`,
+ p.body || '(empty)',
+ '',
+ ].join('\n')
+ const comments = p.comments.length
+ ? [
+ '## Latest comments',
+ ...p.comments.map(
+ (c) =>
+ `- **@${c.author}** (${c.createdAt}):\n ${c.body.replace(/\n/g, '\n ')}`,
+ ),
+ '',
+ ].join('\n')
+ : ''
+ const diff = p.diff
+ ? `## Diff\n\n\`\`\`diff\n${clip(p.diff, 8000)}\n\`\`\`\n`
+ : ''
+ return `${head}${comments}${diff}`
+}
diff --git a/src/api/agents/project-init.ts b/src/api/agents/project-init.ts
new file mode 100644
index 00000000..d690aeb5
--- /dev/null
+++ b/src/api/agents/project-init.ts
@@ -0,0 +1,197 @@
+/**
+ * project_init — System-Wide Setup builtin (Bonus, 2026-05).
+ *
+ * Pure recipe library: maps a stack spec ("next-postgres-stripe") to an
+ * ordered list of shell commands the model can execute via shell_execute.
+ * The tool itself does not run the commands — it returns a structured
+ * plan so the Codex/Agent loop can orchestrate, surface progress, and
+ * ask before destructive steps.
+ *
+ * Adding a new recipe = appending to RECIPES below. Each entry stays
+ * cross-platform by emitting POSIX shell first; Windows-specific
+ * differences (e.g. `pnpm` vs `pnpm.exe`) are handled by the user's
+ * shell wrapper, not by this module.
+ */
+
+export interface InitStep {
+ /** One-line description shown to the user before the command runs. */
+ description: string
+ /** Shell command. Empty means the step is a note (no command). */
+ command: string
+ /** Steps marked optional won't halt the plan if they fail. */
+ optional?: boolean
+}
+
+export interface InitRecipe {
+ id: string
+ name: string
+ summary: string
+ prerequisites: string[]
+ steps: InitStep[]
+}
+
+export const RECIPES: Record<string, InitRecipe> = {
+ 'next-postgres': {
+ id: 'next-postgres',
+ name: 'Next.js + Postgres',
+ summary: 'Next 15 App Router + Postgres via Prisma + a starter README.',
+ prerequisites: ['node', 'pnpm', 'psql'],
+ steps: [
+ {
+ description: 'Scaffold Next.js (app router, TS, Tailwind, src/, App Router, no eslint prompt)',
+ command: 'pnpm create next-app@latest . --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"',
+ },
+ {
+ description: 'Install Prisma + Postgres client',
+ command: 'pnpm add -D prisma && pnpm add @prisma/client',
+ },
+ {
+ description: 'Initialise Prisma schema',
+ command: 'pnpm exec prisma init --datasource-provider postgresql',
+ },
+ {
+ description: 'Create local Postgres database (skip if you already have one)',
+ command: 'createdb $(basename "$PWD")',
+ optional: true,
+ },
+ {
+ description: 'Write the first migration once you edit prisma/schema.prisma',
+ command: '',
+ },
+ ],
+ },
+ 'next-supabase': {
+ id: 'next-supabase',
+ name: 'Next.js + Supabase',
+ summary: 'Next 15 + @supabase/ssr ready for auth + RLS-backed APIs.',
+ prerequisites: ['node', 'pnpm', 'supabase'],
+ steps: [
+ {
+ description: 'Scaffold Next.js',
+ command: 'pnpm create next-app@latest . --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"',
+ },
+ {
+ description: 'Install Supabase SSR + JS client',
+ command: 'pnpm add @supabase/ssr @supabase/supabase-js',
+ },
+ {
+ description: 'Initialise Supabase locally (linked project)',
+ command: 'supabase init',
+ optional: true,
+ },
+ {
+ description: 'Stub .env.local with the required keys',
+ command: 'printf "NEXT_PUBLIC_SUPABASE_URL=\\nNEXT_PUBLIC_SUPABASE_ANON_KEY=\\nSUPABASE_SERVICE_ROLE_KEY=\\n" > .env.local',
+ },
+ ],
+ },
+ 'next-stripe': {
+ id: 'next-stripe',
+ name: 'Next.js + Stripe Checkout',
+ summary: 'Stripe-payment-ready Next.js with a /pricing + /api/checkout pair.',
+ prerequisites: ['node', 'pnpm', 'stripe'],
+ steps: [
+ {
+ description: 'Scaffold Next.js',
+ command: 'pnpm create next-app@latest . --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"',
+ },
+ {
+ description: 'Install Stripe + Server SDK',
+ command: 'pnpm add stripe @stripe/stripe-js',
+ },
+ {
+ description: 'Stub .env.local for Stripe keys',
+ command: 'printf "STRIPE_SECRET_KEY=\\nNEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=\\nSTRIPE_WEBHOOK_SECRET=\\n" > .env.local',
+ },
+ {
+ description: 'Pull the Stripe CLI for local webhook forwarding',
+ command: 'stripe listen --print-secret',
+ optional: true,
+ },
+ ],
+ },
+ 'rust-axum': {
+ id: 'rust-axum',
+ name: 'Rust + Axum',
+ summary: 'A new Cargo binary crate with Axum 0.7 + tokio + tracing pre-wired.',
+ prerequisites: ['cargo'],
+ steps: [
+ { description: 'Create the crate', command: 'cargo init --bin .' },
+ {
+ description: 'Add Axum + Tokio + tracing',
+ command: 'cargo add axum tokio --features tokio/full && cargo add tracing tracing-subscriber --features tracing-subscriber/env-filter',
+ },
+ {
+ description: 'Verify it compiles',
+ command: 'cargo check',
+ },
+ ],
+ },
+ 'vite-react': {
+ id: 'vite-react',
+ name: 'Vite + React + TypeScript',
+ summary: 'Vite 6 + React 19 + Tailwind 4 — the minimal SPA starter.',
+ prerequisites: ['node', 'pnpm'],
+ steps: [
+ {
+ description: 'Scaffold Vite with the React-TS template',
+ command: 'pnpm create vite@latest . --template react-ts',
+ },
+ { description: 'Install deps', command: 'pnpm install' },
+ {
+ description: 'Add Tailwind 4',
+ command: 'pnpm add -D tailwindcss @tailwindcss/postcss',
+ },
+ ],
+ },
+}
+
+export interface InitPlan {
+ recipe: InitRecipe
+ /** Combined prerequisite check command — fails fast when a required tool is missing. */
+ prereqCheck: string
+}
+
+/** Looks up a recipe by id (case-insensitive). Returns null when unknown. */
+export function findRecipe(id: string): InitRecipe | null {
+ const key = (id ?? '').trim().toLowerCase()
+ return RECIPES[key] ?? null
+}
+
+/** Builds the prerequisite-check shell snippet for a recipe. */
+export function prereqCheckCommand(recipe: InitRecipe): string {
+ if (!recipe.prerequisites.length) return ': # no prerequisites'
+ const tests = recipe.prerequisites
+ .map((p) => `command -v ${p} >/dev/null 2>&1 || { echo "missing: ${p}"; exit 127; }`)
+ .join(' && ')
+ return tests
+}
+
+/** Renders the plan as a markdown the model can quote / show the user. */
+export function renderInitPlan(recipe: InitRecipe): string {
+ const lines: string[] = []
+ lines.push(`# ${recipe.name}`)
+ lines.push('')
+ lines.push(recipe.summary)
+ lines.push('')
+ lines.push(`**Prerequisites:** ${recipe.prerequisites.join(', ') || '(none)'}`)
+ lines.push('')
+ lines.push('## Steps')
+ recipe.steps.forEach((s, i) => {
+ const opt = s.optional ? ' _(optional)_' : ''
+ lines.push(`### ${i + 1}. ${s.description}${opt}`)
+ if (s.command) {
+ lines.push('```sh')
+ lines.push(s.command)
+ lines.push('```')
+ } else {
+ lines.push('_(no command — manual step)_')
+ }
+ })
+ return lines.join('\n')
+}
+
+/** Lists every known recipe id with its one-line summary. */
+export function listRecipes(): Array<{ id: string; name: string; summary: string }> {
+ return Object.values(RECIPES).map((r) => ({ id: r.id, name: r.name, summary: r.summary }))
+}
diff --git a/src/api/agents/repo-map.ts b/src/api/agents/repo-map.ts
new file mode 100644
index 00000000..7684c47c
--- /dev/null
+++ b/src/api/agents/repo-map.ts
@@ -0,0 +1,70 @@
+import { backendCall } from '../backend'
+
+export interface RepoMapFile {
+ path: string
+ score: number
+ snippet: string
+}
+
+export interface RepoMapResult {
+ files: RepoMapFile[]
+ count: number
+}
+
+export interface FetchRepoMapInput {
+ workingDirectory: string
+ query?: string
+ limit?: number
+ signal?: AbortSignal
+}
+
+/**
+ * Calls the Bridge `repo_map` command. The Bridge walks the working
+ * directory, parses imports, runs PageRank, and returns the top-N ranked
+ * files. Pure I/O — no caching; the caller decides when to refresh.
+ */
+export async function fetchRepoMap(input: FetchRepoMapInput): Promise<RepoMapResult> {
+ if (!input.workingDirectory) {
+ return { files: [], count: 0 }
+ }
+ const out = await backendCall<RepoMapResult>('repo_map', {
+ workingDirectory: input.workingDirectory,
+ query: input.query,
+ limit: input.limit ?? 20,
+ })
+ return {
+ files: Array.isArray(out.files) ? out.files : [],
+ count: typeof out.count === 'number' ? out.count : 0,
+ }
+}
+
+/**
+ * Renders the repo-map result as a system-prompt section. Bounded by
+ * character count so a 200-file map can't crowd out the user's actual
+ * instructions. The format mirrors the Architect plan section — a
+ * stable header the editor model can refer back to.
+ */
+export function renderRepoMapSection(
+ result: RepoMapResult,
+ opts?: { maxChars?: number },
+): string {
+ if (!result.files.length) return ''
+ const maxChars = opts?.maxChars ?? 2400
+ const lines: string[] = []
+ lines.push('')
+ lines.push('')
+ lines.push(
+ 'REPO MAP — files ranked by import-graph PageRank. Use these as your',
+ )
+ lines.push('initial reading list before grepping for unrelated files.')
+ lines.push('')
+ let used = lines.join('\n').length
+ for (const f of result.files) {
+ const snippet = f.snippet ? ` — ${f.snippet}` : ''
+ const row = `- ${f.path}${snippet}`
+ if (used + row.length + 1 > maxChars) break
+ lines.push(row)
+ used += row.length + 1
+ }
+ return lines.join('\n')
+}
diff --git a/src/api/agents/test-runner.ts b/src/api/agents/test-runner.ts
new file mode 100644
index 00000000..e571a194
--- /dev/null
+++ b/src/api/agents/test-runner.ts
@@ -0,0 +1,204 @@
+/**
+ * Test-Driven Loop (Sprint B #4) — runner detection + output parsing.
+ *
+ * Pure helpers: no shell, no fetch. The `run_tests` builtin tool calls
+ * these on the bridge's `shell_execute` result so the model gets a
+ * structured payload — pass/fail counts, failing test names, a clipped
+ * tail of the runner output — instead of an opaque stdout dump.
+ */
+
+export type Runner = 'vitest' | 'cargo' | 'pytest' | 'jest' | 'unknown'
+
+export interface ParsedTestRun {
+ runner: Runner
+ passed: boolean
+ total: number
+ passedCount: number
+ failedCount: number
+ failedTests: string[]
+ /** Last ~40 lines of runner output for the model — full log when small. */
+ outputTail: string
+}
+
+/**
+ * Picks a runner from the contents of the working directory. Heuristic
+ * order: vitest > jest > cargo > pytest. The caller decides whether to
+ * use it or override via the tool argument.
+ */
+export function detectRunnerFromFiles(filenames: string[]): Runner {
+ const set = new Set(filenames.map((f) => f.toLowerCase()))
+ if (set.has('vitest.config.ts') || set.has('vitest.config.js')) return 'vitest'
+ if (set.has('cargo.toml')) return 'cargo'
+ if (set.has('jest.config.js') || set.has('jest.config.ts')) return 'jest'
+ if (set.has('pyproject.toml') || set.has('pytest.ini') || set.has('setup.cfg')) return 'pytest'
+ if (set.has('package.json')) {
+ // package.json without an explicit runner — assume vitest since LU
+ // itself uses vitest; consumers can override per-call.
+ return 'vitest'
+ }
+ return 'unknown'
+}
+
+/**
+ * Returns the shell command for a runner. Caller is responsible for cwd.
+ * We use `--no-color` flags where they exist to keep parser regex simple.
+ */
+export function commandForRunner(runner: Runner): string {
+ switch (runner) {
+ case 'vitest':
+ return 'pnpm exec vitest run --reporter=verbose --no-color'
+ case 'jest':
+ return 'npx jest --colors=false'
+ case 'cargo':
+ return 'cargo test --color never'
+ case 'pytest':
+ return 'pytest -v --color=no'
+ default:
+ return ''
+ }
+}
+
+function tailLines(s: string, n: number): string {
+ const lines = s.split('\n')
+ if (lines.length <= n) return s
+ return lines.slice(-n).join('\n')
+}
+
+// ── Parsers ─────────────────────────────────────────────────────────
+
+/**
+ * Vitest summary lines look like:
+ * Test Files 3 failed | 100 passed (103)
+ * Tests 5 failed | 2249 passed (2254)
+ * ❯ src/foo.test.ts > module > some test name
+ */
+export function parseVitest(out: string): ParsedTestRun {
+ const lines = out.split('\n')
+ let passedCount = 0
+ let failedCount = 0
+ for (const line of lines) {
+ const m = line.match(/Tests\s+(?:(\d+)\s+failed\s*\|\s*)?(\d+)\s+passed/i)
+ if (m) {
+ failedCount = m[1] ? parseInt(m[1], 10) : 0
+ passedCount = parseInt(m[2], 10)
+ break
+ }
+ }
+ const failedTests: string[] = []
+ for (const line of lines) {
+ // The verbose vitest reporter prefixes failures with × or ✗ or FAIL.
+ const m = line.match(/^\s*(?:×|✗|FAIL)\s+(.+?)(?:\s+\d+ms)?$/)
+ if (m && m[1]) failedTests.push(m[1].trim())
+ }
+ const total = passedCount + failedCount
+ return {
+ runner: 'vitest',
+ passed: failedCount === 0 && total > 0,
+ total,
+ passedCount,
+ failedCount,
+ failedTests,
+ outputTail: tailLines(out, 40),
+ }
+}
+
+/**
+ * Cargo summary:
+ * test result: ok. 80 passed; 0 failed; 0 ignored; 0 measured
+ * test commands::repo_map::tests::pagerank_handles_empty_graph ... ok
+ * test commands::repo_map::tests::pagerank_handles_empty_graph ... FAILED
+ */
+export function parseCargo(out: string): ParsedTestRun {
+ let passedCount = 0
+ let failedCount = 0
+ const lines = out.split('\n')
+ for (const line of lines) {
+ const m = line.match(/test result:\s+\w+\.\s+(\d+)\s+passed;\s+(\d+)\s+failed/)
+ if (m) {
+ passedCount = parseInt(m[1], 10)
+ failedCount = parseInt(m[2], 10)
+ break
+ }
+ }
+ const failedTests: string[] = []
+ for (const line of lines) {
+ const m = line.match(/^test\s+(\S+)\s+\.\.\.\s+FAILED/)
+ if (m) failedTests.push(m[1])
+ }
+ const total = passedCount + failedCount
+ return {
+ runner: 'cargo',
+ passed: failedCount === 0 && total > 0,
+ total,
+ passedCount,
+ failedCount,
+ failedTests,
+ outputTail: tailLines(out, 40),
+ }
+}
+
+/**
+ * Pytest summary:
+ * ===== 12 passed, 1 failed in 0.42s =====
+ * FAILED tests/test_foo.py::test_bar - AssertionError: ...
+ */
+export function parsePytest(out: string): ParsedTestRun {
+ let passedCount = 0
+ let failedCount = 0
+ const lines = out.split('\n')
+ for (const line of lines) {
+ const pm = line.match(/(\d+)\s+passed/)
+ const fm = line.match(/(\d+)\s+failed/)
+ if (pm) passedCount = parseInt(pm[1], 10)
+ if (fm) failedCount = parseInt(fm[1], 10)
+ if (pm || fm) break
+ }
+ const failedTests: string[] = []
+ for (const line of lines) {
+ const m = line.match(/^FAILED\s+(\S+?)(?:\s+-.*)?$/)
+ if (m) failedTests.push(m[1])
+ }
+ const total = passedCount + failedCount
+ return {
+ runner: 'pytest',
+ passed: failedCount === 0 && total > 0,
+ total,
+ passedCount,
+ failedCount,
+ failedTests,
+ outputTail: tailLines(out, 40),
+ }
+}
+
+export function parseForRunner(runner: Runner, out: string): ParsedTestRun {
+ switch (runner) {
+ case 'vitest':
+ case 'jest':
+ return { ...parseVitest(out), runner }
+ case 'cargo':
+ return parseCargo(out)
+ case 'pytest':
+ return parsePytest(out)
+ default:
+ return {
+ runner: 'unknown',
+ passed: false,
+ total: 0,
+ passedCount: 0,
+ failedCount: 0,
+ failedTests: [],
+ outputTail: tailLines(out, 40),
+ }
+ }
+}
+
+/** Renders a ParsedTestRun as a string for the model. Compact + greppable. */
+export function renderResult(r: ParsedTestRun): string {
+ const status = r.passed ? 'PASSED' : r.total === 0 ? 'NO TESTS / UNPARSEABLE' : 'FAILED'
+ const head = `${status} (${r.runner}): ${r.passedCount}/${r.total} passed, ${r.failedCount} failed.`
+ const failed = r.failedTests.length
+ ? `\nFailing tests:\n${r.failedTests.map((t) => `- ${t}`).join('\n')}`
+ : ''
+ const tail = r.outputTail ? `\n---\n${r.outputTail}` : ''
+ return `${head}${failed}${tail}`
+}
diff --git a/src/api/agents/workspace-resolve.ts b/src/api/agents/workspace-resolve.ts
new file mode 100644
index 00000000..eb09ba54
--- /dev/null
+++ b/src/api/agents/workspace-resolve.ts
@@ -0,0 +1,32 @@
+/**
+ * Workspace resolver — shared lookup for Codex + Agent (Underlying
+ * unification, Sprint C 2026-05).
+ *
+ * Lookup order:
+ * 1. Per-chat workspace from `agentModeStore`
+ * 2. `settings.defaultWorkspace`
+ * 3. `null` — caller falls back to sandbox / per-thread cwd
+ */
+
+import type { AgentWorkspace } from '../../types/agent-workspace'
+
+export interface ResolveInput {
+ perChat: AgentWorkspace | undefined
+ defaultWorkspace: AgentWorkspace | null
+}
+
+export function resolveWorkspace({ perChat, defaultWorkspace }: ResolveInput): AgentWorkspace | null {
+ if (perChat) return perChat
+ if (defaultWorkspace) return defaultWorkspace
+ return null
+}
+
+/**
+ * Folder-path extraction with the same precedence as resolveWorkspace.
+ * Returns `null` when neither layer pinned a real path (sandbox or unset).
+ */
+export function resolveWorkspacePath({ perChat, defaultWorkspace }: ResolveInput): string | null {
+ const ws = resolveWorkspace({ perChat, defaultWorkspace })
+ if (!ws || ws.kind !== 'folder' || !ws.path) return null
+ return ws.path
+}
diff --git a/src/lib/diff.ts b/src/lib/diff.ts
new file mode 100644
index 00000000..067bf7de
--- /dev/null
+++ b/src/lib/diff.ts
@@ -0,0 +1,264 @@
+// Minimal text-diff helpers for the Codex file_change event view.
+//
+// Not a full Myers diff — we use the LCS table for line-granularity, which
+// is enough for "show me what the agent edited" and avoids pulling in
+// diff-match-patch (~120 kB gz) just for the chat surface.
+//
+// `computeUnifiedDiff` returns a GNU-unified-diff string:
+//
+// --- a/<path>
+// +++ b/<path>
+// @@ -3,4 +3,5 @@
+// context line
+// -removed
+// +added
+//
+// `parseUnifiedDiff` round-trips the same shape back to typed hunks so the
+// renderer can paint each line without re-tokenising the string.
+
+export interface DiffLine {
+ kind: 'context' | 'add' | 'remove' | 'hunk' | 'header'
+ text: string
+ oldLine?: number
+ newLine?: number
+}
+
+export interface ParsedDiff {
+ path: string
+ lines: DiffLine[]
+ /** Summary stats. */
+ added: number
+ removed: number
+}
+
+/**
+ * Build a unified diff between two text blobs at line granularity.
+ *
+ * `context` controls how many unchanged lines to keep around each hunk;
+ * 3 mirrors `git diff` and stays readable inside the chat panel.
+ */
+export function computeUnifiedDiff(
+ path: string,
+ oldText: string,
+ newText: string,
+ context = 3,
+): string {
+ const a = oldText === '' ? [] : oldText.split('\n')
+ const b = newText === '' ? [] : newText.split('\n')
+ const ops = diffLines(a, b)
+ if (ops.every((o) => o.kind === 'equal')) {
+ return ''
+ }
+
+ const out: string[] = [`--- a/${path}`, `+++ b/${path}`]
+ let i = 0
+ let aLine = 0
+ let bLine = 0
+ while (i < ops.length) {
+ // Skip stretches of equal lines that don't sit near a change.
+ if (ops[i].kind === 'equal') {
+ const skip = nearestChange(ops, i)
+ if (skip === -1) {
+ // Trailing equal block — nothing left to report.
+ aLine += ops[i].text.length
+ bLine += ops[i].text.length
+ i++
+ continue
+ }
+ const equalLen = ops[i].text.length
+ const leading = Math.min(context, equalLen)
+ const dropped = equalLen - leading
+ aLine += dropped
+ bLine += dropped
+ // Re-enter the loop on the leading-context boundary.
+ ops[i] = { kind: 'equal', text: ops[i].text.slice(dropped) }
+ }
+
+ // Collect a hunk: leading context + change run + trailing context.
+ const hunkStartA = aLine
+ const hunkStartB = bLine
+ const hunkLines: string[] = []
+ while (i < ops.length) {
+ const op = ops[i]
+ if (op.kind === 'equal') {
+ // Stop the hunk after `context` trailing equal lines OR if a far
+ // change is more than 2*context lines away.
+ const reach = nearestChange(ops, i)
+ const headRoom = op.text.length
+ if (reach === -1 || reach - i > 1) {
+ const trailing = Math.min(context, headRoom)
+ for (let k = 0; k < trailing; k++) {
+ hunkLines.push(' ' + op.text[k])
+ }
+ aLine += headRoom
+ bLine += headRoom
+ if (reach === -1) {
+ i = ops.length
+ } else {
+ const remaining = headRoom - trailing
+ // Stash whatever's left of the equal block back into ops for the
+ // *next* hunk's leading context.
+ ops[i] = { kind: 'equal', text: op.text.slice(trailing) }
+ aLine -= remaining
+ bLine -= remaining
+ }
+ break
+ }
+ for (const t of op.text) {
+ hunkLines.push(' ' + t)
+ }
+ aLine += headRoom
+ bLine += headRoom
+ i++
+ continue
+ }
+ if (op.kind === 'remove') {
+ for (const t of op.text) {
+ hunkLines.push('-' + t)
+ }
+ aLine += op.text.length
+ i++
+ continue
+ }
+ // add
+ for (const t of op.text) {
+ hunkLines.push('+' + t)
+ }
+ bLine += op.text.length
+ i++
+ }
+
+ const oldLen = hunkLines.filter((l) => l.startsWith(' ') || l.startsWith('-'))
+ .length
+ const newLen = hunkLines.filter((l) => l.startsWith(' ') || l.startsWith('+'))
+ .length
+ out.push(
+ `@@ -${hunkStartA + 1},${oldLen} +${hunkStartB + 1},${newLen} @@`,
+ )
+ out.push(...hunkLines)
+ }
+ return out.join('\n')
+}
+
+export function parseUnifiedDiff(diff: string): ParsedDiff {
+ const lines = diff.split('\n')
+ const out: DiffLine[] = []
+ let path = ''
+ let oldLine = 0
+ let newLine = 0
+ let added = 0
+ let removed = 0
+
+ for (const raw of lines) {
+ if (raw.startsWith('--- a/')) {
+ path = raw.slice(6)
+ out.push({ kind: 'header', text: raw })
+ continue
+ }
+ if (raw.startsWith('+++ b/')) {
+ if (!path) path = raw.slice(6)
+ out.push({ kind: 'header', text: raw })
+ continue
+ }
+ if (raw.startsWith('@@')) {
+ const m = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw)
+ if (m) {
+ oldLine = parseInt(m[1], 10)
+ newLine = parseInt(m[2], 10)
+ }
+ out.push({ kind: 'hunk', text: raw })
+ continue
+ }
+ if (raw.startsWith('+')) {
+ out.push({ kind: 'add', text: raw.slice(1), newLine })
+ added++
+ newLine++
+ continue
+ }
+ if (raw.startsWith('-')) {
+ out.push({ kind: 'remove', text: raw.slice(1), oldLine })
+ removed++
+ oldLine++
+ continue
+ }
+ if (raw.startsWith(' ')) {
+ out.push({ kind: 'context', text: raw.slice(1), oldLine, newLine })
+ oldLine++
+ newLine++
+ continue
+ }
+ // Stray line (blank, malformed) — keep as context so the renderer can
+ // still show it without throwing.
+ if (raw !== '') {
+ out.push({ kind: 'context', text: raw })
+ }
+ }
+ return { path, lines: out, added, removed }
+}
+
+// ── internals ──────────────────────────────────────────────────────
+
+type Op =
+ | { kind: 'equal'; text: string[] }
+ | { kind: 'add'; text: string[] }
+ | { kind: 'remove'; text: string[] }
+
+/** LCS-based line diff. Grouped into op runs for a compact unified format. */
+function diffLines(a: string[], b: string[]): Op[] {
+ const n = a.length
+ const m = b.length
+ // Classic dynamic-programming LCS table. Sufficient for chat-sized files
+ // (we cap upstream).
+ const dp: number[][] = Array.from({ length: n + 1 }, () =>
+ new Array(m + 1).fill(0),
+ )
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ if (a[i] === b[j]) {
+ dp[i][j] = dp[i + 1][j + 1] + 1
+ } else {
+ dp[i][j] = Math.max(dp[i + 1][j], dp[i][j + 1])
+ }
+ }
+ }
+
+ const ops: Op[] = []
+ let i = 0
+ let j = 0
+ while (i < n && j < m) {
+ if (a[i] === b[j]) {
+ append(ops, { kind: 'equal', text: [a[i]] })
+ i++
+ j++
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
+ append(ops, { kind: 'remove', text: [a[i]] })
+ i++
+ } else {
+ append(ops, { kind: 'add', text: [b[j]] })
+ j++
+ }
+ }
+ while (i < n) {
+ append(ops, { kind: 'remove', text: [a[i++]] })
+ }
+ while (j < m) {
+ append(ops, { kind: 'add', text: [b[j++]] })
+ }
+ return ops
+}
+
+function append(ops: Op[], op: Op): void {
+ const last = ops[ops.length - 1]
+ if (last && last.kind === op.kind) {
+ last.text.push(...op.text)
+ } else {
+ ops.push(op)
+ }
+}
+
+function nearestChange(ops: Op[], from: number): number {
+ for (let k = from + 1; k < ops.length; k++) {
+ if (ops[k].kind !== 'equal') return k
+ }
+ return -1
+}
diff --git a/src/lib/lurules.ts b/src/lib/lurules.ts
new file mode 100644
index 00000000..0eca4ddd
--- /dev/null
+++ b/src/lib/lurules.ts
@@ -0,0 +1,97 @@
+// `.lurules` — per-repo Codex configuration, table-stakes for any 2026
+// coding agent (Cursor → `.cursorrules`, Cline → `.clinerules`, Claude
+// Code → `CLAUDE.md` hooks, Continue → `.continue/config.yaml`).
+//
+// Our shape is the minimum that actually delivers value: a plain-text
+// file at the working-dir root whose contents get appended to the Codex
+// system prompt verbatim. The agent reads it as project conventions —
+// "use 2-space indent", "never touch src/generated", "always run pnpm
+// typecheck after edits", etc.
+//
+// We deliberately don't parse a structured format yet: the bigger
+// payoff is just letting the user write prose. Tool-allow-lists and
+// model-pinning live in Settings; bringing them into the rules file is
+// a future step once we have actual usage signal.
+//
+// Caveats:
+// - We only look at the workDir root, not parents. A monorepo can put
+// one file at the repo root and it applies to every per-chat
+// workspace beneath it via the user's own symlink / shared rules
+// directory (`.lurules → ../.lurules`).
+// - We cap the file at 10 kB. A 100 kB rules file would dominate the
+// context window of a 4k/8k local model and is almost always a sign
+// the user wants a README, not agent guidance.
+
+export const LURULES_FILENAME = '.lurules'
+export const LURULES_MAX_BYTES = 10 * 1024
+
+export interface LoadedRules {
+ /** Absolute path the rules came from. */
+ path: string
+ /** File contents, trimmed and length-capped. */
+ text: string
+ /** True when the source file exceeded LURULES_MAX_BYTES and was truncated. */
+ truncated: boolean
+}
+
+export interface RulesReader {
+ read(path: string): Promise<string | null>
+}
+
+/**
+ * Try to load `.lurules` from `workDir`. Returns null when the file
+ * doesn't exist or the reader errored — both treated identically so the
+ * caller doesn't need to know whether the failure was "no file" vs.
+ * "filesystem permission denied".
+ */
+export async function loadLurules(
+ workDir: string,
+ reader: RulesReader,
+): Promise<LoadedRules | null> {
+ if (!workDir) return null
+ const path = joinPath(workDir, LURULES_FILENAME)
+ let raw: string | null
+ try {
+ raw = await reader.read(path)
+ } catch {
+ return null
+ }
+ if (raw === null || raw === undefined) return null
+ const trimmed = raw.trim()
+ if (trimmed.length === 0) return null
+
+ const truncated = trimmed.length > LURULES_MAX_BYTES
+ const text = truncated ? trimmed.slice(0, LURULES_MAX_BYTES) : trimmed
+ return { path, text, truncated }
+}
+
+/**
+ * Wrap loaded rules in a system-prompt section that's clearly fenced
+ * off from the agent's instructions. Returns the empty string for a
+ * null input so callers can `prompt += renderRulesSection(rules)`
+ * unconditionally.
+ */
+export function renderRulesSection(rules: LoadedRules | null): string {
+ if (!rules) return ''
+ const truncatedNotice = rules.truncated
+ ? `\n[truncated to ${LURULES_MAX_BYTES} bytes — split the file if you need more]`
+ : ''
+ return [
+ '',
+ '─── Project rules from .lurules ────────────────────────────',
+ 'These are project conventions defined by the user. Follow them',
+ 'unless the user explicitly overrides one in this turn.',
+ '',
+ rules.text,
+ truncatedNotice,
+ '─── end .lurules ───────────────────────────────────────────',
+ '',
+ ].join('\n')
+}
+
+function joinPath(dir: string, name: string): string {
+ // Cross-platform join without bringing node:path into the client bundle.
+ const slash = dir.includes('\\') && !dir.includes('/') ? '\\' : '/'
+ const trimmed = dir.replace(/[\\/]+$/, '')
+ return `${trimmed}${slash}${name}`
+}
diff --git a/src/types/agent-workspace.ts b/src/types/agent-workspace.ts
new file mode 100644
index 00000000..60b693e9
--- /dev/null
+++ b/src/types/agent-workspace.ts
@@ -0,0 +1,25 @@
+// Where an agent-mode chat operates on disk.
+//
+// 'sandbox' → bridge resolves relative paths under
+// `~/agent-workspace/<chat-slug>/`. Isolated, throwaway, safe.
+//
+// 'folder' → the user picked a real directory (via Bridge `pick_folder`).
+// Relative paths land under that path; the agent can read + modify the
+// user's actual repo. Same wire shape as Codex.
+export type AgentWorkspaceKind = 'sandbox' | 'folder'
+
+export interface AgentWorkspace {
+ kind: AgentWorkspaceKind
+ /** Absolute path. Set when kind === 'folder', undefined for sandbox. */
+ path?: string
+ /**
+ * Additional absolute repo paths the agent can read/write via *absolute*
+ * paths. Tool resolution still anchors relative paths to `path`; extras
+ * are listed in the system prompt so the model can address them by
+ * absolute path. Use case: "sync this API in repo-A with the client in
+ * repo-B" — pick repo-A as the primary, add repo-B as an extra.
+ */
+ extraPaths?: string[]
+}
+
+export const SANDBOX_WORKSPACE: AgentWorkspace = { kind: 'sandbox' }