Compare commits
17 Commits
5ae191be49
...
feat/capac
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6bee1a12aa | ||
|
|
1636d6bada | ||
| d80e1266ee | |||
| cf03827cd5 | |||
| 69106b603d | |||
|
|
dbcdcda5e7 | ||
|
|
57595852a4 | ||
|
|
ae46cb99b3 | ||
| 403aef9d16 | |||
|
|
2f6636684e | ||
|
|
fca36f9075 | ||
| aab7fd6eeb | |||
|
|
469c63fb95 | ||
| 3d8a320a04 | |||
|
|
ba9ea43b4c | ||
|
|
6e8a6a15bc | ||
| 652c8c86b9 |
@@ -41,6 +41,22 @@ test.describe('live backlog', () => {
|
||||
await expect(
|
||||
win.getByText(/cold-start priors · \d+\/20 closed issues estimated|calibrated on \d+ closed/),
|
||||
).toBeVisible()
|
||||
// Real per-milestone forecasts — these milestone names come from gitea, not the
|
||||
// fixture (which lists Beta / Pilot-ready / v1.0). Only milestones with open
|
||||
// scope appear (P2 dropped off once all its work shipped — correct).
|
||||
await expect(win.getByText(/P5 — Dogfood/)).toBeVisible()
|
||||
// Real capacity config from pm-state (christian/stephen), not the fixture (Stephen/Ana K.)
|
||||
await expect(win.getByText('christian', { exact: true })).toBeVisible()
|
||||
await expect(win.getByText(/pd\/day/).first()).toBeVisible()
|
||||
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-runway.png'), fullPage: true, animations: 'disabled' })
|
||||
|
||||
// Milestone drill-in — clicking a real milestone opens its real detail
|
||||
await win.getByText(/P5 — Dogfood/).click()
|
||||
await expect(win.getByRole('heading', { name: 'P5 — Dogfood + polish' })).toBeVisible()
|
||||
await expect(win.getByText(/\d+ issues · est \d+d/)).toBeVisible()
|
||||
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-milestone.png'), fullPage: true, animations: 'disabled' })
|
||||
await rail.getByRole('button', { name: 'Runway' }).click()
|
||||
|
||||
await win.getByRole('button', { name: 'Full report' }).click()
|
||||
await expect(win.getByText(/cold-start · \d+\/20|curve active · n ≥ 20/)).toBeVisible()
|
||||
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-calibration.png'), fullPage: true, animations: 'disabled' })
|
||||
|
||||
32
apps/desktop/e2e/live-directive.spec.ts
Normal file
32
apps/desktop/e2e/live-directive.spec.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
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 + the commitea-pm-state
|
||||
// repo). Reginald records a standing directive; it's appended to the real pm-state
|
||||
// ledger. The append is idempotent-ish (a fresh line each run); this only reads back
|
||||
// that a directive was consulted, and leaves the ledger intact.
|
||||
test.describe('live record_directive', () => {
|
||||
test('logs a standing directive to the pm-state ledger', 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')
|
||||
await expect(win.getByText(/· local$/)).toBeVisible({ timeout: 20000 })
|
||||
|
||||
const composer = win.getByPlaceholder(/Tell me what to do/)
|
||||
await composer.fill('Record a standing directive: freeze scope for beta, pilots come first.')
|
||||
await composer.press('Enter')
|
||||
|
||||
// the agent logged it to the ledger (record_directive), not applied a change
|
||||
await expect(win.getByText(/consulted the directive ledger/)).toBeVisible({ timeout: 240_000 })
|
||||
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-directive.png'), fullPage: true, animations: 'disabled' })
|
||||
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
37
apps/desktop/e2e/live-persistence.spec.ts
Normal file
37
apps/desktop/e2e/live-persistence.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). A real launch persists the snapshot; a second launch with
|
||||
// gitea unreachable must still show the board + real scheduler output from the
|
||||
// persisted cache (offline reads). No model needed.
|
||||
test.describe('live persistence', () => {
|
||||
test('offline: serves the persisted snapshot', async () => {
|
||||
test.skip(!process.env.GITEA_LIVE, 'GITEA_LIVE not set — opt-in live test')
|
||||
test.setTimeout(120_000)
|
||||
|
||||
// launch 1 — real reconcile writes the snapshot to disk
|
||||
const app1 = await electron.launch({ args: [MAIN], env: { ...process.env } })
|
||||
const w1 = await app1.firstWindow()
|
||||
await w1.waitForLoadState('domcontentloaded')
|
||||
// a scheduler-only phrase confirms real data reconciled (never emitted by fixtures)
|
||||
await expect(w1.getByText(/on the critical path|unblocks #|waits on #|· ready/).first()).toBeVisible({ timeout: 30000 })
|
||||
await app1.close()
|
||||
|
||||
// launch 2 — gitea unreachable; the reconcile must fall back to the persisted snapshot
|
||||
const app2 = await electron.launch({
|
||||
args: [MAIN],
|
||||
env: { ...process.env, GITEA_BASE_URL: 'http://127.0.0.1:9' },
|
||||
})
|
||||
const w2 = await app2.firstWindow()
|
||||
await w2.waitForLoadState('domcontentloaded')
|
||||
// Focus still renders real scheduler output — proving it came from the cache, offline
|
||||
await expect(w2.getByText(/on the critical path|unblocks #|waits on #|· ready/).first()).toBeVisible({ timeout: 20000 })
|
||||
await w2.screenshot({ path: join(here, '.artifacts', 'screens', 'live-offline.png'), fullPage: true, animations: 'disabled' })
|
||||
await app2.close()
|
||||
})
|
||||
})
|
||||
@@ -6,21 +6,30 @@
|
||||
* 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,
|
||||
parseCapacityConfig,
|
||||
parseDirectiveLog,
|
||||
planIssueChange,
|
||||
type ProjectSnapshot,
|
||||
type DirectiveInput,
|
||||
} from '@commitea/core'
|
||||
import { ipcMain } from 'electron'
|
||||
|
||||
import { loadSnapshot, saveSnapshot } from './snapshot-store.js'
|
||||
|
||||
/** Walk up from cwd looking for a .env.local with a GITEA_TOKEN (dev convenience). */
|
||||
function loadEnvLocalToken(): string | undefined {
|
||||
let dir = process.cwd()
|
||||
@@ -62,6 +71,58 @@ 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<DirectiveEntry> {
|
||||
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)
|
||||
}
|
||||
|
||||
const CAPACITY_PATH = 'capacity/members.json'
|
||||
|
||||
/** Read the capacity config from the pm-state repo (empty when absent). */
|
||||
export async function readCapacity(client: GiteaClient) {
|
||||
const file = await client.getFile(CAPACITY_PATH)
|
||||
if (!file) return []
|
||||
try {
|
||||
return parseCapacityConfig(JSON.parse(Buffer.from(file.contentBase64, 'base64').toString('utf8')))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Full reconcile: issues + milestones + native deps + lifecycle timelines. */
|
||||
export async function reconcileSnapshot(
|
||||
client: GiteaClient,
|
||||
@@ -81,16 +142,81 @@ export async function reconcileSnapshot(
|
||||
return { issues, milestones, deps, timelines }
|
||||
}
|
||||
|
||||
type Snapshot = Awaited<ReturnType<typeof reconcileSnapshot>>
|
||||
|
||||
/**
|
||||
* A single in-memory reconcile cache shared across the app. A full reconcile is
|
||||
* ~2N gitea calls (deps + timelines per issue); without this, every agent tool
|
||||
* call refetched the whole repo. Reads within `maxAgeMs` reuse the cache;
|
||||
* `getSnapshot({ maxAgeMs: 0 })` forces a fresh pull (the explicit UI reconcile),
|
||||
* and any write calls `invalidateSnapshot()` so the next read sees it. The cache
|
||||
* is rebuildable — the durable truth stays in gitea (the purity split, D4).
|
||||
*/
|
||||
let snapshotCache: { snap: Snapshot; at: number } | null = null
|
||||
|
||||
export async function getSnapshot(client: GiteaClient, opts?: { maxAgeMs?: number }): Promise<Snapshot> {
|
||||
const maxAgeMs = opts?.maxAgeMs ?? 0
|
||||
if (snapshotCache && maxAgeMs > 0 && Date.now() - snapshotCache.at <= maxAgeMs) {
|
||||
return snapshotCache.snap
|
||||
}
|
||||
const snap = await reconcileSnapshot(client)
|
||||
snapshotCache = { snap, at: Date.now() }
|
||||
saveSnapshot(snap, new Date().toISOString()) // persist for instant boot + offline
|
||||
return snap
|
||||
}
|
||||
|
||||
/** Drop the cache so the next read reflects a just-made write. */
|
||||
export function invalidateSnapshot(): void {
|
||||
snapshotCache = null
|
||||
}
|
||||
|
||||
/**
|
||||
* The last persisted snapshot (from a previous session), for instant boot. The
|
||||
* renderer shows it immediately, then a real reconcile supersedes it
|
||||
* (stale-while-revalidate). Returns null when there's nothing on disk; its
|
||||
* `savedAt` marks staleness. It does NOT seed the cache — agent tool calls
|
||||
* always reconcile fresh so they never reason over stale data.
|
||||
*/
|
||||
export function bootSnapshot(): (Snapshot & { savedAt: string }) | null {
|
||||
const persisted = loadSnapshot()
|
||||
if (!persisted) return null
|
||||
return {
|
||||
issues: persisted.issues,
|
||||
milestones: persisted.milestones,
|
||||
deps: persisted.deps,
|
||||
timelines: persisted.timelines,
|
||||
savedAt: persisted.savedAt,
|
||||
} as unknown as Snapshot & { savedAt: string }
|
||||
}
|
||||
|
||||
/** Agent tool calls tolerate a slightly stale snapshot (seconds) to stay responsive. */
|
||||
export const AGENT_SNAPSHOT_TTL_MS = 30_000
|
||||
|
||||
export function registerGiteaIpc(): void {
|
||||
const client = getGiteaClient()
|
||||
const repo = client ? `${process.env.GITEA_OWNER ?? 'christian'}/${process.env.GITEA_REPO ?? 'commitea'}` : null
|
||||
|
||||
ipcMain.handle('gitea:status', () => ({ configured: !!client, repo }))
|
||||
|
||||
// Instant boot: the last persisted snapshot, shown before the fresh reconcile lands.
|
||||
ipcMain.handle('gitea:boot', () => {
|
||||
if (!client) return { configured: false }
|
||||
const persisted = bootSnapshot()
|
||||
return persisted ? { configured: true, cached: true, ...persisted } : { configured: true, cached: false }
|
||||
})
|
||||
|
||||
ipcMain.handle('gitea:reconcile', async () => {
|
||||
if (!client) return { configured: false, issues: [], milestones: [], deps: [], timelines: {} }
|
||||
const snap = await reconcileSnapshot(client)
|
||||
return { configured: true, ...snap }
|
||||
try {
|
||||
// explicit UI sync — force fresh, and warm the cache for agent tool calls
|
||||
const snap = await getSnapshot(client, { maxAgeMs: 0 })
|
||||
return { configured: true, stale: false, ...snap }
|
||||
} catch (e) {
|
||||
// offline / gitea down — serve the last persisted snapshot rather than error out
|
||||
const persisted = bootSnapshot()
|
||||
if (persisted) return { configured: true, stale: true, ...persisted }
|
||||
throw e
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('gitea:getIssue', async (_event, index: number) => {
|
||||
@@ -122,6 +248,7 @@ export function registerGiteaIpc(): void {
|
||||
const ids = await resolveLabelIds(plan.labels)
|
||||
await client.setIssueLabels(change.issue, ids)
|
||||
const issue = await client.getIssue(change.issue)
|
||||
invalidateSnapshot() // the board + forecast must reflect the label change
|
||||
return { ok: true as const, plan, issue }
|
||||
})
|
||||
|
||||
@@ -138,7 +265,30 @@ export function registerGiteaIpc(): void {
|
||||
const issue = await client.createIssue({ title: it.title, body: it.body, labelIds })
|
||||
created.push({ number: issue.number, title: issue.title })
|
||||
}
|
||||
if (created.length) invalidateSnapshot() // new issues enter the board/scope
|
||||
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) }
|
||||
}
|
||||
})
|
||||
|
||||
// Read the capacity config from the pm-state repo (for capacity-aware forecasts).
|
||||
ipcMain.handle('pmstate:capacity', async () => {
|
||||
const pm = getPmStateClient()
|
||||
if (!pm) return { ok: false as const, reason: 'unconfigured' as const, members: [] }
|
||||
try {
|
||||
return { ok: true as const, members: await readCapacity(pm) }
|
||||
} catch {
|
||||
return { ok: true as const, members: [] }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -22,10 +22,17 @@ import {
|
||||
REGINALD_SYSTEM,
|
||||
REGINALD_TOOLS,
|
||||
runAgentTurn,
|
||||
toDirectiveInput,
|
||||
} from '@commitea/core'
|
||||
import { ipcMain } from 'electron'
|
||||
|
||||
import { getGiteaClient, reconcileSnapshot } from './gitea.js'
|
||||
import {
|
||||
AGENT_SNAPSHOT_TTL_MS,
|
||||
appendDirectiveEntry,
|
||||
getGiteaClient,
|
||||
getPmStateClient,
|
||||
getSnapshot,
|
||||
} from './gitea.js'
|
||||
|
||||
/** Small local model for prose + the read tool; big model reserved for later decomposition. */
|
||||
function resolveModelRouter(): ModelRouter | null {
|
||||
@@ -79,11 +86,15 @@ export function registerModelIpc(): void {
|
||||
return { configured: true, model }
|
||||
})
|
||||
|
||||
ipcMain.handle('model:chat', async (_event, messages: ChatMessage[]) => {
|
||||
ipcMain.handle('model:chat', async (event, messages: ChatMessage[]) => {
|
||||
if (!router) return { ok: false as const, reason: 'unconfigured' as const }
|
||||
const client = getGiteaClient()
|
||||
const model = await resolveLoadedModel(router.small.baseUrl, router.small.model)
|
||||
const chat = createChatClient({ ...router.small, model }, fetch)
|
||||
// stream the model's prose to the renderer token-by-token
|
||||
const onToken = (delta: string) => {
|
||||
if (!event.sender.isDestroyed()) event.sender.send('model:chat:token', delta)
|
||||
}
|
||||
|
||||
// Proposals the model formulates this turn; the renderer approves them (the
|
||||
// write happens through gitea:applyChange, never inside the loop).
|
||||
@@ -92,7 +103,8 @@ export function registerModelIpc(): void {
|
||||
const execute = async (name: string, args: unknown) => {
|
||||
if (!client) return { error: 'gitea is not configured' }
|
||||
if (name === 'query_project') {
|
||||
const snap = await reconcileSnapshot(client)
|
||||
// reuse a recent reconcile — a multi-tool turn shouldn't refetch the repo each call
|
||||
const snap = await getSnapshot(client, { maxAgeMs: AGENT_SNAPSHOT_TTL_MS })
|
||||
const a = (args ?? {}) as { view: ProjectView; filters?: QueryFilters }
|
||||
return buildProjectView(a.view, a.filters, snap, new Date())
|
||||
}
|
||||
@@ -106,15 +118,26 @@ 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}` }
|
||||
}
|
||||
|
||||
try {
|
||||
const turn = await runAgentTurn({
|
||||
complete: (m, t) => chat.complete(m, t),
|
||||
complete: (m, t, ot) => chat.complete(m, t, ot),
|
||||
messages: [{ role: 'system', content: REGINALD_SYSTEM }, ...messages],
|
||||
tools: REGINALD_TOOLS,
|
||||
execute,
|
||||
onToken,
|
||||
})
|
||||
return { ok: true as const, content: turn.content, steps: turn.steps, proposals }
|
||||
} catch (e) {
|
||||
|
||||
47
apps/desktop/src/main/snapshot-store.ts
Normal file
47
apps/desktop/src/main/snapshot-store.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Durable snapshot store — the reconcile cache, persisted to disk. On boot the
|
||||
* app shows the last snapshot instantly (stale-while-revalidate) instead of a
|
||||
* blank board while ~2N gitea calls run; if gitea is unreachable, reads fall
|
||||
* back to it (offline). It's a rebuildable mirror — the durable truth stays in
|
||||
* gitea (the purity split, D4). A plain JSON file: the whole snapshot fits in
|
||||
* memory at this scale, so indexed SQL buys nothing yet (see the PR).
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { app } from 'electron'
|
||||
|
||||
/** The shape we persist — kept loose so a schema drift degrades to "no cache", not a crash. */
|
||||
export interface PersistedSnapshot {
|
||||
issues: unknown[]
|
||||
milestones: unknown[]
|
||||
deps: unknown[]
|
||||
timelines: Record<number, unknown[]>
|
||||
/** ISO time the snapshot was reconciled — shown as "cached since". */
|
||||
savedAt: string
|
||||
}
|
||||
|
||||
function snapshotPath(): string {
|
||||
return join(app.getPath('userData'), 'commitea-snapshot.json')
|
||||
}
|
||||
|
||||
/** Load the last persisted snapshot, or null if absent/corrupt. Never throws. */
|
||||
export function loadSnapshot(): PersistedSnapshot | null {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(snapshotPath(), 'utf8')) as PersistedSnapshot
|
||||
if (parsed && Array.isArray(parsed.issues)) return parsed
|
||||
return null
|
||||
} catch {
|
||||
return null // missing file, bad JSON, or drift — treat as no cache
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist a freshly reconciled snapshot. Best-effort — a write failure never breaks a reconcile. */
|
||||
export function saveSnapshot(snap: Omit<PersistedSnapshot, 'savedAt'>, savedAt: string): void {
|
||||
try {
|
||||
writeFileSync(snapshotPath(), JSON.stringify({ ...snap, savedAt }), 'utf8')
|
||||
} catch {
|
||||
// disk full / permissions — the in-memory cache still works this session
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ const api = {
|
||||
gitea: {
|
||||
/** Whether the main process has a gitea token + target repo configured. */
|
||||
status: () => ipcRenderer.invoke('gitea:status'),
|
||||
/** The last persisted snapshot, for instant boot before the fresh reconcile. */
|
||||
boot: () => ipcRenderer.invoke('gitea:boot'),
|
||||
/** Full read of the managed repo — every issue + milestone. */
|
||||
reconcile: () => ipcRenderer.invoke('gitea:reconcile'),
|
||||
/** One issue by index, normalized (or null if unconfigured). */
|
||||
@@ -14,11 +16,23 @@ const api = {
|
||||
/** 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'),
|
||||
/** Read the capacity config from the pm-state repo. */
|
||||
capacity: () => ipcRenderer.invoke('pmstate:capacity'),
|
||||
},
|
||||
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),
|
||||
/** Subscribe to streamed prose tokens for the in-flight turn; returns an unsubscribe. */
|
||||
onToken: (cb: (delta: string) => void) => {
|
||||
const listener = (_e: unknown, delta: string) => cb(delta)
|
||||
ipcRenderer.on('model:chat:token', listener)
|
||||
return () => ipcRenderer.removeListener('model:chat:token', listener)
|
||||
},
|
||||
/** Decompose a braindump into a proposed issue set (capture_work). */
|
||||
capture: (braindump: string) => ipcRenderer.invoke('model:capture', braindump),
|
||||
},
|
||||
|
||||
@@ -8,6 +8,35 @@ export function DirectivesScreen() {
|
||||
const [pending, setPending] = React.useState<DirectivePending | null>(DIRECTIVES.pending)
|
||||
const [entries, setEntries] = React.useState<DirectiveEntry[]>(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',
|
||||
|
||||
@@ -1,22 +1,44 @@
|
||||
import React from 'react'
|
||||
|
||||
import { COLUMNS, type IssueRef } from '../../data/fixtures.js'
|
||||
import { type MilestoneView } from '../../lib/backlog.js'
|
||||
import { BurnUpCone } from '../charts/chart.js'
|
||||
import { Badge, Button, Card, Icon, Tag } from '../ui/index.js'
|
||||
|
||||
// Milestone detail — scope, cone, issues; forecasts stay ranges
|
||||
export function MilestoneScreen({ onBack, onOpenIssue }: { onBack: () => void; onOpenIssue: (issue: IssueRef) => void }) {
|
||||
// Milestone detail — scope, cone, issues; forecasts stay ranges.
|
||||
// `data` (real milestone forecast) overrides the demo fixture when present.
|
||||
export function MilestoneScreen({
|
||||
onBack,
|
||||
onOpenIssue,
|
||||
data,
|
||||
}: {
|
||||
onBack: () => void
|
||||
onOpenIssue: (issue: IssueRef) => void
|
||||
data?: MilestoneView
|
||||
}) {
|
||||
const cols = COLUMNS
|
||||
const byState = (ids: number[]) =>
|
||||
cols.flatMap((c) => c.issues.map((i) => ({ ...i, col: c.label }))).filter((i) => ids.includes(i.id))
|
||||
|
||||
const groups = [
|
||||
const fixtureGroups = [
|
||||
{ label: 'Steeping', issues: byState([87, 84]) },
|
||||
{ label: 'In review', issues: byState([92]) },
|
||||
{ label: 'Queued', issues: byState([102, 103, 99, 96, 78]) },
|
||||
{ label: 'Done', issues: byState([71, 69, 65]), muted: true },
|
||||
]
|
||||
|
||||
// real or demo, in one shape the render loop understands
|
||||
const groups = data
|
||||
? data.groups.map((g) => ({ label: g.label, issues: g.issues, muted: g.label === 'Done' }))
|
||||
: fixtureGroups
|
||||
const name = data ? data.name : 'Beta'
|
||||
const dueLine = data
|
||||
? `milestone · due ${data.due} · ${data.soft ? 'soft — scope may flex' : 'hard deadline'}`
|
||||
: 'milestone · due Mar 15 · soft — scope may flex'
|
||||
const forecastLabel = data ? (data.forecastRange ? `80% ${data.forecastRange}` : 'all shipped') : '80% Mar 3–12'
|
||||
const scopeStat = data ? `${data.scopeCount} issues · est ${data.scopeEstDays}d` : '42 issues · est 61d'
|
||||
const doneStat = data ? `${data.doneCount} · ${data.donePct}%` : '24 · 57%'
|
||||
|
||||
const Stat = ({ label, value, tone }: { label: string; value: string; tone?: string }) => (
|
||||
<div style={{ flex: 1, padding: '12px 18px', borderRight: '1px solid var(--line-1)' }}>
|
||||
<div style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>{label}</div>
|
||||
@@ -36,12 +58,12 @@ export function MilestoneScreen({ onBack, onOpenIssue }: { onBack: () => void; o
|
||||
<header style={{ borderBottom: 'var(--rule-double)', paddingBottom: 14, display: 'flex', alignItems: 'flex-start', gap: 16 }}>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-3)', margin: '0 0 6px', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
<Icon name="milestone" size={13} /> milestone · due Mar 15 · soft — scope may flex
|
||||
<Icon name="milestone" size={13} /> {dueLine}
|
||||
</p>
|
||||
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Beta</h1>
|
||||
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>{name}</h1>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10 }}>
|
||||
<Badge tone="ok" dot>ahead of forecast</Badge>
|
||||
<span style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>80% Mar 3–12</span>
|
||||
<Badge tone="ok" dot>{data ? `${data.doneCount}/${data.scopeCount} done` : 'ahead of forecast'}</Badge>
|
||||
<span style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>{forecastLabel}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="secondary" icon="arrow-up-right">Open in Gitea</Button>
|
||||
@@ -51,21 +73,25 @@ export function MilestoneScreen({ onBack, onOpenIssue }: { onBack: () => void; o
|
||||
{/* stats strip */}
|
||||
<Card flush>
|
||||
<div style={{ display: 'flex' }}>
|
||||
<Stat label="Scope" value="42 issues · est 61d" />
|
||||
<Stat label="Done" value="24 · 57%" />
|
||||
<Stat label="Forecast" value="80% Mar 3–12" />
|
||||
<Stat label="Scope" value={scopeStat} />
|
||||
<Stat label="Done" value={doneStat} />
|
||||
<Stat label="Forecast" value={forecastLabel} />
|
||||
<div style={{ flex: 1, padding: '12px 18px' }}>
|
||||
<div style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>Drift · 7d</div>
|
||||
<div style={{ font: '500 14px var(--font-mono)', color: 'var(--ok)', whiteSpace: 'nowrap' }}>−2d · cone narrowed</div>
|
||||
<div style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>Remaining</div>
|
||||
<div style={{ font: '500 14px var(--font-mono)', color: 'var(--ink-1)', whiteSpace: 'nowrap' }}>{data ? `${data.scopeCount - data.doneCount} open` : '−2d · cone narrowed'}</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 14, alignItems: 'start' }}>
|
||||
<Card overline="Burn-up" title={<>80% this lands <span style={{ whiteSpace: 'nowrap' }}>Mar 3–12</span></>} jade>
|
||||
<BurnUpCone />
|
||||
<Card overline="Burn-up" title={<>80% this lands <span style={{ whiteSpace: 'nowrap' }}>{data ? (data.forecastRange ?? 'shipped') : 'Mar 3–12'}</span></>} jade>
|
||||
<BurnUpCone data={data?.cone ?? undefined} />
|
||||
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 0' }}>
|
||||
Comfortably ahead. Beta needs #87 more than it needs my commentary.
|
||||
{data
|
||||
? data.cone
|
||||
? `${data.scopeCount - data.doneCount} open of ${data.scopeCount}. Cone over what's left.`
|
||||
: 'Everything here has shipped.'
|
||||
: 'Comfortably ahead. Beta needs #87 more than it needs my commentary.'}
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -1,19 +1,35 @@
|
||||
import React from 'react'
|
||||
|
||||
import { type CapacityMember, capacityPerWorkday } from '@commitea/core'
|
||||
|
||||
import { RunwayBar } from '../charts/chart.js'
|
||||
import { Card, Badge, Tag, Icon, IconButton } from '../ui/index.js'
|
||||
import { RUNWAY, CAPACITY } from '../../data/fixtures.js'
|
||||
import { RUNWAY, CAPACITY, type RunwayMilestone } from '../../data/fixtures.js'
|
||||
|
||||
// Runway — capacity vs milestone dates; ranges, never points
|
||||
// Runway — capacity vs milestone dates; ranges, never points.
|
||||
// `milestones` (real per-milestone forecasts) + `capacity` (real config) override the demo.
|
||||
export function RunwayScreen({
|
||||
onOpenCalibration,
|
||||
onOpenMilestone,
|
||||
calibration,
|
||||
milestones,
|
||||
capacity,
|
||||
}: {
|
||||
onOpenCalibration: () => void
|
||||
onOpenMilestone: () => void
|
||||
onOpenMilestone: (id?: number) => void
|
||||
calibration?: { n: number; coldStart: boolean }
|
||||
milestones?: RunwayMilestone[]
|
||||
capacity?: CapacityMember[]
|
||||
}) {
|
||||
const rows = milestones && milestones.length ? milestones : RUNWAY
|
||||
const capacityRows =
|
||||
capacity && capacity.length
|
||||
? capacity.map((m) => ({
|
||||
who: m.person,
|
||||
slices: `focus ${m.focusFactor} · alloc ${Math.round(m.allocation * 100)}%`,
|
||||
hours: `${capacityPerWorkday(m).toFixed(2)} pd/day`,
|
||||
}))
|
||||
: CAPACITY
|
||||
const calibNote = calibration
|
||||
? calibration.coldStart
|
||||
? `cold-start priors · ${calibration.n}/20 closed issues estimated`
|
||||
@@ -28,8 +44,8 @@ export function RunwayScreen({
|
||||
|
||||
<Card overline="Milestones" flush>
|
||||
<div>
|
||||
{RUNWAY.map((m, i) => (
|
||||
<div key={m.name} onClick={onOpenMilestone} style={{
|
||||
{rows.map((m, i) => (
|
||||
<div key={m.name} onClick={() => onOpenMilestone(m.id)} style={{
|
||||
display: 'grid', gridTemplateColumns: '160px 1fr 150px 90px', gap: 16, alignItems: 'center', cursor: 'pointer',
|
||||
padding: '14px 20px', borderTop: i === 0 ? 'none' : '1px solid var(--line-1)',
|
||||
}}
|
||||
@@ -55,7 +71,7 @@ export function RunwayScreen({
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, alignItems: 'start' }}>
|
||||
<Card overline="Capacity" flush>
|
||||
<div>
|
||||
{CAPACITY.map((p, i) => (
|
||||
{capacityRows.map((p, i) => (
|
||||
<div key={p.who} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 12, padding: '12px 20px',
|
||||
borderTop: i === 0 ? 'none' : '1px solid var(--line-1)',
|
||||
|
||||
@@ -4,8 +4,17 @@ import logoIcon from '../../design/assets/logo-icon.png'
|
||||
import type { IssueChange } from '@commitea/core'
|
||||
|
||||
import type { IssueRef } from '../../data/fixtures.js'
|
||||
import { backlogCalibration, forecastBacklog, issuesToBoardColumns, scheduleFocus } from '../../lib/backlog.js'
|
||||
import {
|
||||
backlogCalibration,
|
||||
capacityWorkers,
|
||||
forecastBacklog,
|
||||
issuesToBoardColumns,
|
||||
milestoneView,
|
||||
runwayView,
|
||||
scheduleFocus,
|
||||
} from '../../lib/backlog.js'
|
||||
import { useBacklog } from '../../lib/use-backlog.js'
|
||||
import { useCapacity } from '../../lib/use-capacity.js'
|
||||
import { PrimitivesGallery } from '../gallery.js'
|
||||
import { BoardScreen } from '../screens/board-screen.js'
|
||||
import { CalibrationScreen } from '../screens/calibration-screen.js'
|
||||
@@ -87,7 +96,10 @@ export function AppShell() {
|
||||
const [offline, setOffline] = useState(false)
|
||||
const [issue, setIssue] = useState<IssueRef | null>(null)
|
||||
const [readIds, setReadIds] = useState<number[]>([])
|
||||
const [milestoneId, setMilestoneId] = useState<number | null>(null)
|
||||
const [backlog, refetchBacklog] = useBacklog()
|
||||
const capacityMembers = useCapacity()
|
||||
const workers = capacityWorkers(capacityMembers)
|
||||
const boardColumns =
|
||||
backlog.status === 'ready' ? issuesToBoardColumns(backlog.issues, backlog.timelines) : undefined
|
||||
const focus =
|
||||
@@ -96,7 +108,24 @@ export function AppShell() {
|
||||
backlog.status === 'ready' ? backlogCalibration(backlog.issues, backlog.timelines) : undefined
|
||||
const forecast =
|
||||
backlog.status === 'ready'
|
||||
? (forecastBacklog(backlog.issues, backlog.deps, new Date(), calibration?.model) ?? undefined)
|
||||
? (forecastBacklog(backlog.issues, backlog.deps, new Date(), calibration?.model, workers) ?? undefined)
|
||||
: undefined
|
||||
const runwayMilestones =
|
||||
backlog.status === 'ready'
|
||||
? runwayView(backlog.issues, backlog.milestones, backlog.deps, new Date(), workers)
|
||||
: undefined
|
||||
const milestone =
|
||||
backlog.status === 'ready' && milestoneId != null
|
||||
? (milestoneView(
|
||||
milestoneId,
|
||||
backlog.issues,
|
||||
backlog.milestones,
|
||||
backlog.deps,
|
||||
backlog.timelines,
|
||||
calibration?.model,
|
||||
new Date(),
|
||||
workers,
|
||||
) ?? undefined)
|
||||
: undefined
|
||||
|
||||
useEffect(() => {
|
||||
@@ -194,14 +223,19 @@ export function AppShell() {
|
||||
return (
|
||||
<RunwayScreen
|
||||
onOpenCalibration={() => setView('calibration')}
|
||||
onOpenMilestone={() => setView('milestone')}
|
||||
onOpenMilestone={(id) => {
|
||||
setMilestoneId(id ?? null)
|
||||
setView('milestone')
|
||||
}}
|
||||
calibration={calibration ? { n: calibration.model.n, coldStart: calibration.model.coldStart } : undefined}
|
||||
milestones={runwayMilestones}
|
||||
capacity={capacityMembers}
|
||||
/>
|
||||
)
|
||||
case 'calibration':
|
||||
return <CalibrationScreen onBack={() => setView('runway')} data={calibration?.data} />
|
||||
case 'milestone':
|
||||
return <MilestoneScreen onBack={() => setView('runway')} onOpenIssue={openIssue} />
|
||||
return <MilestoneScreen onBack={() => setView('runway')} onOpenIssue={openIssue} data={milestone} />
|
||||
case 'inbox':
|
||||
return (
|
||||
<InboxScreen
|
||||
|
||||
@@ -19,7 +19,7 @@ export interface ChatPanelProps {
|
||||
}
|
||||
|
||||
export function ChatPanel({ onOpenDirectives, offline, onApplyChange }: ChatPanelProps) {
|
||||
const { msgs, thinking, live, model, steps, proposals, send: sendChat, approve, dismiss } = useChat(onApplyChange)
|
||||
const { msgs, thinking, live, model, steps, proposals, streaming, send: sendChat, approve, dismiss } = useChat(onApplyChange)
|
||||
// shorten "google/gemma-4-26b-a4b-qat" → "gemma-4-26b" for the header chip
|
||||
const modelLabel = model ? (model.split('/').pop() ?? model).replace(/-(qat|instruct|it|gguf)$/i, '') : 'gemma-4'
|
||||
const [text, setText] = useState('')
|
||||
@@ -28,7 +28,7 @@ export function ChatPanel({ onOpenDirectives, offline, onApplyChange }: ChatPane
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current
|
||||
if (el) el.scrollTop = el.scrollHeight
|
||||
}, [msgs, thinking])
|
||||
}, [msgs, thinking, streaming])
|
||||
|
||||
const send = () => {
|
||||
const t = text.trim()
|
||||
@@ -98,10 +98,17 @@ export function ChatPanel({ onOpenDirectives, offline, onApplyChange }: ChatPane
|
||||
The model is away from its desk. Reads still work; writes will wait their turn.
|
||||
</div>
|
||||
) : null}
|
||||
{thinking ? <div style={{ font: 'var(--text-agent)', color: 'var(--ink-3)' }}>considering…</div> : null}
|
||||
{streaming ? (
|
||||
<div style={{ font: 'var(--text-agent)', color: 'var(--ink-1)', lineHeight: 1.55 }}>
|
||||
{streaming}
|
||||
<span style={{ opacity: 0.5 }}>▊</span>
|
||||
</div>
|
||||
) : thinking ? (
|
||||
<div style={{ font: 'var(--text-agent)', color: 'var(--ink-3)' }}>considering…</div>
|
||||
) : null}
|
||||
{!thinking && steps.length ? (
|
||||
<div style={{ font: 'var(--text-caption)', color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 5 }}>
|
||||
<Icon name="eye" size={11} /> consulted {Array.from(new Set(steps.map((s) => s.replace('query_project', 'the project').replace('propose_change', 'the labels')))).join(', ')}
|
||||
<Icon name="eye" size={11} /> consulted {Array.from(new Set(steps.map((s) => s.replace('query_project', 'the project').replace('propose_change', 'the labels').replace('record_directive', 'the directive ledger')))).join(', ')}
|
||||
</div>
|
||||
) : null}
|
||||
{proposals.map((p) => (
|
||||
|
||||
@@ -315,6 +315,8 @@ export interface RunwayMilestone {
|
||||
spread: number
|
||||
tone: 'ok' | 'warn'
|
||||
note: string
|
||||
/** gitea milestone id, for the drill-in (absent on the demo fixture). */
|
||||
id?: number
|
||||
}
|
||||
|
||||
export const RUNWAY: RunwayMilestone[] = [
|
||||
|
||||
51
apps/desktop/src/renderer/src/global.d.ts
vendored
51
apps/desktop/src/renderer/src/global.d.ts
vendored
@@ -1,9 +1,11 @@
|
||||
import type {
|
||||
AgentStep,
|
||||
CapacityMember,
|
||||
ChangeProposal,
|
||||
ChatMessage,
|
||||
CaptureProposal,
|
||||
DependencyEdge,
|
||||
DirectiveRecord,
|
||||
GiteaIssue,
|
||||
GiteaMilestone,
|
||||
IssueChange,
|
||||
@@ -27,17 +29,31 @@ export type CaptureResult =
|
||||
| { ok: false; reason: 'unconfigured' | 'error'; message?: string }
|
||||
| ({ ok: true } & CaptureProposal)
|
||||
|
||||
/** A reconciled snapshot as it crosses the bridge. */
|
||||
export interface SnapshotPayload {
|
||||
configured: boolean
|
||||
issues: GiteaIssue[]
|
||||
milestones: GiteaMilestone[]
|
||||
deps: DependencyEdge[]
|
||||
/** Normalized lifecycle events keyed by issue number. */
|
||||
timelines: Record<number, LifecycleEvent[]>
|
||||
/** true when served from the persisted cache (offline / instant boot). */
|
||||
stale?: boolean
|
||||
/** ISO time the persisted snapshot was reconciled (present on cached reads). */
|
||||
savedAt?: string
|
||||
}
|
||||
|
||||
/** Boot payload — the persisted snapshot, or a marker that there's none yet. */
|
||||
export type BootPayload =
|
||||
| { configured: false }
|
||||
| { configured: true; cached: false }
|
||||
| ({ configured: true; cached: true } & Omit<SnapshotPayload, 'configured'>)
|
||||
|
||||
/** The gitea bridge exposed by the preload over IPC (main-process backed). */
|
||||
export interface GiteaBridge {
|
||||
status(): Promise<{ configured: boolean; repo: string | null }>
|
||||
reconcile(): Promise<{
|
||||
configured: boolean
|
||||
issues: GiteaIssue[]
|
||||
milestones: GiteaMilestone[]
|
||||
deps: DependencyEdge[]
|
||||
/** Normalized lifecycle events keyed by issue number. */
|
||||
timelines: Record<number, LifecycleEvent[]>
|
||||
}>
|
||||
boot(): Promise<BootPayload>
|
||||
reconcile(): Promise<SnapshotPayload>
|
||||
getIssue(index: number): Promise<GiteaIssue | null>
|
||||
applyChange(change: IssueChange): Promise<ApplyChangeResult>
|
||||
createIssues(issues: ProposedIssue[]): Promise<CreateIssuesResult>
|
||||
@@ -53,6 +69,24 @@ export interface ModelBridge {
|
||||
status(): Promise<{ configured: boolean; model: string | null }>
|
||||
chat(messages: ChatMessage[]): Promise<ChatResult>
|
||||
capture(braindump: string): Promise<CaptureResult>
|
||||
/** Subscribe to streamed prose tokens; returns an unsubscribe fn. */
|
||||
onToken(cb: (delta: string) => void): () => void
|
||||
}
|
||||
|
||||
/** The result of reading the directive ledger. */
|
||||
export type DirectivesResult =
|
||||
| { ok: false; reason: 'unconfigured' | 'error'; message?: string }
|
||||
| { ok: true; directives: DirectiveRecord[] }
|
||||
|
||||
/** The result of reading the capacity config. */
|
||||
export type CapacityResult =
|
||||
| { ok: false; reason: 'unconfigured'; members: CapacityMember[] }
|
||||
| { ok: true; members: CapacityMember[] }
|
||||
|
||||
/** The pm-state bridge (machine-derived state) exposed by the preload over IPC. */
|
||||
export interface PmStateBridge {
|
||||
directives(): Promise<DirectivesResult>
|
||||
capacity(): Promise<CapacityResult>
|
||||
}
|
||||
|
||||
declare global {
|
||||
@@ -61,6 +95,7 @@ declare global {
|
||||
platform: string
|
||||
gitea: GiteaBridge
|
||||
model: ModelBridge
|
||||
pmstate: PmStateBridge
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,15 @@ import {
|
||||
type CalibrationModel,
|
||||
type CalibrationSample,
|
||||
calibrationSamples,
|
||||
type CapacityMember,
|
||||
capacityPerWorkday,
|
||||
COLD_START_THRESHOLD,
|
||||
type DependencyEdge,
|
||||
fitCalibration,
|
||||
forecast,
|
||||
type Worker,
|
||||
type GiteaIssue,
|
||||
type GiteaMilestone,
|
||||
inferLifecycle,
|
||||
type LifecycleColumn,
|
||||
type LifecycleEvent,
|
||||
@@ -16,10 +20,17 @@ import {
|
||||
type ScheduledItem,
|
||||
selectFocus,
|
||||
toDurationModel,
|
||||
workingDaysBetween,
|
||||
} from '@commitea/core'
|
||||
|
||||
import { type BoardColumn, type BoardIssue, type CalibrationData, type FocusIssue } from '../data/fixtures.js'
|
||||
import { type BurnUpData, buildBurnUpData } from './dates.js'
|
||||
import {
|
||||
type BoardColumn,
|
||||
type BoardIssue,
|
||||
type CalibrationData,
|
||||
type FocusIssue,
|
||||
type RunwayMilestone,
|
||||
} from '../data/fixtures.js'
|
||||
import { addWorkingDays, type BurnUpData, buildBurnUpData, formatRange, formatShort } from './dates.js'
|
||||
|
||||
type Timelines = Record<number, LifecycleEvent[]>
|
||||
|
||||
@@ -99,9 +110,15 @@ function toSchedulable(issues: GiteaIssue[]) {
|
||||
labels: i.labels,
|
||||
estimateDays: i.facts.estimateDays,
|
||||
priority: i.facts.priority,
|
||||
assignee: i.assignee,
|
||||
}))
|
||||
}
|
||||
|
||||
/** gitea CapacityMembers → scheduler lanes (person + throughput). */
|
||||
export function capacityWorkers(members: CapacityMember[]): Worker[] {
|
||||
return members.map((m) => ({ person: m.person, speed: capacityPerWorkday(m) }))
|
||||
}
|
||||
|
||||
export interface ForecastView {
|
||||
scope: number
|
||||
cone: BurnUpData
|
||||
@@ -124,9 +141,10 @@ export function forecastBacklog(
|
||||
deps: DependencyEdge[],
|
||||
today: Date = new Date(),
|
||||
calibration?: CalibrationModel,
|
||||
workers: Worker[] = [],
|
||||
): ForecastView | null {
|
||||
const model = calibration ? toDurationModel(calibration) : undefined
|
||||
const f = forecast(toSchedulable(issues), deps, model ? { model } : {})
|
||||
const f = forecast(toSchedulable(issues), deps, { ...(model ? { model } : {}), workers })
|
||||
const cone = buildBurnUpData(f, today)
|
||||
if (!cone) return null
|
||||
return {
|
||||
@@ -232,3 +250,138 @@ export function scheduleFocus(
|
||||
later: toFocusIssue(f.later, inf),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-milestone Monte Carlo forecast for the Runway screen — each open milestone's
|
||||
* open scope gets its own cone, and the p80 landing is compared to the milestone's
|
||||
* due date (ok/at-risk). Ranges, never point dates. Milestones with no open scope
|
||||
* (already shipped) are omitted. Falls back to the demo when there's nothing real.
|
||||
*/
|
||||
export function runwayView(
|
||||
issues: GiteaIssue[],
|
||||
milestones: GiteaMilestone[],
|
||||
deps: DependencyEdge[],
|
||||
today: Date = new Date(),
|
||||
workers: Worker[] = [],
|
||||
): RunwayMilestone[] {
|
||||
const open = issues.filter((i) => i.state === 'open')
|
||||
const rows = milestones
|
||||
.filter((m) => m.state === 'open')
|
||||
.map((m) => ({ m, scope: open.filter((i) => i.milestone?.id === m.id) }))
|
||||
.filter((x) => x.scope.length > 0)
|
||||
.map(({ m, scope }) => {
|
||||
const f = forecast(
|
||||
scope.map((i) => ({
|
||||
number: i.number,
|
||||
title: i.title,
|
||||
labels: i.labels,
|
||||
estimateDays: i.facts.estimateDays,
|
||||
priority: i.facts.priority,
|
||||
assignee: i.assignee,
|
||||
})),
|
||||
deps,
|
||||
{ workers },
|
||||
)
|
||||
const p90 = f.curve.length ? f.curve[f.curve.length - 1].p90Day : f.p95Day
|
||||
const dueDay = m.dueOn ? workingDaysBetween(today, new Date(m.dueOn)) : null
|
||||
return { m, p50: f.p50Day, p80: f.p80Day, p90, dueDay }
|
||||
})
|
||||
|
||||
const horizon = Math.max(1, ...rows.map((r) => Math.max(r.p90, r.dueDay ?? 0)))
|
||||
|
||||
return rows.map(({ m, p50, p80, p90, dueDay }) => {
|
||||
const onTrack = dueDay == null || p80 <= dueDay
|
||||
return {
|
||||
id: m.id,
|
||||
name: m.title,
|
||||
due: m.dueOn ? formatShort(new Date(m.dueOn)) : 'no date',
|
||||
hard: false,
|
||||
p80: formatRange(addWorkingDays(today, p50), addWorkingDays(today, p90)),
|
||||
pos: p80 / horizon,
|
||||
spread: Math.min(0.6, (p90 - p50) / horizon),
|
||||
tone: onTrack ? ('ok' as const) : ('warn' as const),
|
||||
note: dueDay == null ? `${Math.ceil(p80)}d of work` : onTrack ? 'on track' : 'at risk',
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export interface MilestoneGroup {
|
||||
label: string
|
||||
issues: { id: number; title: string; labels: string[]; days?: string }[]
|
||||
}
|
||||
|
||||
export interface MilestoneView {
|
||||
name: string
|
||||
due: string
|
||||
soft: boolean
|
||||
scopeCount: number
|
||||
scopeEstDays: number
|
||||
doneCount: number
|
||||
donePct: number
|
||||
/** p50..p90 landing range for the remaining open scope; null when nothing's open. */
|
||||
forecastRange: string | null
|
||||
cone: BurnUpData | null
|
||||
groups: MilestoneGroup[]
|
||||
}
|
||||
|
||||
/**
|
||||
* The Milestone drill-in: real scope, done %, a Monte Carlo cone over the
|
||||
* milestone's remaining open work, and its issues grouped by lifecycle column.
|
||||
* Returns null for an unknown id — the screen then shows the demo fixture.
|
||||
*/
|
||||
export function milestoneView(
|
||||
id: number,
|
||||
issues: GiteaIssue[],
|
||||
milestones: GiteaMilestone[],
|
||||
deps: DependencyEdge[],
|
||||
timelines: Timelines = {},
|
||||
calibration?: CalibrationModel,
|
||||
today: Date = new Date(),
|
||||
workers: Worker[] = [],
|
||||
): MilestoneView | null {
|
||||
const m = milestones.find((x) => x.id === id)
|
||||
if (!m) return null
|
||||
const all = issues.filter((i) => i.milestone?.id === id)
|
||||
const open = all.filter((i) => i.state === 'open')
|
||||
const done = all.filter((i) => i.state === 'closed')
|
||||
const scopeEstDays = all.reduce((sum, i) => sum + (i.facts.estimateDays ?? 2), 0)
|
||||
|
||||
const model = calibration ? toDurationModel(calibration) : undefined
|
||||
const f = forecast(
|
||||
open.map((i) => ({
|
||||
number: i.number,
|
||||
title: i.title,
|
||||
labels: i.labels,
|
||||
estimateDays: i.facts.estimateDays,
|
||||
priority: i.facts.priority,
|
||||
assignee: i.assignee,
|
||||
})),
|
||||
deps,
|
||||
{ ...(model ? { model } : {}), workers },
|
||||
)
|
||||
const cone = buildBurnUpData(f, today)
|
||||
|
||||
const inf = inferAll(all, timelines, today)
|
||||
const groups: MilestoneGroup[] = COLUMN_ORDER.map((key) => ({
|
||||
label: COLUMN_LABELS[key],
|
||||
issues: all
|
||||
.filter((i) => inf.get(i.number)!.column === key)
|
||||
.map((i) => {
|
||||
const days = inf.get(i.number)!.steepingDays
|
||||
return { id: i.number, title: i.title, labels: i.labels, days: days != null ? `${days}d` : undefined }
|
||||
}),
|
||||
})).filter((g) => g.issues.length > 0)
|
||||
|
||||
return {
|
||||
name: m.title,
|
||||
due: m.dueOn ? formatShort(new Date(m.dueOn)) : 'no date',
|
||||
soft: true,
|
||||
scopeCount: all.length,
|
||||
scopeEstDays,
|
||||
doneCount: done.length,
|
||||
donePct: all.length ? Math.round((done.length / all.length) * 100) : 0,
|
||||
forecastRange: cone ? cone.rangeLabel : null,
|
||||
cone,
|
||||
groups,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,13 +12,18 @@ export type BacklogState =
|
||||
milestones: GiteaMilestone[]
|
||||
deps: DependencyEdge[]
|
||||
timelines: Record<number, LifecycleEvent[]>
|
||||
/** true while showing the persisted snapshot (instant boot / offline). */
|
||||
stale: boolean
|
||||
/** ISO time the shown snapshot was reconciled, when stale. */
|
||||
savedAt?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile the managed repo through the main-process bridge. Runs once on
|
||||
* mount; the returned `refetch` re-reconciles after a write so the board and
|
||||
* forecast reflect the change. `unconfigured` means no token — the UI falls
|
||||
* back to demo fixtures. Errors (network, bad token) surface as `error`.
|
||||
* Reconcile the managed repo through the main-process bridge, stale-while-
|
||||
* revalidate: on mount it shows the persisted snapshot instantly (marked stale),
|
||||
* then a fresh reconcile supersedes it. If gitea is unreachable, the fresh
|
||||
* reconcile falls back to the persisted snapshot (offline). `refetch` re-syncs
|
||||
* after a write. `unconfigured` means no token — the UI uses demo fixtures.
|
||||
*/
|
||||
export function useBacklog(): [BacklogState, () => void] {
|
||||
const [state, setState] = useState<BacklogState>({ status: 'loading' })
|
||||
@@ -27,6 +32,30 @@ export function useBacklog(): [BacklogState, () => void] {
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
|
||||
// instant boot from the persisted snapshot (only on first mount, not refetch)
|
||||
if (nonce === 0) {
|
||||
window.commitea.gitea
|
||||
.boot()
|
||||
.then((b) => {
|
||||
if (!alive || !('cached' in b) || !b.cached) return
|
||||
setState((prev) =>
|
||||
prev.status === 'ready' && !prev.stale
|
||||
? prev // a fresh reconcile already won the race
|
||||
: {
|
||||
status: 'ready',
|
||||
issues: b.issues,
|
||||
milestones: b.milestones,
|
||||
deps: b.deps,
|
||||
timelines: b.timelines,
|
||||
stale: true,
|
||||
savedAt: b.savedAt,
|
||||
},
|
||||
)
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
window.commitea.gitea
|
||||
.reconcile()
|
||||
.then((r) => {
|
||||
@@ -39,12 +68,19 @@ export function useBacklog(): [BacklogState, () => void] {
|
||||
milestones: r.milestones,
|
||||
deps: r.deps,
|
||||
timelines: r.timelines,
|
||||
stale: r.stale ?? false,
|
||||
savedAt: r.savedAt,
|
||||
}
|
||||
: { status: 'unconfigured' },
|
||||
)
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (alive) setState({ status: 'error', message: e instanceof Error ? e.message : String(e) })
|
||||
if (alive) {
|
||||
// keep a shown boot snapshot rather than clobbering it with an error
|
||||
setState((prev) =>
|
||||
prev.status === 'ready' ? prev : { status: 'error', message: e instanceof Error ? e.message : String(e) },
|
||||
)
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
alive = false
|
||||
|
||||
24
apps/desktop/src/renderer/src/lib/use-capacity.ts
Normal file
24
apps/desktop/src/renderer/src/lib/use-capacity.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import type { CapacityMember } from '@commitea/core'
|
||||
|
||||
/**
|
||||
* The team's capacity config from the pm-state repo. Empty when unconfigured —
|
||||
* forecasts then fall back to a single serial worker. Read once on mount.
|
||||
*/
|
||||
export function useCapacity(): CapacityMember[] {
|
||||
const [members, setMembers] = useState<CapacityMember[]>([])
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
window.commitea.pmstate
|
||||
.capacity()
|
||||
.then((r) => {
|
||||
if (alive) setMembers(r.members)
|
||||
})
|
||||
.catch(() => {})
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [])
|
||||
return members
|
||||
}
|
||||
@@ -20,6 +20,8 @@ export interface ChatState {
|
||||
steps: string[]
|
||||
/** Changes Reginald has proposed and is awaiting approval on. */
|
||||
proposals: ChangeProposal[]
|
||||
/** The in-flight streamed prose (grows token-by-token) before the turn finalizes. */
|
||||
streaming: string
|
||||
send: (text: string) => void
|
||||
approve: (p: ChangeProposal) => void
|
||||
dismiss: (p: ChangeProposal) => void
|
||||
@@ -41,6 +43,7 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
||||
const [model, setModel] = useState<string | null>(null)
|
||||
const [steps, setSteps] = useState<string[]>([])
|
||||
const [proposals, setProposals] = useState<ChangeProposal[]>([])
|
||||
const [streaming, setStreaming] = useState('')
|
||||
const convoRef = useRef(convo)
|
||||
convoRef.current = convo
|
||||
|
||||
@@ -86,10 +89,17 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
||||
role: m.from === 'user' ? 'user' : 'assistant',
|
||||
content: m.text,
|
||||
}))
|
||||
setStreaming('')
|
||||
const unsubscribe = window.commitea.model.onToken((delta) => setStreaming((s) => s + delta))
|
||||
const finish = () => {
|
||||
unsubscribe()
|
||||
setThinking(false)
|
||||
setStreaming('')
|
||||
}
|
||||
window.commitea.model
|
||||
.chat(wire)
|
||||
.then((res) => {
|
||||
setThinking(false)
|
||||
finish()
|
||||
if (res.ok) {
|
||||
setSteps(res.steps.map((s) => s.tool))
|
||||
setProposals(res.proposals)
|
||||
@@ -105,7 +115,7 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
setThinking(false)
|
||||
finish()
|
||||
setConvo((c) => [...c, { from: 'agent', text: 'I could not reach the model.' }])
|
||||
})
|
||||
},
|
||||
@@ -137,5 +147,5 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
||||
setConvo((c) => [...c, { from: 'agent', text: `Left #${p.change.issue} as it was.` }])
|
||||
}, [])
|
||||
|
||||
return { msgs: [...seed, ...convo], thinking, live, model, steps, proposals, send, approve, dismiss }
|
||||
return { msgs: [...seed, ...convo], thinking, live, model, steps, proposals, streaming, send, approve, dismiss }
|
||||
}
|
||||
|
||||
@@ -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>): 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,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -31,18 +31,20 @@ function stringify(result: unknown): string {
|
||||
}
|
||||
|
||||
export async function runAgentTurn(opts: {
|
||||
complete: (messages: ChatMessage[], tools?: ToolDecl[]) => Promise<CompletionResult>
|
||||
complete: (messages: ChatMessage[], tools?: ToolDecl[], onToken?: (delta: string) => void) => Promise<CompletionResult>
|
||||
messages: ChatMessage[]
|
||||
tools: ToolDecl[]
|
||||
execute: ToolExecutor
|
||||
maxSteps?: number
|
||||
/** Streams content deltas as the model produces prose (final-answer streaming). */
|
||||
onToken?: (delta: string) => void
|
||||
}): Promise<AgentTurn> {
|
||||
const maxSteps = opts.maxSteps ?? DEFAULT_MAX_STEPS
|
||||
const convo: ChatMessage[] = [...opts.messages]
|
||||
const steps: AgentStep[] = []
|
||||
|
||||
for (let step = 0; step < maxSteps; step++) {
|
||||
const { content, toolCalls } = await opts.complete(convo, opts.tools)
|
||||
const { content, toolCalls } = await opts.complete(convo, opts.tools, opts.onToken)
|
||||
if (toolCalls.length === 0) {
|
||||
convo.push({ role: 'assistant', content })
|
||||
return { content, steps, messages: convo }
|
||||
@@ -63,7 +65,7 @@ export async function runAgentTurn(opts: {
|
||||
}
|
||||
|
||||
// Out of tool budget — force a final prose answer with tools withheld.
|
||||
const final = await opts.complete(convo, [])
|
||||
const final = await opts.complete(convo, [], opts.onToken)
|
||||
convo.push({ role: 'assistant', content: final.content })
|
||||
return { content: final.content, steps, messages: convo }
|
||||
}
|
||||
|
||||
@@ -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 #<number>. Be brief and plain — a sentence or two. No preamble, no bullet dumps.',
|
||||
].join(' ')
|
||||
|
||||
@@ -25,6 +25,48 @@ describe('createChatClient', () => {
|
||||
return { fetch, calls }
|
||||
}
|
||||
|
||||
function sseStub(chunks: string[]) {
|
||||
const calls: { url: string; body: unknown }[] = []
|
||||
const fetch: FetchLike = (url, init) => {
|
||||
calls.push({ url, body: init?.body ? JSON.parse(init.body) : undefined })
|
||||
const enc = new TextEncoder()
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(c) {
|
||||
for (const ch of chunks) c.enqueue(enc.encode(ch))
|
||||
c.close()
|
||||
},
|
||||
})
|
||||
return Promise.resolve({ ok: true, status: 200, body, json: () => Promise.resolve({}), text: () => Promise.resolve('') })
|
||||
}
|
||||
return { fetch, calls }
|
||||
}
|
||||
|
||||
it('streams content deltas via onToken and returns the assembled result', async () => {
|
||||
const { fetch, calls } = sseStub([
|
||||
'data: {"choices":[{"delta":{"content":"Right "}}]}\n\n',
|
||||
'data: {"choices":[{"delta":{"content":"now: #2."}}]}\n\n',
|
||||
'data: [DONE]\n\n',
|
||||
])
|
||||
const client = createChatClient({ baseUrl: 'http://x/v1', model: 'm' }, fetch)
|
||||
const tokens: string[] = []
|
||||
const res = await client.complete([{ role: 'user', content: 'now?' }], undefined, (d) => tokens.push(d))
|
||||
|
||||
expect(tokens).toEqual(['Right ', 'now: #2.'])
|
||||
expect(res.content).toBe('Right now: #2.')
|
||||
expect((calls[0].body as { stream?: boolean }).stream).toBe(true)
|
||||
})
|
||||
|
||||
it('assembles a streamed tool call from argument deltas', async () => {
|
||||
const { fetch } = sseStub([
|
||||
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"query_project","arguments":"{\\"view\\""}}]}}]}\n\n',
|
||||
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":":\\"focus\\"}"}}]}}]}\n\n',
|
||||
'data: [DONE]\n\n',
|
||||
])
|
||||
const client = createChatClient({ baseUrl: 'http://x/v1', model: 'm' }, fetch)
|
||||
const res = await client.complete([{ role: 'user', content: 'x' }], [{ name: 'query_project', description: '', parameters: {} }], () => {})
|
||||
expect(res.toolCalls).toEqual([{ id: 'c1', name: 'query_project', arguments: '{"view":"focus"}' }])
|
||||
})
|
||||
|
||||
it('POSTs to /chat/completions and parses content', async () => {
|
||||
const { fetch, calls } = stub({ choices: [{ message: { content: 'the focus is #2' } }] })
|
||||
const client = createChatClient({ baseUrl: 'http://localhost:1234/v1', model: 'gemma' }, fetch)
|
||||
|
||||
@@ -48,8 +48,12 @@ export interface CompletionResult {
|
||||
toolCalls: ToolCall[]
|
||||
}
|
||||
|
||||
/** Called with each streamed content delta (final-prose streaming). */
|
||||
export type OnToken = (delta: string) => void
|
||||
|
||||
export interface ChatClient {
|
||||
complete(messages: ChatMessage[], tools?: ToolDecl[]): Promise<CompletionResult>
|
||||
/** When `onToken` is given, the response streams (SSE) and each content delta is emitted. */
|
||||
complete(messages: ChatMessage[], tools?: ToolDecl[], onToken?: OnToken): Promise<CompletionResult>
|
||||
}
|
||||
|
||||
/** Map our message shape to the OpenAI wire shape. */
|
||||
@@ -85,7 +89,7 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
||||
const url = `${config.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||
|
||||
return {
|
||||
async complete(messages, tools) {
|
||||
async complete(messages, tools, onToken) {
|
||||
const body: Record<string, unknown> = {
|
||||
model: config.model,
|
||||
messages: messages.map(toWireMessage),
|
||||
@@ -95,11 +99,13 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
||||
body.tools = tools.map(toWireTool)
|
||||
body.tool_choice = 'auto'
|
||||
}
|
||||
const stream = !!onToken
|
||||
if (stream) body.stream = true
|
||||
const res = await fetchImpl(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
Accept: stream ? 'text/event-stream' : 'application/json',
|
||||
...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
@@ -108,6 +114,8 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`model completion failed (${res.status}): ${text.slice(0, 200)}`)
|
||||
}
|
||||
if (stream && res.body) return readStream(res.body, onToken!)
|
||||
|
||||
const json = (await res.json()) as { choices?: { message: RawChoiceMessage }[] }
|
||||
const msg = json.choices?.[0]?.message
|
||||
return {
|
||||
@@ -121,3 +129,56 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Streamed tool-call delta: name arrives first, arguments accumulate across chunks. */
|
||||
interface RawToolDelta {
|
||||
index: number
|
||||
id?: string
|
||||
function?: { name?: string; arguments?: string }
|
||||
}
|
||||
|
||||
/** Parse an OpenAI SSE stream: emit content deltas via onToken, accumulate the final result. */
|
||||
async function readStream(body: ReadableStream<Uint8Array>, onToken: OnToken): Promise<CompletionResult> {
|
||||
const reader = body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
let content = ''
|
||||
const toolAcc: { id: string; name: string; arguments: string }[] = []
|
||||
|
||||
const handle = (data: string) => {
|
||||
if (data === '[DONE]') return
|
||||
let chunk: { choices?: { delta?: { content?: string; tool_calls?: RawToolDelta[] } }[] }
|
||||
try {
|
||||
chunk = JSON.parse(data)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const delta = chunk.choices?.[0]?.delta
|
||||
if (!delta) return
|
||||
if (delta.content) {
|
||||
content += delta.content
|
||||
onToken(delta.content)
|
||||
}
|
||||
for (const tc of delta.tool_calls ?? []) {
|
||||
const slot = (toolAcc[tc.index] ??= { id: '', name: '', arguments: '' })
|
||||
if (tc.id) slot.id = tc.id
|
||||
if (tc.function?.name) slot.name = tc.function.name
|
||||
if (tc.function?.arguments) slot.arguments += tc.function.arguments
|
||||
}
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() ?? ''
|
||||
for (const line of lines) {
|
||||
const t = line.trim()
|
||||
if (t.startsWith('data:')) handle(t.slice(5).trim())
|
||||
}
|
||||
}
|
||||
if (buffer.trim().startsWith('data:')) handle(buffer.trim().slice(5).trim())
|
||||
|
||||
return { content, toolCalls: toolAcc.filter((t) => t.name).map((t) => ({ id: t.id, name: t.name, arguments: t.arguments })) }
|
||||
}
|
||||
|
||||
88
packages/core/src/capacity/capacity-v0.test.ts
Normal file
88
packages/core/src/capacity/capacity-v0.test.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { type DependencyEdge, type SchedulableIssue } from '../scheduler/scheduler-v0.js'
|
||||
import { makespan, scheduleWithCapacity, type Worker } from '../scheduler/scheduler-capacity-v0.js'
|
||||
import { capacityPerWorkday, parseCapacityConfig } from './capacity-v0.js'
|
||||
|
||||
describe('capacity model', () => {
|
||||
it('capacityPerWorkday = focusFactor × allocation', () => {
|
||||
expect(capacityPerWorkday({ person: 'a', focusFactor: 0.8, allocation: 0.5 })).toBeCloseTo(0.4)
|
||||
})
|
||||
|
||||
it('parses + clamps config, drops invalid members', () => {
|
||||
const members = parseCapacityConfig({
|
||||
members: [
|
||||
{ person: 'christian', focusFactor: 0.8, allocation: 1 },
|
||||
{ person: 'ak', focusFactor: 1.5, allocation: -1 }, // clamps to 1 / 0 → zero capacity → dropped
|
||||
{ focusFactor: 0.8 }, // no person → dropped
|
||||
],
|
||||
})
|
||||
expect(members).toEqual([{ person: 'christian', focusFactor: 0.8, allocation: 1 }])
|
||||
})
|
||||
|
||||
it('returns [] for a non-array/absent members field', () => {
|
||||
expect(parseCapacityConfig({})).toEqual([])
|
||||
expect(parseCapacityConfig({ members: 'nope' })).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
function issue(number: number, over: Partial<SchedulableIssue> = {}): SchedulableIssue {
|
||||
return { number, title: `#${number}`, labels: [], estimateDays: 4, priority: 2, ...over }
|
||||
}
|
||||
|
||||
describe('scheduleWithCapacity', () => {
|
||||
it('with no workers, falls back to the single serial plan', () => {
|
||||
const issues = [issue(1), issue(2)]
|
||||
const plan = scheduleWithCapacity(issues, [], [])
|
||||
expect(makespan(plan)).toBe(8) // 4 + 4 serial
|
||||
})
|
||||
|
||||
it('parallelizes independent work across lanes (makespan shrinks)', () => {
|
||||
const issues = [issue(1), issue(2), issue(3), issue(4)] // 4×4d = 16d serial
|
||||
const one: Worker[] = [{ person: 'a', speed: 1 }]
|
||||
const two: Worker[] = [
|
||||
{ person: 'a', speed: 1 },
|
||||
{ person: 'b', speed: 1 },
|
||||
]
|
||||
expect(makespan(scheduleWithCapacity(issues, [], one))).toBe(16)
|
||||
expect(makespan(scheduleWithCapacity(issues, [], two))).toBe(8) // two lanes → half
|
||||
})
|
||||
|
||||
it('scales duration by a lane speed (slower lane takes longer)', () => {
|
||||
const plan = scheduleWithCapacity([issue(1, { estimateDays: 4 })], [], [{ person: 'a', speed: 0.5 }])
|
||||
expect(plan.items[0].durationDays).toBe(8) // 4 / 0.5
|
||||
expect(plan.items[0].worker).toBe('a')
|
||||
})
|
||||
|
||||
it('routes an issue to its assignee lane', () => {
|
||||
const issues = [issue(1, { assignee: 'ak' }), issue(2, { assignee: 'sm' })]
|
||||
const workers: Worker[] = [
|
||||
{ person: 'ak', speed: 1 },
|
||||
{ person: 'sm', speed: 1 },
|
||||
]
|
||||
const plan = scheduleWithCapacity(issues, [], workers)
|
||||
const byN = Object.fromEntries(plan.items.map((i) => [i.number, i]))
|
||||
expect(byN[1].worker).toBe('ak')
|
||||
expect(byN[2].worker).toBe('sm')
|
||||
// both start at 0 (different lanes) → parallel
|
||||
expect(byN[1].startDay).toBe(0)
|
||||
expect(byN[2].startDay).toBe(0)
|
||||
})
|
||||
|
||||
it('adds a lane for an assignee not in the config (mean speed)', () => {
|
||||
const plan = scheduleWithCapacity([issue(1, { assignee: 'newbie' })], [], [{ person: 'a', speed: 0.5 }])
|
||||
expect(plan.items[0].worker).toBe('newbie')
|
||||
expect(plan.items[0].durationDays).toBe(8) // mean speed 0.5 → 4/0.5
|
||||
})
|
||||
|
||||
it('respects dependencies across lanes (a blocker finishes before its dependent starts)', () => {
|
||||
const edges: DependencyEdge[] = [{ issue: 2, dependsOn: 1 }]
|
||||
const workers: Worker[] = [
|
||||
{ person: 'a', speed: 1 },
|
||||
{ person: 'b', speed: 1 },
|
||||
]
|
||||
const plan = scheduleWithCapacity([issue(1), issue(2)], edges, workers)
|
||||
const byN = Object.fromEntries(plan.items.map((i) => [i.number, i]))
|
||||
expect(byN[2].startDay).toBeGreaterThanOrEqual(byN[1].endDay) // #2 waits for #1 even on another lane
|
||||
})
|
||||
})
|
||||
49
packages/core/src/capacity/capacity-v0.ts
Normal file
49
packages/core/src/capacity/capacity-v0.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Capacity model (#8). A member's throughput is `focusFactor × allocation` =
|
||||
* ideal person-days of project work delivered per calendar working day. The
|
||||
* scheduler treats each member as a lane whose task durations are scaled by that
|
||||
* rate (a 0.5-capacity person takes twice as long on an est/2d task). Config
|
||||
* lives in the pm-state repo (`capacity/members.yaml/json`, D4); estimates are
|
||||
* in ideal person-days (pm-state.md).
|
||||
*/
|
||||
|
||||
export interface CapacityMember {
|
||||
/** gitea login. */
|
||||
person: string
|
||||
/** Productive fraction of a working day (0..1). */
|
||||
focusFactor: number
|
||||
/** Fraction of that allocated to this project (0..1). */
|
||||
allocation: number
|
||||
}
|
||||
|
||||
/** Ideal person-days delivered per calendar working day. */
|
||||
export function capacityPerWorkday(m: CapacityMember): number {
|
||||
return m.focusFactor * m.allocation
|
||||
}
|
||||
|
||||
function clamp01(n: unknown, fallback: number): number {
|
||||
return typeof n === 'number' && Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a raw capacity config (`{ members: [...] }`) into members. Unknown
|
||||
* shapes degrade to `[]` (→ the scheduler falls back to a single worker), never
|
||||
* throw. focusFactor/allocation clamp to [0,1]; a member without a person is dropped.
|
||||
*/
|
||||
export function parseCapacityConfig(raw: unknown): CapacityMember[] {
|
||||
const list = (raw as { members?: unknown })?.members
|
||||
if (!Array.isArray(list)) return []
|
||||
const out: CapacityMember[] = []
|
||||
for (const m of list) {
|
||||
const r = (m ?? {}) as Record<string, unknown>
|
||||
const person = typeof r.person === 'string' ? r.person.trim() : ''
|
||||
if (!person) continue
|
||||
const member: CapacityMember = {
|
||||
person,
|
||||
focusFactor: clamp01(r.focusFactor, 0.8),
|
||||
allocation: clamp01(r.allocation, 1),
|
||||
}
|
||||
if (capacityPerWorkday(member) > 0) out.push(member)
|
||||
}
|
||||
return out
|
||||
}
|
||||
66
packages/core/src/directives/record-directive-v0.test.ts
Normal file
66
packages/core/src/directives/record-directive-v0.test.ts
Normal file
@@ -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)
|
||||
})
|
||||
})
|
||||
106
packages/core/src/directives/record-directive-v0.ts
Normal file
106
packages/core/src/directives/record-directive-v0.ts
Normal file
@@ -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<string, unknown>
|
||||
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<string, unknown>
|
||||
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<string, unknown>) : 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`
|
||||
}
|
||||
@@ -120,4 +120,20 @@ describe('forecast', () => {
|
||||
expect(fitted.coldStart).toBe(false)
|
||||
expect(fitted.p50Day).toBeLessThan(priors.p50Day)
|
||||
})
|
||||
|
||||
it('capacity lanes parallelize the sim — the makespan shrinks with more workers', () => {
|
||||
const independent = [issue(1), issue(2), issue(3), issue(4)] // no deps → fully parallelizable
|
||||
const serial = forecast(independent, [], { trials: 2000, seed: 7 })
|
||||
const twoLanes = forecast(independent, [], {
|
||||
trials: 2000,
|
||||
seed: 7,
|
||||
workers: [
|
||||
{ person: 'a', speed: 1 },
|
||||
{ person: 'b', speed: 1 },
|
||||
],
|
||||
})
|
||||
// two equal lanes ≈ half the serial landing (independent work)
|
||||
expect(twoLanes.p80Day).toBeLessThan(serial.p80Day)
|
||||
expect(twoLanes.p80Day).toBeLessThan(serial.p80Day * 0.7)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
schedule,
|
||||
type SchedulableIssue,
|
||||
} from '../scheduler/scheduler-v0.js'
|
||||
import { type LaneInputs, layoutOnLanes, resolveLanes, type Worker } from '../scheduler/scheduler-capacity-v0.js'
|
||||
|
||||
export interface LognormalPrior {
|
||||
/** Median log-ratio: sampled median duration = estimate * e^mu. */
|
||||
@@ -76,6 +77,12 @@ export interface ForecastOptions {
|
||||
* the sim; otherwise the code-resident cold-start priors do.
|
||||
*/
|
||||
model?: DurationModel
|
||||
/**
|
||||
* Capacity lanes. When provided, each trial lays sampled durations across the
|
||||
* lanes (parallel) instead of a single serial worker — the makespan shrinks
|
||||
* toward the critical path. Empty/absent → single serial worker.
|
||||
*/
|
||||
workers?: Worker[]
|
||||
}
|
||||
|
||||
/** Resolve the lognormal params for an estimate, preferring a fitted model. */
|
||||
@@ -158,15 +165,32 @@ export function forecast(
|
||||
const priors = order.map((it) => durationParams(it.durationDays, options.model))
|
||||
const rng = mulberry32(seed)
|
||||
|
||||
// endByRank[k][t] = working day the (k+1)-th scheduled issue completes on trial t.
|
||||
// Capacity lanes, when configured — the per-trial layout goes parallel.
|
||||
const laneInputs: LaneInputs = {
|
||||
order: order.map((it) => it.number),
|
||||
blockedBy: new Map(order.map((it) => [it.number, it.blockedBy])),
|
||||
assignee: new Map(issues.map((i) => [i.number, i.assignee ?? null])),
|
||||
}
|
||||
const lanes =
|
||||
options.workers && options.workers.length ? resolveLanes(options.workers, [...laneInputs.assignee.values()]) : null
|
||||
|
||||
// endByRank[k][t] = working day the (k+1)-th issue *to finish* completes on trial t.
|
||||
const endByRank: number[][] = Array.from({ length: n }, () => new Array<number>(trials))
|
||||
for (let t = 0; t < trials; t++) {
|
||||
let cursor = 0
|
||||
for (let k = 0; k < n; k++) {
|
||||
const p = priors[k]
|
||||
const sampled = order[k].durationDays * Math.exp(p.mu + p.sigma * standardNormal(rng))
|
||||
cursor += sampled
|
||||
endByRank[k][t] = cursor
|
||||
const sampled = order.map((it, k) => it.durationDays * Math.exp(priors[k].mu + priors[k].sigma * standardNormal(rng)))
|
||||
if (lanes) {
|
||||
// parallel: lay the sampled durations across lanes, then sort finish days
|
||||
const byNumber = new Map(order.map((it, k) => [it.number, sampled[k]]))
|
||||
const { finishAt } = layoutOnLanes(laneInputs, lanes, (num) => byNumber.get(num)!)
|
||||
const finishes = order.map((it) => finishAt.get(it.number)!).sort((a, b) => a - b)
|
||||
for (let k = 0; k < n; k++) endByRank[k][t] = finishes[k]
|
||||
} else {
|
||||
// single serial worker: cumulative sum (already sorted ascending)
|
||||
let cursor = 0
|
||||
for (let k = 0; k < n; k++) {
|
||||
cursor += sampled[k]
|
||||
endByRank[k][t] = cursor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,6 +146,28 @@ 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)
|
||||
|
||||
@@ -105,6 +105,10 @@ export interface GiteaClient {
|
||||
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>
|
||||
/** 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<void>
|
||||
}
|
||||
|
||||
/** Map raw gitea issue JSON to the normalized domain shape. Pure. */
|
||||
@@ -232,5 +236,25 @@ export function createGiteaClient(config: GiteaConfig, fetchImpl: FetchLike): Gi
|
||||
})) 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 } : {}) },
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ export interface GiteaHttpResponse {
|
||||
status: number
|
||||
json(): Promise<unknown>
|
||||
text(): Promise<string>
|
||||
/** Present on the real fetch Response; used for SSE streaming (chat). */
|
||||
body?: ReadableStream<Uint8Array> | null
|
||||
}
|
||||
|
||||
export type FetchLike = (url: string, init?: GiteaRequestInit) => Promise<GiteaHttpResponse>
|
||||
|
||||
@@ -49,6 +49,12 @@ export type {
|
||||
SchedulePlan,
|
||||
} from './scheduler/scheduler-v0.js'
|
||||
|
||||
export { makespan, scheduleWithCapacity } from './scheduler/scheduler-capacity-v0.js'
|
||||
export type { Worker } from './scheduler/scheduler-capacity-v0.js'
|
||||
|
||||
export { capacityPerWorkday, parseCapacityConfig } from './capacity/capacity-v0.js'
|
||||
export type { CapacityMember } from './capacity/capacity-v0.js'
|
||||
|
||||
export {
|
||||
COLD_START_PRIORS,
|
||||
durationParams,
|
||||
@@ -80,13 +86,35 @@ export type {
|
||||
} from './calibration/calibration-v0.js'
|
||||
|
||||
export { createChatClient } from './agent/chat-client.js'
|
||||
export type { ChatClient, ChatMessage, CompletionResult, ModelConfig, ToolCall, ToolDecl } from './agent/chat-client.js'
|
||||
export type { ChatClient, ChatMessage, CompletionResult, ModelConfig, OnToken, ToolCall, ToolDecl } from './agent/chat-client.js'
|
||||
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'
|
||||
|
||||
119
packages/core/src/scheduler/scheduler-capacity-v0.ts
Normal file
119
packages/core/src/scheduler/scheduler-capacity-v0.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Capacity-aware scheduler (#8). Reuses the single-worker scheduler's topological
|
||||
* order + critical-path marking, then re-lays the work across lanes: an issue
|
||||
* runs on its assignee's lane (or the earliest-free lane when unassigned), its
|
||||
* duration scaled by that lane's speed (ideal person-days/workday). Makespan
|
||||
* shrinks toward the critical path as lanes are added. Deterministic; falls back
|
||||
* to the single serial worker when no capacity is configured. The lane layout is
|
||||
* factored so the Monte Carlo forecast reuses it per trial with sampled durations.
|
||||
*/
|
||||
|
||||
import {
|
||||
type DependencyEdge,
|
||||
schedule,
|
||||
type SchedulableIssue,
|
||||
type SchedulePlan,
|
||||
} from './scheduler-v0.js'
|
||||
|
||||
/** A scheduling lane: a person and their throughput (ideal person-days / workday). */
|
||||
export interface Worker {
|
||||
person: string
|
||||
speed: number
|
||||
}
|
||||
|
||||
/** The topological order + per-issue relations the layout needs (from the base plan). */
|
||||
export interface LaneInputs {
|
||||
order: number[]
|
||||
blockedBy: Map<number, number[]>
|
||||
assignee: Map<number, string | null>
|
||||
}
|
||||
|
||||
/** Ensure a lane exists for every assignee; unconfigured assignees get the mean speed. */
|
||||
export function resolveLanes(workers: Worker[], assignees: (string | null)[]): Worker[] {
|
||||
const lanes = [...workers]
|
||||
const known = new Set(lanes.map((w) => w.person))
|
||||
const meanSpeed = lanes.length ? lanes.reduce((s, w) => s + w.speed, 0) / lanes.length : 1
|
||||
for (const a of assignees) {
|
||||
if (a && !known.has(a)) {
|
||||
lanes.push({ person: a, speed: meanSpeed })
|
||||
known.add(a)
|
||||
}
|
||||
}
|
||||
return lanes
|
||||
}
|
||||
|
||||
function pickWorker(lanes: Worker[], freeAt: Map<string, number>, assignee: string | null | undefined): Worker {
|
||||
if (assignee) {
|
||||
const own = lanes.find((w) => w.person === assignee)
|
||||
if (own) return own
|
||||
}
|
||||
let best = lanes[0]
|
||||
for (const w of lanes) if (freeAt.get(w.person)! < freeAt.get(best.person)!) best = w
|
||||
return best
|
||||
}
|
||||
|
||||
/**
|
||||
* Lay a topologically-ordered set out across lanes. `duration(n)` supplies each
|
||||
* issue's duration for this layout (estimate, or a sampled value in a MC trial).
|
||||
* Returns each issue's finish day + the lane it ran on. Order guarantees a
|
||||
* dependency is always laid out before its dependents.
|
||||
*/
|
||||
export function layoutOnLanes(
|
||||
inputs: LaneInputs,
|
||||
lanes: Worker[],
|
||||
duration: (n: number) => number,
|
||||
): { finishAt: Map<number, number>; startAt: Map<number, number>; laneOf: Map<number, string> } {
|
||||
const freeAt = new Map(lanes.map((w) => [w.person, 0]))
|
||||
const finishAt = new Map<number, number>()
|
||||
const startAt = new Map<number, number>()
|
||||
const laneOf = new Map<number, string>()
|
||||
for (const n of inputs.order) {
|
||||
const worker = pickWorker(lanes, freeAt, inputs.assignee.get(n))
|
||||
const blockers = inputs.blockedBy.get(n) ?? []
|
||||
const depFinish = blockers.length ? Math.max(...blockers.map((d) => finishAt.get(d) ?? 0)) : 0
|
||||
const start = Math.max(freeAt.get(worker.person)!, depFinish)
|
||||
const end = start + duration(n) / worker.speed
|
||||
startAt.set(n, start)
|
||||
finishAt.set(n, end)
|
||||
laneOf.set(n, worker.person)
|
||||
freeAt.set(worker.person, end)
|
||||
}
|
||||
return { finishAt, startAt, laneOf }
|
||||
}
|
||||
|
||||
/**
|
||||
* Capacity-aware plan. An empty `workers` means no capacity is configured → the
|
||||
* single-worker plan verbatim.
|
||||
*/
|
||||
export function scheduleWithCapacity(
|
||||
issues: SchedulableIssue[],
|
||||
edges: DependencyEdge[],
|
||||
workers: Worker[],
|
||||
): SchedulePlan {
|
||||
if (workers.length === 0) return schedule(issues, edges)
|
||||
const base = schedule(issues, edges)
|
||||
if (base.cycle || base.items.length === 0) return base
|
||||
|
||||
const inputs: LaneInputs = {
|
||||
order: base.items.map((it) => it.number),
|
||||
blockedBy: new Map(base.items.map((it) => [it.number, it.blockedBy])),
|
||||
assignee: new Map(issues.map((i) => [i.number, i.assignee ?? null])),
|
||||
}
|
||||
const lanes = resolveLanes(workers, [...inputs.assignee.values()])
|
||||
const durationOf = new Map(base.items.map((it) => [it.number, it.durationDays]))
|
||||
const { finishAt, startAt, laneOf } = layoutOnLanes(inputs, lanes, (n) => durationOf.get(n)!)
|
||||
|
||||
const items = base.items.map((it) => ({
|
||||
...it,
|
||||
startDay: startAt.get(it.number)!,
|
||||
endDay: finishAt.get(it.number)!,
|
||||
durationDays: finishAt.get(it.number)! - startAt.get(it.number)!,
|
||||
worker: laneOf.get(it.number),
|
||||
}))
|
||||
return { items, cycle: null }
|
||||
}
|
||||
|
||||
/** Makespan (last finish) of a plan — the project's landing day. */
|
||||
export function makespan(plan: SchedulePlan): number {
|
||||
return plan.items.reduce((m, it) => Math.max(m, it.endDay), 0)
|
||||
}
|
||||
@@ -21,6 +21,8 @@ export interface SchedulableIssue {
|
||||
estimateDays: number | null
|
||||
/** 1 (most urgent) … 4; null when unset. */
|
||||
priority: number | null
|
||||
/** gitea assignee login, for capacity-aware lane routing; optional. */
|
||||
assignee?: string | null
|
||||
}
|
||||
|
||||
export interface DependencyEdge {
|
||||
@@ -45,6 +47,8 @@ export interface ScheduledItem {
|
||||
/** On a longest-duration dependency chain. */
|
||||
critical: boolean
|
||||
rationale: string
|
||||
/** Lane it's scheduled on, when capacity-aware; absent for the single-worker plan. */
|
||||
worker?: string
|
||||
}
|
||||
|
||||
export interface SchedulePlan {
|
||||
|
||||
Reference in New Issue
Block a user