From 6e8a6a15bcc59a727c18bc2ad9100eb08dbe3b0d Mon Sep 17 00:00:00 2001 From: Croissant Le Doux Date: Wed, 8 Jul 2026 22:08:37 -0400 Subject: [PATCH] =?UTF-8?q?feat:=20capture=5Fwork=20=E2=80=94=20braindump?= =?UTF-8?q?=20=E2=86=92=20decomposed=20issues=20=E2=86=92=20filed=20in=20g?= =?UTF-8?q?itea=20(P4)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The last big agent capability. In the Capture screen, a rough braindump runs real big-model decomposition into a small, estimated issue set; you review/edit the labels and approve, and the issues are opened in gitea. This is the one place the big model earns its keep (docs/agent-tools.md). core (@commitea/core): - capture-work: PROPOSE_ISSUES_TOOL + CAPTURE_SYSTEM; captureWork(complete, dump) forces a single structured decomposition and returns validated issues; parseCaptureArgs drops blank titles + invalid est/p labels. ProposedIssue / CaptureProposal. - gitea client: createIssue({title, body?, labelIds?}) → POST /issues, normalized. app: - model bridge model:capture runs captureWork on the (loaded) big model. - gitea bridge gitea:createIssues opens each approved issue with its est/* + p/* labels (reusing the #41 label-id resolver — zero-pollution, no invented labels). - Capture screen: when a model is configured, "Brew tickets" runs real capture and "Approve all" files the set; otherwise the scripted demo interview runs. Fixed a race — the brew handler re-checks model status at click time so a configured model never falls into the scripted path before status resolves. Verified: 108 core tests green (7 capture + createIssue added), desktop typecheck clean, 14 fixture e2e green. Gated live e2e against gemma-4-26b: the auth braindump → 3 real tickets ("Resolve token refresh + session staleness" est/3d p/1, "Fix webhook double-firing" est/2d p/2, "Write auth setup docs" est/1d p/3), reviewable and editable; Discard so the test files nothing (createIssue POST is unit-tested). Co-Authored-By: Claude Opus 4.8 (1M context) --- apps/desktop/e2e/live-capture.spec.ts | 37 +++++ apps/desktop/src/main/gitea.ts | 17 +++ apps/desktop/src/main/model.ts | 16 ++ apps/desktop/src/preload/index.ts | 4 + .../src/components/screens/capture-screen.tsx | 138 +++++++++++++++--- apps/desktop/src/renderer/src/global.d.ts | 14 ++ packages/core/src/agent/capture-work.test.ts | 65 +++++++++ packages/core/src/agent/capture-work.ts | 109 ++++++++++++++ packages/core/src/gitea/client.test.ts | 12 ++ packages/core/src/gitea/client.ts | 10 ++ packages/core/src/index.ts | 2 + 11 files changed, 402 insertions(+), 22 deletions(-) create mode 100644 apps/desktop/e2e/live-capture.spec.ts create mode 100644 packages/core/src/agent/capture-work.test.ts create mode 100644 packages/core/src/agent/capture-work.ts diff --git a/apps/desktop/e2e/live-capture.spec.ts b/apps/desktop/e2e/live-capture.spec.ts new file mode 100644 index 0000000..c431e08 --- /dev/null +++ b/apps/desktop/e2e/live-capture.spec.ts @@ -0,0 +1,37 @@ +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { _electron as electron, expect, test } from '@playwright/test' + +const here = dirname(fileURLToPath(import.meta.url)) +const MAIN = join(here, '..', 'out', 'main', 'index.js') + +// Opt-in (GITEA_LIVE=1 + COMMITEA_MODEL_LIVE=1 + a local model on :1234). Launches +// WITHOUT COMMITEA_E2E so capture_work runs the real decomposition. It Discards at +// the end so the run never files junk issues (the create-issue POST is unit-tested). +test.describe('live capture_work', () => { + test('decomposes a braindump into a reviewable ticket set', async () => { + test.skip(!process.env.GITEA_LIVE || !process.env.COMMITEA_MODEL_LIVE, 'live model test — opt-in') + test.setTimeout(300_000) + const app = await electron.launch({ args: [MAIN], env: { ...process.env } }) + const win = await app.firstWindow() + await win.waitForLoadState('domcontentloaded') + const rail = win.getByRole('navigation', { name: 'Primary' }) + + await rail.getByRole('button', { name: 'Capture' }).click() + await expect(win.getByRole('heading', { name: 'Capture' })).toBeVisible() + // the braindump is prefilled; run the real decomposition + await win.getByRole('button', { name: 'Brew tickets' }).click() + + // capture_work → the review tray with a real, estimated ticket set + await expect(win.getByText(/tickets · ~\d+d of work/)).toBeVisible({ timeout: 240_000 }) + await expect(win.getByRole('button', { name: 'Approve all' })).toBeVisible() + await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-capture.png'), fullPage: true, animations: 'disabled' }) + + // Discard — never file junk issues into the real repo from a test + await win.getByRole('button', { name: 'Discard' }).click() + await expect(win.getByRole('button', { name: 'Brew tickets' })).toBeVisible() + + await app.close() + }) +}) diff --git a/apps/desktop/src/main/gitea.ts b/apps/desktop/src/main/gitea.ts index 3cb6775..b50ae38 100644 --- a/apps/desktop/src/main/gitea.ts +++ b/apps/desktop/src/main/gitea.ts @@ -124,4 +124,21 @@ export function registerGiteaIpc(): void { const issue = await client.getIssue(change.issue) return { ok: true as const, plan, issue } }) + + // capture_work filing: open each approved issue with its est/* + p/* labels. + // Only touches the CommiTea label namespaces — no invented labels (zero-pollution). + ipcMain.handle( + 'gitea:createIssues', + async (_event, issues: { title: string; body?: string; estimate?: string; priority?: string }[]) => { + if (!client) return { ok: false as const, reason: 'unconfigured' as const } + const created: { number: number; title: string }[] = [] + for (const it of issues) { + const names = [it.estimate, it.priority].filter((n): n is string => !!n) + const labelIds = await resolveLabelIds(names) + const issue = await client.createIssue({ title: it.title, body: it.body, labelIds }) + created.push({ number: issue.number, title: issue.title }) + } + return { ok: true as const, created } + }, + ) } diff --git a/apps/desktop/src/main/model.ts b/apps/desktop/src/main/model.ts index 0c2016f..79cbdd4 100644 --- a/apps/desktop/src/main/model.ts +++ b/apps/desktop/src/main/model.ts @@ -9,6 +9,7 @@ import { buildProjectView, + captureWork, type ChangeProposal, type ChatMessage, createChatClient, @@ -120,4 +121,19 @@ export function registerModelIpc(): void { return { ok: false as const, reason: 'error' as const, message: e instanceof Error ? e.message : String(e) } } }) + + // capture_work — braindump → proposed issue set. The big model does the + // decomposition (with one loaded local model, that's the loaded one). Returns + // a proposal; nothing is filed until the Capture tray approves it. + ipcMain.handle('model:capture', async (_event, braindump: string) => { + if (!router) return { ok: false as const, reason: 'unconfigured' as const } + const model = await resolveLoadedModel(router.big.baseUrl, router.big.model) + const chat = createChatClient({ ...router.big, model }, fetch) + try { + const proposal = await captureWork((m, t) => chat.complete(m, t), braindump) + return { ok: true as const, ...proposal } + } catch (e) { + return { ok: false as const, reason: 'error' as const, message: e instanceof Error ? e.message : String(e) } + } + }) } diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index c20fc3b..f24a1de 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -11,12 +11,16 @@ const api = { getIssue: (index: number) => ipcRenderer.invoke('gitea:getIssue', index), /** Apply an estimate/priority change (the write path); resolves to the plan + fresh issue. */ applyChange: (change: unknown) => ipcRenderer.invoke('gitea:applyChange', change), + /** File a set of captured issues with their est/* + p/* labels. */ + createIssues: (issues: unknown) => ipcRenderer.invoke('gitea:createIssues', issues), }, model: { /** Whether a model endpoint is configured (else the UI keeps the scripted Reginald). */ status: () => ipcRenderer.invoke('model:status'), /** One agent turn: messages in, Reginald's prose + the tools it consulted out. */ chat: (messages: unknown) => ipcRenderer.invoke('model:chat', messages), + /** Decompose a braindump into a proposed issue set (capture_work). */ + capture: (braindump: string) => ipcRenderer.invoke('model:capture', braindump), }, } diff --git a/apps/desktop/src/renderer/src/components/screens/capture-screen.tsx b/apps/desktop/src/renderer/src/components/screens/capture-screen.tsx index 6d0c71d..9ac3229 100644 --- a/apps/desktop/src/renderer/src/components/screens/capture-screen.tsx +++ b/apps/desktop/src/renderer/src/components/screens/capture-screen.tsx @@ -1,8 +1,12 @@ import React from 'react' +import type { ProposedIssue } from '@commitea/core' + import { Badge, Button, Card, Icon, Select, Tag } from '../ui/index.js' -// Capture interview — braindump → interview → approved ticket set (< 2 min) +// Capture interview — braindump → interview → approved ticket set (< 2 min). +// With a model configured, "Brew tickets" runs real capture_work decomposition +// and "Approve all" files the issues in gitea; otherwise the scripted demo runs. interface Ticket { title: string @@ -30,6 +34,64 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) { const [webEst, setWebEst] = React.useState(null) const [secs, setSecs] = React.useState(0) + // live capture_work path (real model + gitea writes) + const [live, setLive] = React.useState(false) + const [brewing, setBrewing] = React.useState(false) + const [liveTickets, setLiveTickets] = React.useState(null) + const [filedCount, setFiledCount] = React.useState(0) + const [error, setError] = React.useState(null) + + React.useEffect(() => { + let alive = true + window.commitea.model.status().then((s) => { if (alive) setLive(s.configured) }).catch(() => {}) + return () => { alive = false } + }, []) + + const editTicket = (i: number, field: 'estimate' | 'priority', value: string) => + setLiveTickets((ts) => (ts ? ts.map((t, j) => (j === i ? { ...t, [field]: value } : t)) : ts)) + + // Decide live-vs-scripted at click time: re-check status if it hasn't resolved + // yet, so a configured model never falls into the scripted interview by a race. + const onBrew = async () => { + const configured = live || (await window.commitea.model.status().then((s) => s.configured).catch(() => false)) + if (configured) { + setLive(true) + brew() + } else { + setStage('interview') + } + } + + const brew = () => { + setError(null) + setBrewing(true) + window.commitea.model + .capture(dump) + .then((res) => { + setBrewing(false) + if (res.ok && res.issues.length) { + setLiveTickets(res.issues) + setStage('review') + } else { + setError(res.ok ? 'I could not find concrete work in that — try a bit more detail.' : `Capture failed: ${res.reason === 'error' ? res.message : 'no model'}`) + } + }) + .catch(() => { setBrewing(false); setError('I could not reach the model.') }) + } + + const fileLive = () => { + if (!liveTickets) return + setBrewing(true) + window.commitea.gitea + .createIssues(liveTickets) + .then((res) => { + setBrewing(false) + if (res.ok) { setFiledCount(res.created.length); setStage('filed') } + else setError('Filing failed — gitea is not configured.') + }) + .catch(() => { setBrewing(false); setError('Filing failed.') }) + } + const running = stage === 'interview' || stage === 'review' React.useEffect(() => { if (!running) return @@ -63,19 +125,23 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) { else setStage('review') } - // draft tickets build as the interview progresses - const tickets: Ticket[] = [] + // draft tickets build as the interview progresses (scripted demo path) + const scripted: Ticket[] = [] if (split === true) { - tickets.push({ title: 'Token refresh: retry with backoff', est: 'est/2d', p: 'p/2' }) - tickets.push({ title: 'Session storage: stale reads on wake', est: 'est/1d', p: 'p/3' }) + scripted.push({ title: 'Token refresh: retry with backoff', est: 'est/2d', p: 'p/2' }) + scripted.push({ title: 'Session storage: stale reads on wake', est: 'est/1d', p: 'p/3' }) } else if (split === false) { - tickets.push({ title: 'Auth: token refresh + session storage', est: 'est/3d', p: 'p/2' }) + scripted.push({ title: 'Auth: token refresh + session storage', est: 'est/3d', p: 'p/2' }) } - if (webEst) tickets.push({ title: 'Webhook debounce: double-fire guard', est: webEst, p: 'p/1', dep: 'blocked by auth work' }) - if (stage === 'review' || stage === 'filed') { - tickets.push({ title: 'Docs: auth setup guide', est: 'est/1d', p: 'p/4', byReginald: true }) + if (webEst) scripted.push({ title: 'Webhook debounce: double-fire guard', est: webEst, p: 'p/1', dep: 'blocked by auth work' }) + if (!live && (stage === 'review' || stage === 'filed')) { + scripted.push({ title: 'Docs: auth setup guide', est: 'est/1d', p: 'p/4', byReginald: true }) } - const totalDays = tickets.reduce((n, t) => n + parseInt(t.est.replace('est/', '')), 0) + // real capture_work output overrides the scripted set when present + const tickets: Ticket[] = liveTickets + ? liveTickets.map((i) => ({ title: i.title, est: i.estimate ?? 'est/2d', p: i.priority ?? 'p/3' })) + : scripted + const totalDays = tickets.reduce((n, t) => n + parseInt(t.est.replace('est/', ''), 10), 0) const estOptions = ['est/1d', 'est/2d', 'est/3d', 'est/5d', 'est/8d'].map((v) => ({ value: v, label: v })) const pOptions = ['p/1', 'p/2', 'p/3', 'p/4'].map((v) => ({ value: v, label: v })) @@ -96,8 +162,20 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) {
{editable ? ( <> - + editTicket(i, 'priority', e.target.value)} + style={{ width: 76 }} + /> ) : ( <> @@ -144,7 +222,12 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) {

Sentences, fragments, grievances — all welcome. I'll sort it into tickets and only ask what I can't infer.

- + + {error ? ( +

{error}

+ ) : null} ) : null} @@ -174,15 +257,26 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) {
- - + + }> -

