Compare commits
1 Commits
6e8a6a15bc
...
5ae191be49
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ae191be49 |
37
apps/desktop/e2e/live-capture.spec.ts
Normal file
37
apps/desktop/e2e/live-capture.spec.ts
Normal file
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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 }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string | null>(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<ProposedIssue[] | null>(null)
|
||||
const [filedCount, setFiledCount] = React.useState(0)
|
||||
const [error, setError] = React.useState<string | null>(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 }) {
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
|
||||
{editable ? (
|
||||
<>
|
||||
<Select options={estOptions} defaultValue={t.est} style={{ width: 96 }} />
|
||||
<Select options={pOptions} defaultValue={t.p} style={{ width: 76 }} />
|
||||
<Select
|
||||
options={estOptions}
|
||||
value={liveTickets ? t.est : undefined}
|
||||
defaultValue={liveTickets ? undefined : t.est}
|
||||
onChange={(e) => editTicket(i, 'estimate', e.target.value)}
|
||||
style={{ width: 96 }}
|
||||
/>
|
||||
<Select
|
||||
options={pOptions}
|
||||
value={liveTickets ? t.p : undefined}
|
||||
defaultValue={liveTickets ? undefined : t.p}
|
||||
onChange={(e) => editTicket(i, 'priority', e.target.value)}
|
||||
style={{ width: 76 }}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -144,7 +222,12 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) {
|
||||
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 14px' }}>
|
||||
Sentences, fragments, grievances — all welcome. I'll sort it into tickets and only ask what I can't infer.
|
||||
</p>
|
||||
<Button icon="sparkles" onClick={() => setStage('interview')}>Brew tickets</Button>
|
||||
<Button icon="sparkles" onClick={() => void onBrew()} disabled={brewing}>
|
||||
{brewing ? 'Brewing…' : 'Brew tickets'}
|
||||
</Button>
|
||||
{error ? (
|
||||
<p style={{ font: 'var(--text-agent)', color: 'var(--danger)', margin: '10px 0 0' }}>{error}</p>
|
||||
) : null}
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
@@ -174,15 +257,26 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) {
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 14, alignItems: 'start' }}>
|
||||
<Card overline="Consequence" title={`${tickets.length} tickets · ~${totalDays}d of work`} jade
|
||||
footer={<>
|
||||
<Button onClick={() => setStage('filed')}>Approve all</Button>
|
||||
<Button variant="ghost" onClick={() => { setStage('dump'); setQi(0); setLog([]); setSplit(null); setWebEst(null); setSecs(0); }}>Discard</Button>
|
||||
<Button onClick={() => (live ? fileLive() : setStage('filed'))} disabled={brewing}>
|
||||
{brewing ? 'Filing…' : 'Approve all'}
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => { setStage('dump'); setQi(0); setLog([]); setSplit(null); setWebEst(null); setSecs(0); setLiveTickets(null); setError(null); }}>Discard</Button>
|
||||
</>}>
|
||||
<p style={{ font: 'var(--text-body)', margin: '0 0 8px' }}>
|
||||
Beta's 80% window moves <span style={{ font: 'var(--text-data)' }}>Mar 3–12 → Mar 5–14</span>. Capacity absorbs the rest.
|
||||
</p>
|
||||
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
|
||||
I added the docs ticket you mentioned and wired the dependency. Shall I make it so?
|
||||
</p>
|
||||
{live ? (
|
||||
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
|
||||
{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.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p style={{ font: 'var(--text-body)', margin: '0 0 8px' }}>
|
||||
Beta's 80% window moves <span style={{ font: 'var(--text-data)' }}>Mar 3–12 → Mar 5–14</span>. Capacity absorbs the rest.
|
||||
</p>
|
||||
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
|
||||
I added the docs ticket you mentioned and wired the dependency. Shall I make it so?
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
<Tray editable />
|
||||
</div>
|
||||
@@ -195,7 +289,7 @@ export function CaptureScreen({ onDone }: { onDone: () => void }) {
|
||||
<Icon name="circle-check" size={22} /> Filed
|
||||
</span>
|
||||
<p style={{ font: 'var(--text-body)', margin: 0 }}>
|
||||
{tickets.length} issues opened in gitea with <span style={{ font: 'var(--text-data)' }}>est/*</span> and <span style={{ font: 'var(--text-data)' }}>p/*</span> labels — nothing else touched.
|
||||
{live ? filedCount : tickets.length} issues opened in gitea with <span style={{ font: 'var(--text-data)' }}>est/*</span> and <span style={{ font: 'var(--text-data)' }}>p/*</span> labels — nothing else touched.
|
||||
</p>
|
||||
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
|
||||
Elapsed {clock} — under budget. No bot comments, no synthetic issues; your repo remains yours.
|
||||
|
||||
14
apps/desktop/src/renderer/src/global.d.ts
vendored
14
apps/desktop/src/renderer/src/global.d.ts
vendored
@@ -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<GiteaIssue | null>
|
||||
applyChange(change: IssueChange): Promise<ApplyChangeResult>
|
||||
createIssues(issues: ProposedIssue[]): Promise<CreateIssuesResult>
|
||||
}
|
||||
|
||||
/** 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<ChatResult>
|
||||
capture(braindump: string): Promise<CaptureResult>
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
65
packages/core/src/agent/capture-work.test.ts
Normal file
65
packages/core/src/agent/capture-work.test.ts
Normal file
@@ -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([])
|
||||
})
|
||||
})
|
||||
109
packages/core/src/agent/capture-work.ts
Normal file
109
packages/core/src/agent/capture-work.ts
Normal file
@@ -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<string, unknown>
|
||||
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<CompletionResult>,
|
||||
braindump: string,
|
||||
): Promise<CaptureProposal> {
|
||||
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: [] }
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -103,6 +103,8 @@ export interface GiteaClient {
|
||||
listLabels(): Promise<GiteaLabel[]>
|
||||
/** Replace an issue's entire label set with the given label ids. Write. */
|
||||
setIssueLabels(index: number, labelIds: number[]): Promise<void>
|
||||
/** Open a new issue with a title, optional body, and label ids. Write. */
|
||||
createIssue(input: { title: string; body?: string; labelIds?: number[] }): Promise<GiteaIssue>
|
||||
}
|
||||
|
||||
/** 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)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
|
||||
Reference in New Issue
Block a user