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..eaf5670 100644 --- a/apps/desktop/src/main/gitea.ts +++ b/apps/desktop/src/main/gitea.ts @@ -6,18 +6,24 @@ * properly later. */ +import { randomUUID } from 'node:crypto' import { readFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { + appendDirective, createGiteaClient, + type DirectiveEntry, type GiteaClient, type GiteaConfig, type GiteaLabel, type IssueChange, type LifecycleEvent, + makeDirectiveEntry, + parseDirectiveLog, planIssueChange, type ProjectSnapshot, + type DirectiveInput, } from '@commitea/core' import { ipcMain } from 'electron' @@ -62,6 +68,45 @@ export function getGiteaClient(): GiteaClient | null { return sharedClient } +// The pm-state repo holds machine-derived state (the directive ledger). Same +// token/host as the work repo, a different repo (the purity split, decisions D4). +let pmStateClient: GiteaClient | null | undefined +export function getPmStateClient(): GiteaClient | null { + if (pmStateClient === undefined) { + const config = resolveConfig() + pmStateClient = config + ? createGiteaClient({ ...config, repo: process.env.COMMITEA_PMSTATE_REPO ?? 'commitea-pm-state' }, fetch) + : null + } + return pmStateClient +} + +const DIRECTIVE_LOG_PATH = 'directives/log.jsonl' + +async function readDirectiveLog(client: GiteaClient): Promise<{ text: string; sha: string | null }> { + const file = await client.getFile(DIRECTIVE_LOG_PATH) + if (!file) return { text: '', sha: null } + return { text: Buffer.from(file.contentBase64, 'base64').toString('utf8'), sha: file.sha } +} + +/** Record a directive: read the ledger, append, write it back (concatenation merge). */ +export async function appendDirectiveEntry(client: GiteaClient, input: DirectiveInput): Promise { + const entry = makeDirectiveEntry(input, randomUUID(), new Date().toISOString()) + const { text, sha } = await readDirectiveLog(client) + const next = appendDirective(text, entry) + await client.putFile(DIRECTIVE_LOG_PATH, { + contentBase64: Buffer.from(next, 'utf8').toString('base64'), + message: `directive: ${entry.kind}`, + sha: sha ?? undefined, + }) + return entry +} + +export async function readDirectives(client: GiteaClient) { + const { text } = await readDirectiveLog(client) + return parseDirectiveLog(text) +} + /** Full reconcile: issues + milestones + native deps + lifecycle timelines. */ export async function reconcileSnapshot( client: GiteaClient, @@ -124,4 +169,32 @@ 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 } + }, + ) + + // Read the directive ledger from the pm-state repo (for the Directives screen). + ipcMain.handle('pmstate:directives', async () => { + const pm = getPmStateClient() + if (!pm) return { ok: false as const, reason: 'unconfigured' as const } + try { + return { ok: true as const, directives: await readDirectives(pm) } + } 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/main/model.ts b/apps/desktop/src/main/model.ts index 0c2016f..686a8a3 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, @@ -21,10 +22,11 @@ import { REGINALD_SYSTEM, REGINALD_TOOLS, runAgentTurn, + toDirectiveInput, } from '@commitea/core' import { ipcMain } from 'electron' -import { getGiteaClient, reconcileSnapshot } from './gitea.js' +import { appendDirectiveEntry, getGiteaClient, getPmStateClient, reconcileSnapshot } from './gitea.js' /** Small local model for prose + the read tool; big model reserved for later decomposition. */ function resolveModelRouter(): ModelRouter | null { @@ -105,6 +107,16 @@ export function registerModelIpc(): void { ? { proposed: built.map((p) => ({ issue: a.issue, diff: describeChange(p.plan) })) } : { proposed: [], note: 'no change — already at that value' } } + if (name === 'record_directive') { + const pm = getPmStateClient() + if (!pm) return { error: 'pm-state is not configured' } + try { + const entry = await appendDirectiveEntry(pm, toDirectiveInput(args)) + return { recorded: { kind: entry.kind, quote: entry.quote } } + } catch (e) { + return { error: `could not record — is the pm-state repo created? (${e instanceof Error ? e.message : e})` } + } + } return { error: `unknown tool: ${name}` } } @@ -120,4 +132,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..6dee376 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -11,12 +11,20 @@ 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), + }, + pmstate: { + /** Read the directive ledger from the pm-state repo. */ + directives: () => ipcRenderer.invoke('pmstate:directives'), }, 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/components/screens/directives-screen.tsx b/apps/desktop/src/renderer/src/components/screens/directives-screen.tsx index 13b5cc4..7446d4b 100644 --- a/apps/desktop/src/renderer/src/components/screens/directives-screen.tsx +++ b/apps/desktop/src/renderer/src/components/screens/directives-screen.tsx @@ -8,6 +8,35 @@ export function DirectivesScreen() { const [pending, setPending] = React.useState(DIRECTIVES.pending) const [entries, setEntries] = React.useState(DIRECTIVES.entries) + // Real ledger from the pm-state repo, when it exists — else the fixture demo. + React.useEffect(() => { + let alive = true + window.commitea.pmstate + .directives() + .then((r) => { + if (!alive || !r.ok || r.directives.length === 0) return + setPending(null) + setEntries( + r.directives + .slice() + .reverse() + .map((d) => ({ + seq: d.seq, + who: 'You', + when: new Date(d.ts).toLocaleDateString(), + what: d.quote, + why: d.rationale ?? '', + status: d.status === 'accepted' ? 'applied' : d.status === 'withdrawn' ? 'withdrawn' : 'superseded', + consequence: '', + })), + ) + }) + .catch(() => {}) + return () => { + alive = false + } + }, []) + const resolve = (status: string) => { setEntries((e) => [{ seq: pending!.seq, who: pending!.who, when: pending!.when, what: pending!.what, why: 'pilot demo on the 14th', diff --git a/apps/desktop/src/renderer/src/global.d.ts b/apps/desktop/src/renderer/src/global.d.ts index 835eb4e..151675c 100644 --- a/apps/desktop/src/renderer/src/global.d.ts +++ b/apps/desktop/src/renderer/src/global.d.ts @@ -2,12 +2,15 @@ import type { AgentStep, ChangeProposal, ChatMessage, + CaptureProposal, DependencyEdge, + DirectiveRecord, GiteaIssue, GiteaMilestone, IssueChange, LabelPlan, LifecycleEvent, + ProposedIssue, } from '@commitea/core' /** The result of a write through the bridge. */ @@ -15,6 +18,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 +41,7 @@ export interface GiteaBridge { }> getIssue(index: number): Promise applyChange(change: IssueChange): Promise + createIssues(issues: ProposedIssue[]): Promise } /** One agent turn's result. */ @@ -39,6 +53,17 @@ export type ChatResult = export interface ModelBridge { status(): Promise<{ configured: boolean; model: string | null }> chat(messages: ChatMessage[]): Promise + capture(braindump: string): Promise +} + +/** The result of reading the directive ledger. */ +export type DirectivesResult = + | { ok: false; reason: 'unconfigured' | 'error'; message?: string } + | { ok: true; directives: DirectiveRecord[] } + +/** The pm-state bridge (machine-derived state) exposed by the preload over IPC. */ +export interface PmStateBridge { + directives(): Promise } declare global { @@ -47,6 +72,7 @@ declare global { platform: string gitea: GiteaBridge model: ModelBridge + pmstate: PmStateBridge } } } diff --git a/packages/core/src/agent/agent-live.test.ts b/packages/core/src/agent/agent-live.test.ts index bf61bae..0dcddf2 100644 --- a/packages/core/src/agent/agent-live.test.ts +++ b/packages/core/src/agent/agent-live.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { beforeAll, describe, expect, it } from 'vitest' import { extractLabelFacts } from '../labels/label-schema.js' import type { FetchLike, GiteaIssue } from '../gitea/types.js' @@ -10,11 +10,22 @@ import { buildProjectView, type ProjectSnapshot } from './query-project.js' /** * Opt-in (COMMITEA_MODEL_LIVE=1). Drives the real chat client + agent loop * against a local OpenAI-compatible server (LM Studio on :1234 by default), - * proving the model calls query_project and narrates the real result. + * proving the model calls the tools and narrates the real result. The model is + * whatever is loaded (via LM Studio's native API), so it never JIT-swaps. */ const LIVE = !!process.env.COMMITEA_MODEL_LIVE const BASE = process.env.COMMITEA_MODEL_URL ?? 'http://localhost:1234/v1' -const MODEL = process.env.COMMITEA_MODEL_SMALL ?? 'google/gemma-4-e4b' +let MODEL = process.env.COMMITEA_MODEL_SMALL ?? '' + +beforeAll(async () => { + if (!LIVE || MODEL) return + const root = BASE.replace(/\/v1\/?$/, '') + const loaded = await fetch(`${root}/api/v0/models`) + .then((r) => (r.ok ? (r.json() as Promise<{ data?: { id: string; state?: string; type?: string }[] }>) : null)) + .then((d) => d?.data?.find((m) => m.state === 'loaded' && m.type !== 'embeddings')?.id) + .catch(() => undefined) + MODEL = loaded ?? 'google/gemma-4-e4b' +}) function issue(over: Partial): GiteaIssue { const labels = over.labels ?? [] @@ -59,4 +70,34 @@ describe('agent loop (live model)', () => { }, 60_000, ) + + it.skipIf(!LIVE)( + 'records a standing instruction via record_directive', + async () => { + const client = createChatClient({ baseUrl: BASE, model: MODEL }, globalThis.fetch as unknown as FetchLike) + const recorded: unknown[] = [] + const turn = await runAgentTurn({ + complete: (m, t) => client.complete(m, t), + messages: [ + { role: 'system', content: REGINALD_SYSTEM }, + { role: 'user', content: 'Log this standing directive: pilots come first, everything else waits.' }, + ], + tools: REGINALD_TOOLS, + execute: async (name, args) => { + if (name === 'record_directive') { + recorded.push(args) + return { recorded: { kind: (args as { kind?: string }).kind ?? 'note' } } + } + return name === 'query_project' + ? buildProjectView((args as { view: any }).view, (args as any).filters, SNAP, new Date()) + : { error: `unknown tool ${name}` } + }, + }) + + // the model logged the directive rather than trying to apply it + expect(turn.steps.some((s) => s.tool === 'record_directive')).toBe(true) + expect(recorded.length).toBeGreaterThan(0) + }, + 60_000, + ) }) diff --git a/packages/core/src/agent/agent-tools.ts b/packages/core/src/agent/agent-tools.ts index 2acff52..f6fd4c7 100644 --- a/packages/core/src/agent/agent-tools.ts +++ b/packages/core/src/agent/agent-tools.ts @@ -52,13 +52,40 @@ export const PROPOSE_CHANGE_TOOL: ToolDecl = { }, } -export const REGINALD_TOOLS: ToolDecl[] = [QUERY_PROJECT_TOOL, PROPOSE_CHANGE_TOOL] +export const RECORD_DIRECTIVE_TOOL: ToolDecl = { + name: 'record_directive', + description: + 'Log a standing instruction from the PM to the durable directive ledger — a reprioritization, ' + + 'a re-estimate policy, a deadline, a scope or capacity call, or a plain note. Use it when the user ' + + 'states intent that should persist ("pilots come first", "freeze scope for beta"). This records the ' + + 'intent verbatim; the actual issue edits still go through propose_change.', + parameters: { + type: 'object', + properties: { + kind: { type: 'string', enum: ['reprioritize', 'reestimate', 'set-deadline', 'scope', 'capacity', 'note'] }, + quote: { type: 'string', description: "the PM's own words, stored verbatim" }, + target: { + type: 'object', + properties: { + issue: { type: 'number' }, + milestone: { type: 'number' }, + member: { type: 'string' }, + }, + }, + rationale: { type: 'string', description: 'why (optional)' }, + }, + required: ['kind', 'quote'], + }, +} + +export const REGINALD_TOOLS: ToolDecl[] = [QUERY_PROJECT_TOOL, PROPOSE_CHANGE_TOOL, RECORD_DIRECTIVE_TOOL] export const REGINALD_SYSTEM = [ 'You are Reginald, the calm, dry project manager inside CommiTea — a tool that runs projects on Gitea.', 'Call query_project to ground every answer in the real project; never invent issues, numbers, or dates.', 'The scheduler and forecasts are deterministic code — report their output, do not recompute it.', 'To change an estimate or priority, call propose_change — it shows the human a diff to approve.', + 'When the PM states standing intent ("pilots first", "freeze scope"), call record_directive to log it.', 'Never claim a change is applied; you propose, the human approves. Forecasts are ranges, never single dates.', 'Refer to issues as #. Be brief and plain — a sentence or two. No preamble, no bullet dumps.', ].join(' ') 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/directives/record-directive-v0.test.ts b/packages/core/src/directives/record-directive-v0.test.ts new file mode 100644 index 0000000..11570b3 --- /dev/null +++ b/packages/core/src/directives/record-directive-v0.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' + +import { + appendDirective, + makeDirectiveEntry, + parseDirectiveLog, + serializeDirective, + toDirectiveInput, +} from './record-directive-v0.js' + +describe('toDirectiveInput', () => { + it('keeps a valid kind + target and drops an empty target', () => { + const input = toDirectiveInput({ kind: 'reprioritize', quote: 'pilots first', target: { issue: 87 }, rationale: 'blocked' }) + expect(input).toEqual({ kind: 'reprioritize', quote: 'pilots first', target: { issue: 87 }, params: undefined, rationale: 'blocked' }) + expect(toDirectiveInput({ kind: 'note', quote: 'x', target: {} }).target).toBeUndefined() + }) + + it('falls back to note for an unknown kind', () => { + expect(toDirectiveInput({ kind: 'nonsense', quote: 'hmm' }).kind).toBe('note') + }) +}) + +describe('serialize + parse round-trip', () => { + const entry = makeDirectiveEntry( + { kind: 'reprioritize', quote: 'pilots come first', target: { issue: 87 } }, + 'id-1', + '2026-02-01T09:00:00Z', + ) + + it('serializes to one JSON line', () => { + const line = serializeDirective(entry) + expect(line).not.toContain('\n') + expect(JSON.parse(line)).toMatchObject({ id: 'id-1', kind: 'reprioritize', status: 'accepted' }) + }) + + it('parses a log, orders by ts, and assigns a 1-based seq', () => { + const a = serializeDirective(makeDirectiveEntry({ kind: 'note', quote: 'later' }, 'b', '2026-02-02T00:00:00Z')) + const b = serializeDirective(makeDirectiveEntry({ kind: 'note', quote: 'earlier' }, 'a', '2026-02-01T00:00:00Z')) + const records = parseDirectiveLog(`${a}\n${b}\n`) + expect(records.map((r) => r.quote)).toEqual(['earlier', 'later']) + expect(records.map((r) => r.seq)).toEqual([1, 2]) + }) + + it('skips blank and corrupt lines without losing the rest', () => { + const good = serializeDirective(entry) + const records = parseDirectiveLog(`\n{not json\n${good}\n\n`) + expect(records).toHaveLength(1) + expect(records[0].id).toBe('id-1') + }) +}) + +describe('appendDirective', () => { + it('concatenates a newline-terminated entry, normalizing a missing trailing newline', () => { + const e1 = makeDirectiveEntry({ kind: 'note', quote: 'one' }, 'i1', '2026-01-01T00:00:00Z') + const e2 = makeDirectiveEntry({ kind: 'note', quote: 'two' }, 'i2', '2026-01-02T00:00:00Z') + let log = appendDirective('', e1) + log = appendDirective(log, e2) + expect(parseDirectiveLog(log).map((r) => r.quote)).toEqual(['one', 'two']) + expect(log.endsWith('\n')).toBe(true) + }) + + it('handles existing text without a trailing newline', () => { + const e = makeDirectiveEntry({ kind: 'note', quote: 'x' }, 'i', '2026-01-01T00:00:00Z') + expect(appendDirective('{"id":"prev","ts":"2025-01-01T00:00:00Z"}', e).split('\n').filter(Boolean)).toHaveLength(2) + }) +}) diff --git a/packages/core/src/directives/record-directive-v0.ts b/packages/core/src/directives/record-directive-v0.ts new file mode 100644 index 0000000..6579b4d --- /dev/null +++ b/packages/core/src/directives/record-directive-v0.ts @@ -0,0 +1,106 @@ +/** + * record_directive — the PM's standing instructions ("pilots come first"), + * appended to an append-only JSONL ledger in the pm-state repo (decisions.md D4, + * pm-state.md). A directive is *intent*: it's logged verbatim; its effects land + * later through apply_changes. Merge is concatenation — order derives from `ts` + * at read time, so two writers never conflict. `seq` is a display ordinal + * computed on read, never stored. This module is pure serialize/parse; the + * append (read → concat → write) is the bridge's job. + */ + +export type DirectiveKind = 'reprioritize' | 'reestimate' | 'set-deadline' | 'scope' | 'capacity' | 'note' + +export type DirectiveStatus = 'proposed' | 'accepted' | 'amended' | 'withdrawn' + +export interface DirectiveTarget { + issue?: number + milestone?: number + member?: string +} + +/** What the record_directive tool captures. */ +export interface DirectiveInput { + kind: DirectiveKind + /** Verbatim PM words, shown in the ledger. */ + quote: string + target?: DirectiveTarget + /** Structured effect the scheduler applies, e.g. { priority: 1 }. */ + params?: Record + rationale?: string +} + +/** A ledger entry — an input plus its durable id/ts/status. */ +export interface DirectiveEntry extends DirectiveInput { + id: string + ts: string + status: DirectiveStatus +} + +/** A ledger entry as read back, with a computed display ordinal. */ +export interface DirectiveRecord extends DirectiveEntry { + seq: number +} + +const DIRECTIVE_KINDS: readonly DirectiveKind[] = [ + 'reprioritize', + 'reestimate', + 'set-deadline', + 'scope', + 'capacity', + 'note', +] + +/** Normalize a raw tool payload into a DirectiveInput (unknown kind → note). */ +export function toDirectiveInput(raw: unknown): DirectiveInput { + const r = (raw ?? {}) as Record + const kind = DIRECTIVE_KINDS.includes(r.kind as DirectiveKind) ? (r.kind as DirectiveKind) : 'note' + const target = (r.target ?? undefined) as DirectiveTarget | undefined + return { + kind, + quote: typeof r.quote === 'string' ? r.quote : '', + target: target && (target.issue || target.milestone || target.member) ? target : undefined, + params: (r.params && typeof r.params === 'object' ? (r.params as Record) : undefined), + rationale: typeof r.rationale === 'string' ? r.rationale : undefined, + } +} + +/** Build a full entry from an input + externally-supplied id/ts (Date/uuid live in the caller). */ +export function makeDirectiveEntry( + input: DirectiveInput, + id: string, + ts: string, + status: DirectiveStatus = 'accepted', +): DirectiveEntry { + return { ...input, id, ts, status } +} + +/** One JSONL line (no trailing newline — the caller joins). */ +export function serializeDirective(entry: DirectiveEntry): string { + return JSON.stringify(entry) +} + +/** + * Parse a JSONL log into records ordered by `ts` (then id for stability), with a + * 1-based `seq` assigned on read. Blank/corrupt lines are skipped, not fatal. + */ +export function parseDirectiveLog(text: string): DirectiveRecord[] { + const entries: DirectiveEntry[] = [] + for (const line of text.split('\n')) { + const trimmed = line.trim() + if (!trimmed) continue + try { + const e = JSON.parse(trimmed) as DirectiveEntry + if (e && typeof e.id === 'string' && typeof e.ts === 'string') entries.push(e) + } catch { + // skip a corrupt line rather than lose the whole ledger + } + } + entries.sort((a, b) => (a.ts === b.ts ? a.id.localeCompare(b.id) : a.ts.localeCompare(b.ts))) + return entries.map((e, i) => ({ ...e, seq: i + 1 })) +} + +/** Append a serialized entry to existing log text (concatenation merge). */ +export function appendDirective(existing: string, entry: DirectiveEntry): string { + const base = existing.endsWith('\n') || existing === '' ? existing : existing + '\n' + return `${base}${serializeDirective(entry)}\n` +} diff --git a/packages/core/src/gitea/client.test.ts b/packages/core/src/gitea/client.test.ts index 79990b3..935372a 100644 --- a/packages/core/src/gitea/client.test.ts +++ b/packages/core/src/gitea/client.test.ts @@ -146,6 +146,40 @@ describe('createGiteaClient.getIssue', () => { ]) }) + it('getFile returns null on 404 and content+sha on hit', async () => { + const miss = stubFetch('nope', 404) + expect(await createGiteaClient(CONFIG, miss.fetch).getFile('directives/log.jsonl')).toBeNull() + + const hit = stubFetch({ content: 'aGVsbG8=\n', sha: 'abc123' }) + const file = await createGiteaClient(CONFIG, hit.fetch).getFile('directives/log.jsonl') + expect(file).toEqual({ contentBase64: 'aGVsbG8=', sha: 'abc123' }) + expect(hit.calls[0].url).toContain('/contents/directives/log.jsonl') + }) + + it('putFile POSTs to create and PUTs to update (with sha)', async () => { + const create = stubFetch({}, 201) + await createGiteaClient(CONFIG, create.fetch).putFile('directives/log.jsonl', { contentBase64: 'eA==', message: 'seed' }) + expect(create.calls[0].init?.method).toBe('POST') + expect(JSON.parse(create.calls[0].init?.body ?? '{}')).toEqual({ content: 'eA==', message: 'seed' }) + + const update = stubFetch({}, 200) + await createGiteaClient(CONFIG, update.fetch).putFile('directives/log.jsonl', { contentBase64: 'eQ==', message: 'append', sha: 's1' }) + expect(update.calls[0].init?.method).toBe('PUT') + expect(JSON.parse(update.calls[0].init?.body ?? '{}')).toEqual({ content: 'eQ==', message: 'append', sha: 's1' }) + }) + + 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..52aaeba 100644 --- a/packages/core/src/gitea/client.ts +++ b/packages/core/src/gitea/client.ts @@ -103,6 +103,12 @@ 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 + /** Read a repo file's base64 content + blob sha; null if it (or the repo) is absent. */ + getFile(path: string): Promise<{ contentBase64: string; sha: string } | null> + /** Create or update a repo file with base64 content (pass `sha` to update). Write. */ + putFile(path: string, input: { contentBase64: string; message: string; sha?: string }): Promise } /** Map raw gitea issue JSON to the normalized domain shape. Pure. */ @@ -222,5 +228,33 @@ 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) + }, + + async getFile(path) { + const res = await fetchImpl(`${repoBase}/contents/${path}`, { + headers: { Authorization: `token ${config.token}`, Accept: 'application/json' }, + }) + if (res.status === 404) return null + if (!res.ok) { + const body = await res.text().catch(() => '') + throw new GiteaApiError(res.status, `GET contents/${path} failed (${res.status})`, body) + } + const json = (await res.json()) as { content?: string; sha: string } + return { contentBase64: (json.content ?? '').replace(/\n/g, ''), sha: json.sha } + }, + + async putFile(path, input) { + await request(`/contents/${path}`, { + method: input.sha ? 'PUT' : 'POST', + body: { content: input.contentBase64, message: input.message, ...(input.sha ? { sha: input.sha } : {}) }, + }) + }, } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 9881069..d190e3a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -85,6 +85,30 @@ export { pickModel } from './agent/model-router.js' export type { ModelRouter, TaskKind } from './agent/model-router.js' export { runAgentTurn } from './agent/agent-loop.js' 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 { + PROPOSE_CHANGE_TOOL, + QUERY_PROJECT_TOOL, + RECORD_DIRECTIVE_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' + +export { + appendDirective, + makeDirectiveEntry, + parseDirectiveLog, + serializeDirective, + toDirectiveInput, +} from './directives/record-directive-v0.js' +export type { + DirectiveEntry, + DirectiveInput, + DirectiveKind, + DirectiveRecord, + DirectiveStatus, + DirectiveTarget, +} from './directives/record-directive-v0.js'