- Beta's 80% window moves Mar 3–12 → Mar 5–14. Capacity absorbs the rest. -

-

- I added the docs ticket you mentioned and wired the dependency. Shall I make it so? -

+ {live ? ( +

+ {tickets.length} issue{tickets.length === 1 ? '' : 's'} from your braindump, estimated and prioritized. + Adjust the labels, then approve — I'll open them in gitea with only est/* and p/* labels. +

+ ) : ( + <> +

+ Beta's 80% window moves Mar 3–12 → Mar 5–14. Capacity absorbs the rest. +

+

+ I added the docs ticket you mentioned and wired the dependency. Shall I make it so? +

+ + )}
@@ -195,7 +289,7 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) { Filed

- {tickets.length} issues opened in gitea with est/* and p/* labels — nothing else touched. + {live ? filedCount : tickets.length} issues opened in gitea with est/* and p/* labels — nothing else touched.

Elapsed {clock} — under budget. No bot comments, no synthetic issues; your repo remains yours. diff --git a/apps/desktop/src/renderer/src/global.d.ts b/apps/desktop/src/renderer/src/global.d.ts index 835eb4e..1583ae1 100644 --- a/apps/desktop/src/renderer/src/global.d.ts +++ b/apps/desktop/src/renderer/src/global.d.ts @@ -2,12 +2,14 @@ import type { AgentStep, ChangeProposal, ChatMessage, + CaptureProposal, DependencyEdge, GiteaIssue, GiteaMilestone, IssueChange, LabelPlan, LifecycleEvent, + ProposedIssue, } from '@commitea/core' /** The result of a write through the bridge. */ @@ -15,6 +17,16 @@ export type ApplyChangeResult = | { ok: false; reason: 'unconfigured' } | { ok: true; plan: LabelPlan; issue: GiteaIssue } +/** The result of filing captured issues. */ +export type CreateIssuesResult = + | { ok: false; reason: 'unconfigured' } + | { ok: true; created: { number: number; title: string }[] } + +/** The result of a capture_work decomposition. */ +export type CaptureResult = + | { ok: false; reason: 'unconfigured' | 'error'; message?: string } + | ({ ok: true } & CaptureProposal) + /** The gitea bridge exposed by the preload over IPC (main-process backed). */ export interface GiteaBridge { status(): Promise<{ configured: boolean; repo: string | null }> @@ -28,6 +40,7 @@ export interface GiteaBridge { }> getIssue(index: number): Promise applyChange(change: IssueChange): Promise + createIssues(issues: ProposedIssue[]): Promise } /** One agent turn's result. */ @@ -39,6 +52,7 @@ export type ChatResult = export interface ModelBridge { status(): Promise<{ configured: boolean; model: string | null }> chat(messages: ChatMessage[]): Promise + capture(braindump: string): Promise } declare global { diff --git a/packages/core/src/agent/capture-work.test.ts b/packages/core/src/agent/capture-work.test.ts new file mode 100644 index 0000000..b34b450 --- /dev/null +++ b/packages/core/src/agent/capture-work.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' + +import type { CompletionResult } from './chat-client.js' +import { captureWork, parseCaptureArgs } from './capture-work.js' + +describe('parseCaptureArgs', () => { + it('validates issues and keeps only real titles + valid labels', () => { + const p = parseCaptureArgs({ + issues: [ + { title: 'Fix token refresh', body: 'dies silently', estimate: 'est/2d', priority: 'p/1' }, + { title: ' ', body: 'blank title dropped' }, + { title: 'Docs', estimate: 'est/9d', priority: 'urgent' }, // invalid labels → dropped to undefined + ], + consequence: 'Beta slips a day', + }) + expect(p.issues).toHaveLength(2) + expect(p.issues[0]).toEqual({ title: 'Fix token refresh', body: 'dies silently', estimate: 'est/2d', priority: 'p/1' }) + expect(p.issues[1]).toEqual({ title: 'Docs', body: '', estimate: undefined, priority: undefined }) + expect(p.consequence).toBe('Beta slips a day') + }) + + it('tolerates a missing/!array issues field', () => { + expect(parseCaptureArgs({}).issues).toEqual([]) + expect(parseCaptureArgs({ issues: 'nope' }).issues).toEqual([]) + }) +}) + +describe('captureWork', () => { + it('forces propose_issues and returns the validated set', async () => { + const result: CompletionResult = { + content: '', + toolCalls: [ + { + id: 'c1', + name: 'propose_issues', + arguments: JSON.stringify({ + issues: [{ title: 'Retry token refresh with backoff', body: '', estimate: 'est/2d', priority: 'p/2' }], + consequence: 'no material shift', + }), + }, + ], + } + let sawTool = '' + const proposal = await captureWork(async (_m, tools) => { + sawTool = tools?.[0]?.name ?? '' + return result + }, 'auth is flaky, token refresh dies') + expect(sawTool).toBe('propose_issues') + expect(proposal.issues[0].title).toBe('Retry token refresh with backoff') + expect(proposal.consequence).toBe('no material shift') + }) + + it('returns an empty set when the model answers without the tool', async () => { + const proposal = await captureWork(async () => ({ content: 'I need more detail.', toolCalls: [] }), 'vague') + expect(proposal.issues).toEqual([]) + }) + + it('survives malformed tool arguments', async () => { + const proposal = await captureWork( + async () => ({ content: '', toolCalls: [{ id: 'c1', name: 'propose_issues', arguments: '{not json' }] }), + 'x', + ) + expect(proposal.issues).toEqual([]) + }) +}) diff --git a/packages/core/src/agent/capture-work.ts b/packages/core/src/agent/capture-work.ts new file mode 100644 index 0000000..f09ec3c --- /dev/null +++ b/packages/core/src/agent/capture-work.ts @@ -0,0 +1,109 @@ +/** + * capture_work — braindump → a small set of concrete issues. This is the one + * place the big model earns its keep (decomposition + estimate negotiation). + * It returns a *proposal*; nothing is filed until the human approves it in the + * Capture tray and it goes through the create-issue write path. Pure + * orchestration over an injected `complete` — stubbable, so it's testable offline. + */ + +import { + type EstimateLabel, + ESTIMATE_LABELS, + type PriorityLabel, + PRIORITY_LABELS, +} from '../labels/label-schema.js' +import type { ChatMessage, CompletionResult, ToolDecl } from './chat-client.js' + +export interface ProposedIssue { + title: string + body: string + estimate?: EstimateLabel + priority?: PriorityLabel +} + +export interface CaptureProposal { + issues: ProposedIssue[] + /** One-line schedule impact, if the model offered one. */ + consequence?: string +} + +export const PROPOSE_ISSUES_TOOL: ToolDecl = { + name: 'propose_issues', + description: 'Return the decomposed issue set for a braindump. Call this exactly once.', + parameters: { + type: 'object', + properties: { + issues: { + type: 'array', + items: { + type: 'object', + properties: { + title: { type: 'string', description: 'a clear imperative title' }, + body: { type: 'string', description: 'one or two lines of detail' }, + estimate: { type: 'string', enum: ['est/1d', 'est/2d', 'est/3d', 'est/5d', 'est/8d'] }, + priority: { type: 'string', enum: ['p/1', 'p/2', 'p/3', 'p/4'] }, + }, + required: ['title'], + }, + }, + consequence: { type: 'string', description: 'one-line note on the schedule impact' }, + }, + required: ['issues'], + }, +} + +export const CAPTURE_SYSTEM = [ + 'You are Reginald, decomposing a rough braindump into a small set of concrete Gitea issues.', + 'Call propose_issues exactly once. Split genuinely separate work; merge trivially-coupled work; invent no scope.', + 'Each issue gets an imperative title, a one-line body, an estimate (est/1d…8d) and a priority (p/1…4).', + 'Estimate honestly — a "quick" task is rarely one day. Keep the set tight; three good issues beat eight vague ones.', +].join(' ') + +function isEstimate(v: unknown): v is EstimateLabel { + return typeof v === 'string' && (ESTIMATE_LABELS as readonly string[]).includes(v) +} +function isPriority(v: unknown): v is PriorityLabel { + return typeof v === 'string' && (PRIORITY_LABELS as readonly string[]).includes(v) +} + +/** Coerce the model's raw propose_issues args into a validated proposal. */ +export function parseCaptureArgs(args: unknown): CaptureProposal { + const a = (args ?? {}) as { issues?: unknown[]; consequence?: unknown } + const issues: ProposedIssue[] = [] + for (const raw of Array.isArray(a.issues) ? a.issues : []) { + const r = (raw ?? {}) as Record + const title = typeof r.title === 'string' ? r.title.trim() : '' + if (!title) continue + issues.push({ + title, + body: typeof r.body === 'string' ? r.body : '', + estimate: isEstimate(r.estimate) ? r.estimate : undefined, + priority: isPriority(r.priority) ? r.priority : undefined, + }) + } + return { issues, consequence: typeof a.consequence === 'string' ? a.consequence : undefined } +} + +/** + * Run one decomposition turn. Forces the model to answer via propose_issues and + * returns the validated set. An empty set means the model declined to structure it. + */ +export async function captureWork( + complete: (messages: ChatMessage[], tools?: ToolDecl[]) => Promise, + braindump: string, +): Promise { + const res = await complete( + [ + { role: 'system', content: CAPTURE_SYSTEM }, + { role: 'user', content: braindump }, + ], + [PROPOSE_ISSUES_TOOL], + ) + const call = res.toolCalls.find((t) => t.name === 'propose_issues') + if (!call) return { issues: [] } + try { + return parseCaptureArgs(JSON.parse(call.arguments || '{}')) + } catch { + return { issues: [] } + } +} diff --git a/packages/core/src/gitea/client.test.ts b/packages/core/src/gitea/client.test.ts index 79990b3..d525b8e 100644 --- a/packages/core/src/gitea/client.test.ts +++ b/packages/core/src/gitea/client.test.ts @@ -146,6 +146,18 @@ describe('createGiteaClient.getIssue', () => { ]) }) + it('createIssue POSTs title/body/labels and returns a normalized issue', async () => { + const created = { ...RAW_ISSUE, number: 44, title: 'Retry token refresh', labels: [{ name: 'est/2d' }, { name: 'p/2' }] } + const { fetch, calls } = stubFetch(created, 201) + const issue = await createGiteaClient(CONFIG, fetch).createIssue({ title: 'Retry token refresh', body: 'backoff', labelIds: [3, 7] }) + + expect(calls[0].url).toBe('https://gitea.stephenmann.io/api/v1/repos/christian/commitea/issues') + expect(calls[0].init?.method).toBe('POST') + expect(JSON.parse(calls[0].init?.body ?? '{}')).toEqual({ title: 'Retry token refresh', body: 'backoff', labels: [3, 7] }) + expect(issue.number).toBe(44) + expect(issue.labels).toEqual(['est/2d', 'p/2']) + }) + it('throws GiteaApiError carrying status + body on a non-2xx response', async () => { const { fetch } = stubFetch('not found', 404) const client = createGiteaClient(CONFIG, fetch) diff --git a/packages/core/src/gitea/client.ts b/packages/core/src/gitea/client.ts index d1fa359..5fff8ba 100644 --- a/packages/core/src/gitea/client.ts +++ b/packages/core/src/gitea/client.ts @@ -103,6 +103,8 @@ export interface GiteaClient { listLabels(): Promise /** Replace an issue's entire label set with the given label ids. Write. */ setIssueLabels(index: number, labelIds: number[]): Promise + /** Open a new issue with a title, optional body, and label ids. Write. */ + createIssue(input: { title: string; body?: string; labelIds?: number[] }): Promise } /** Map raw gitea issue JSON to the normalized domain shape. Pure. */ @@ -222,5 +224,13 @@ export function createGiteaClient(config: GiteaConfig, fetchImpl: FetchLike): Gi async setIssueLabels(index, labelIds) { await request(`/issues/${index}/labels`, { method: 'PUT', body: { labels: labelIds } }) }, + + async createIssue(input) { + const raw = (await request('/issues', { + method: 'POST', + body: { title: input.title, body: input.body ?? '', labels: input.labelIds ?? [] }, + })) as RawIssue + return normalizeIssue(raw) + }, } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 9881069..6216dec 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -88,3 +88,5 @@ export type { AgentStep, AgentTurn, ToolExecutor } from './agent/agent-loop.js' export { PROPOSE_CHANGE_TOOL, QUERY_PROJECT_TOOL, REGINALD_SYSTEM, REGINALD_TOOLS } from './agent/agent-tools.js' export { buildProjectView } from './agent/query-project.js' export type { ProjectSnapshot, ProjectView, QueryFilters } from './agent/query-project.js' +export { CAPTURE_SYSTEM, captureWork, parseCaptureArgs, PROPOSE_ISSUES_TOOL } from './agent/capture-work.js' +export type { CaptureProposal, ProposedIssue } from './agent/capture-work.js'