Compare commits

12 Commits

Author SHA1 Message Date
Croissant Le Doux
6198f21d9a feat: the write path — apply estimate/priority changes to gitea (P4-3 apply_changes)
The first write path. Read, forecast, and calibration were all real; now you can
*manage* CommiTea from CommiTea. Estimates/priority are exclusive label axes, so
a change is a label swap — proposed, approved, then written. Nothing is assumed.

core (@commitea/core):
- planIssueChange(current, change): pure diff planner — swaps the est/*|p/* axis,
  clears on null, dedups a doubled axis; returns the resulting label set + a
  before/after diff + noop flag. describeChange() renders "est/2d → est/5d".
- request() seam extended for writes (method/body, JSON, 204). client gains
  listLabels() (name→id) and setIssueLabels() (PUT /issues/{n}/labels).

app:
- main bridge gitea:applyChange — resolves plan.labels → ids (cached, refetch on
  miss), PUTs, returns the plan + fresh issue. Token never leaves main.
- preload + global.d.ts expose applyChange; useBacklog returns a refetch so a
  write re-reconciles the board + forecast.
- Issue screen: an Adjust button (shown only when configured) opens a
  propose-approve Dialog — estimate/priority pickers, live "est/3d → est/8d"
  consequence, Apply/Cancel. AppShell wires it, reflects new labels on the open
  issue immediately, and refetches.

Verified: 83 core tests green (7 apply-changes + 2 client-write new), desktop
typecheck clean, 14 fixture e2e green. Live spec exercises propose + CANCEL (no
mutation); the real PUT was verified once manually (change #2 est/3d→est/8d→200,
reverted clean). Icon: pencil (no sliders-horizontal in the set).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 20:14:47 -04:00
a901b7f855 Merge pull request 'Calibration → forecast flips off cold-start (#1); re-lands Monte Carlo (#10) + lifecycle (#5)' (#40) from p2/calibration into main
Reviewed-on: #40
2026-07-08 23:54:48 +00:00
Croissant Le Doux
7e26de1b6c feat: calibration from closed-issue actuals → forecast flips off cold-start (#1)
Close the D3 loop. The forecast now learns from the team's own estimate-vs-actual
history (the working time #5 infers from git events) instead of guessing forever.

core (@commitea/core/calibration-v0):
- fitCalibration(samples): lognormal fit on log(actual/estimate) — global +
  per-bucket (once a bucket clears the floor) + per-person bias. coldStart until
  n >= 20 closed-with-estimate issues.
- calibrationSamples(): pull those samples from the closed backlog via lifecycle
  inference (estimate label vs inferred actualWorkingDays).
- toDurationModel(): project the fit to the params forecast consumes.
- forecast() gains options.model: when past cold-start, fitted params drive the
  sim (per bucket, global fallback); otherwise the code priors do. Forecast.coldStart
  now reflects the model. nearestBucket extracted + exported.

app:
- AppShell fits calibration once from the reconciled backlog, feeds the model into
  forecastBacklog (cone), and drives the Calibration screen + Runway header.
- Focus cone footer, Runway note, and Calibration screen now say cold-start (N/20)
  vs calibrated (on N closed) from real data; Calibration scatter / bucket bias /
  per-person all fitted, degrading honestly on a thin dataset.

Known refinement: same-day closes yield 0 working-day actuals (day-granular) and
are excluded, so a fast-moving repo can sit at n=0 — honest, but a fractional
(hours-based) actual would let those count. Per-person uses gitea login, not
display name, until the person map lands.

Note: also re-lands #10 (Monte Carlo) and #5 (lifecycle) which merged into their
stacked base branches but never propagated to main (stacked-merge trap); this
branch is cut from main and carries all three so main is whole again.

Verified: 74 core tests green (9 calibration + 2 forecast-switch added), desktop
typecheck clean, 14 fixture e2e green, live spec asserts the real cold-start
calibration surface (Runway note + screen badge fitted from actuals).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 19:51:50 -04:00
Croissant Le Doux
9cedd8646e feat: lifecycle inference from the issue timeline (#5)
Fill the board's Steeping / In-review columns (and the calibration actuals)
from real gitea timeline events, replacing the three-column-only v0.

core (@commitea/core):
- inferLifecycle(issue, events, asOf): five-column inference — closed → done;
  open PR ref → review; commit ref → steeping; any triage signal → triage;
  else diagnosis. Earliest event of each kind fixes the stage timestamp.
- Derives actualWorkingDays (work-start → close) — the estimate-vs-actual the
  calibration fit (D3) learns from — and steepingDays (first commit → now) for
  the board age badge.
- workingDaysBetween(): whole Mon–Fri days in [start, end), day-granular.
- normalizeTimeline() + client.getIssueTimeline(): map gitea's raw timeline
  (label/milestone → triage, commit_ref → commit, pull_ref → pull, close,
  reopen), drop the rest. Paginated.

app:
- reconcile now fetches every issue's timeline and returns it keyed by number;
  threaded through the bridge → useBacklog → board/focus.
- issuesToBoardColumns + scheduleFocus run inferLifecycle: real Steeping/In-review
  columns, steeping-age `days` badge, focus-card steeping badge.

Known refinement: gitea's pull_ref fires on any PR mention, so an issue merely
referenced in a PR body can read as In-review; distinguishing closing refs from
mentions needs the PR link's state (later). Re-opening multi-segment actuals
also deferred.

Verified: 63 core tests green (15 lifecycle, incl. workingDaysBetween + the five
transitions), desktop typecheck clean, 14 fixture e2e green, live spec asserts
the board's Done column is populated from real events.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 19:42:46 -04:00
Croissant Le Doux
be70c8607d feat: Monte Carlo forecast → real burn-up cone (#10)
Replace the demo cone on Morning service with a real, seeded Monte Carlo
forecast over the open backlog. The LLM never does this — it's plain,
reproducible code (evidence-based scheduling).

core (@commitea/core/forecast-v0):
- Code-resident lognormal cold-start priors per estimate bucket (D3):
  sampled actual = estimate * exp(N(mu, sigma)), mu > 0 (actuals run long),
  sigma shrinks as tickets grow. Replaced by the team's empirical fit at
  n >= 20 (#5 supplies the actuals).
- forecast(): seeded mulberry32 + Box-Muller over the scheduler's
  deterministic order (order is fixed from estimates/deps; only durations
  vary, so the cone stretches, never reorders). Returns p50/p80/p95 landing
  + a per-issue burn-up curve (p10/p50/p90). 12 unit tests; reproducible.

renderer:
- lib/dates.ts: working-day -> calendar mapper (skips weekends) + buildBurnUpData.
- BurnUpCone gains a data-driven twin; falls back byte-identical to the
  fixture cone when no forecast (demo mode unchanged).
- Focus card shows the real "80% of the open backlog lands by <range>",
  real scope count, and names the cold-start priors.

v0 scope (each a later slice): single serial worker (capacity is #8);
cold-start priors only (empirical fit is #5); no historical actual polyline
(needs lifecycle events, #5). Header chrome (reconcile time, ahead/behind
badge) stays fixture until milestone due dates land.

Verified: 51 core tests green, desktop typecheck clean, 14 fixture e2e green,
live spec asserts the real cone renders (25 open issues, "lands by Nov 11-27").

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 19:42:46 -04:00
ca45f1e97c Merge pull request 'P2: deterministic scheduler → real Now/Next/Later' (#37) from p2/scheduler-focus into main
Reviewed-on: #37
2026-07-08 23:22:41 +00:00
e6be8cc64b Merge branch 'main' into p2/scheduler-focus 2026-07-08 23:22:35 +00:00
Croissant Le Doux
68a93de098 feat: deterministic scheduler → real Now/Next/Later (P2 thin slice)
CommiTea now recommends its own next unit of work from the live backlog.

- @commitea/core: `schedule()` — dependency topo-sort with priority +
  estimate tie-breaks, single serial capacity, cycle detection, and
  critical-path marking; `selectFocus()` takes the top three. Pure,
  deterministic; the LLM does none of this. +11 tests (39 in core).
  Client gains `getIssueDependencies`.
- main: reconcile also fetches native issue dependencies for the open
  scope and returns edges.
- renderer: `scheduleFocus()` maps real issues+deps→Now/Next/Later;
  Focus renders scheduler output (fixture fallback when unconfigured).

v0 scope (each a later slice): single serial worker (per-person
capacity #8), point durations (Monte Carlo cone #10), estimate-only
(calibration #5). Verified: 14 e2e green (fixtures) + gated live spec —
the board shows the real 25 open + 9 closed, and Focus picks #2
ChangeSource (critical path) as Now. Screenshots confirmed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 17:12:22 -04:00
ecf1bb16e8 Merge pull request 'P1: read the real gitea backlog into the app' (#36) from p1/backlog-read into main
Reviewed-on: #36
2026-07-08 21:00:33 +00:00
Croissant Le Doux
94199639f2 feat: read the real gitea backlog into the app (P1 thin slice)
The app now displays its own live backlog instead of fixtures. First
end of the sync loop — the tap-root (#1) grows list reads and a read
path through the Electron main process.

- @commitea/core: client gains `listIssues` (paginated, PRs excluded)
  and `listMilestones`; a `lifecycle-v0` mapper (closed→done,
  labelled/milestoned→triage, bare→diagnosis — steeping/review await
  event inference in P1-5). +10 unit tests.
- main: gitea bridge over IPC (token stays in main, never the renderer);
  config from env / .env.local; gated off under COMMITEA_E2E so the
  committed e2e stays on fixtures. Preload exposes the typed bridge.
- renderer: useBacklog() reconciles once on mount; issuesToBoardColumns
  shapes real issues into The pot. Board takes optional real columns +
  a loading state, falling back to demo fixtures when unconfigured.

Verified: 14 e2e green (fixture mode) + a gated live spec that launches
against the real repo — the board renders the actual 25 open + 9 closed
issues (screenshot). SQLite mirror + reconcile-on-a-timer + lifecycle
event inference are the next slices (#2/#3/#5).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:57:57 -04:00
103b6cc98d Merge pull request 'CommiTea foundation + P3 UI: gitea client, e2e harness, all product screens' (#35) from p1/gitea-read-client into main
Reviewed-on: #35
2026-07-08 20:42:13 +00:00
Croissant Le Doux
0fc53d03be feat(desktop): Directives, Settings, Onboarding — P3 complete (#21)
The last three P3 screens, retiring every placeholder:
- DirectivesScreen — jade consequence diff (propose-approve: Make it so
  / Amend / Withdraw, resolving moves it into the ledger) + append-only
  ledger (seq, who/when/why, verbatim quote, status badge).
- SettingsScreen — gitea connection + managed repos, sync switches,
  model router, read-only label schema, rituals, appearance radios
  (wired to the shared theme), single danger action.
- OnboardingScreen — full-window first run: welcome → connect (test
  gate) → repo pick → propose-approve bootstrap; onDone routes into the
  app. Shell early-returns it (no rail/chat), matching the design.

Shell routes directives/settings and the firstrun full-window flow.
DIRECTIVES fixture added. typecheck + 14 e2e green (incl. directive
resolve, appearance↔theme sync, onboarding test gate); all three
screenshot-verified.

Closes P3-8. P3 (UI views) complete — all 14 screens live on fixtures.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 16:22:59 -04:00
34 changed files with 2911 additions and 46 deletions

View File

@@ -0,0 +1,65 @@
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 only (GITEA_LIVE=1). Launches WITHOUT COMMITEA_E2E so the main process
// reconciles the real repo via .env.local, and asserts real data renders.
test.describe('live backlog', () => {
test('The pot + Focus render real gitea data', async () => {
test.skip(!process.env.GITEA_LIVE, 'GITEA_LIVE not set — opt-in live test')
const app = await electron.launch({ args: [MAIN], env: { ...process.env } })
const win = await app.firstWindow()
await win.waitForLoadState('domcontentloaded')
const rail = win.getByRole('navigation', { name: 'Primary' })
// The pot — waiting here also lets the reconcile (issues + deps + timelines) complete
await rail.getByRole('button', { name: 'The pot' }).click()
await expect(win.getByText('Gitea read client behind an injected fetch')).toBeVisible({ timeout: 20000 })
// Lifecycle inference (#5): columns come from the real event stream — merged
// work lands in Done, so that column is non-empty (proves timelines drove it,
// not the three-column fallback which would still show closed issues in Done).
await expect(win.getByText('Done', { exact: true })).toBeVisible()
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-board.png'), fullPage: true, animations: 'disabled' })
// Back to Focus — the deterministic scheduler's real Now/Next/Later. These
// rationale phrases are emitted only by the scheduler, never by the demo fixture.
await rail.getByRole('button', { name: 'Morning service' }).click()
await expect(win.getByText(/on the critical path|unblocks #|waits on #|· ready/).first()).toBeVisible()
// Real Monte Carlo cone — this headline is emitted only for real forecasts.
await expect(win.getByText(/80% of the open backlog lands by/)).toBeVisible()
await expect(win.getByText(/Cold-start priors/)).toBeVisible()
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-focus.png'), fullPage: true, animations: 'disabled' })
// Runway → calibration surface, fitted from real closed-issue actuals (#1).
// With <20 estimated closes the repo is honestly cold-start; the note proves
// the fit ran on real data, not the fixture's "calibrated on 27".
await rail.getByRole('button', { name: 'Runway' }).click()
await expect(
win.getByText(/cold-start priors · \d+\/20 closed issues estimated|calibrated on \d+ closed/),
).toBeVisible()
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' })
// Write path (apply_changes): open the top scheduled issue, propose an
// estimate change, and confirm the propose-approve diff renders — then CANCEL
// so the live run never mutates the real repo (the PUT is unit-tested; a
// one-off change→revert verified it against gitea manually).
await rail.getByRole('button', { name: 'Morning service' }).click()
await win.getByRole('main').getByRole('link').first().click()
await expect(win.getByText(/· stephen\/commitea/)).toBeVisible()
await win.getByRole('button', { name: 'Adjust' }).click()
await expect(win.getByText('Adjust estimate & priority')).toBeVisible()
await win.getByRole('combobox').first().selectOption('est/8d')
await expect(win.getByText('Proposed label change')).toBeVisible()
await expect(win.getByText(/est\/8d/).last()).toBeVisible()
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-apply-change.png'), fullPage: true, animations: 'disabled' })
await win.getByRole('button', { name: 'Cancel' }).click() // no mutation
await app.close()
})
})

View File

@@ -82,6 +82,42 @@ test('Capture: braindump advances to the interview', async ({ app, window }) =>
await expect(window.getByText(/Interview · 1 of 3/)).toBeVisible() await expect(window.getByText(/Interview · 1 of 3/)).toBeVisible()
}) })
test('Directives: consequence diff + append-only ledger', async ({ app, window }) => {
await app.nav('Directives').click()
await expect(window.getByRole('heading', { name: 'Directives' })).toBeVisible()
await expect(window.getByText('Consequence diff')).toBeVisible()
await expect(window.getByText(/append-only · JSONL in pm-state/)).toBeVisible()
await app.screenshot('directives')
// resolving the pending directive moves it into the ledger
await window.getByRole('button', { name: 'Make it so' }).click()
await expect(window.getByText('Consequence diff')).toBeHidden()
await expect(window.getByText(/Nothing awaits your word/)).toBeVisible()
})
test('Settings: connection, schema, and appearance sync with theme', async ({ app, window }) => {
await app.nav('Settings').click()
await expect(window.getByRole('heading', { name: 'Settings' })).toBeVisible()
await expect(window.getByText('Managed repos')).toBeVisible()
await app.screenshot('settings')
// the Evening (dark) radio drives the shared theme
await window.getByText('Evening (dark)').click()
await expect(window.locator('html')).toHaveAttribute('data-theme', 'dark')
})
test('Onboarding: full-window first-run flow with test gate', async ({ app, window }) => {
await app.nav('First run').click()
await expect(window.getByRole('heading', { name: 'Good morning.' })).toBeVisible()
// full-window: no rail wordmark link, brand only
await app.screenshot('onboarding')
await window.getByRole('button', { name: 'Begin' }).click()
await expect(window.getByRole('heading', { name: 'Your Gitea' })).toBeVisible()
// Continue is gated until the connection test passes
await expect(window.getByRole('button', { name: 'Continue' })).toBeDisabled()
await window.getByRole('button', { name: 'Test connection' }).click()
await expect(window.getByText(/connected · 3 repos visible/)).toBeVisible()
await expect(window.getByRole('button', { name: 'Continue' })).toBeEnabled()
})
test('issue drill-in from a Focus card and back-stack of one', async ({ app, window }) => { test('issue drill-in from a Focus card and back-stack of one', async ({ app, window }) => {
await window.getByRole('link', { name: 'Fix lifecycle inference on merge events' }).click() await window.getByRole('link', { name: 'Fix lifecycle inference on merge events' }).click()
await expect(window.getByText('#87 · stephen/commitea')).toBeVisible() await expect(window.getByText('#87 · stephen/commitea')).toBeVisible()

View File

@@ -0,0 +1,108 @@
/**
* Main-process gitea bridge. All gitea traffic runs here — the token never
* reaches the renderer (which is CSP-locked to 'self' anyway). The renderer
* calls these over IPC (see preload). Config for the dogfood slice comes from
* the environment or the repo's .env.local; Settings/Onboarding wire it up
* properly later.
*/
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import {
createGiteaClient,
type GiteaConfig,
type GiteaLabel,
type IssueChange,
type LifecycleEvent,
planIssueChange,
} from '@commitea/core'
import { ipcMain } from 'electron'
/** Walk up from cwd looking for a .env.local with a GITEA_TOKEN (dev convenience). */
function loadEnvLocalToken(): string | undefined {
let dir = process.cwd()
for (let i = 0; i < 6; i++) {
try {
const txt = readFileSync(join(dir, '.env.local'), 'utf8')
const m = /^GITEA_TOKEN\s*=\s*(.+?)\s*$/m.exec(txt)
if (m) return m[1].trim()
} catch {
// not in this dir — keep walking up
}
const parent = dirname(dir)
if (parent === dir) break
dir = parent
}
return undefined
}
function resolveConfig(): GiteaConfig | null {
// E2E runs against fixtures — never hit the network from the test harness.
if (process.env.COMMITEA_E2E === '1') return null
const token = process.env.GITEA_TOKEN ?? loadEnvLocalToken()
if (!token) return null
return {
baseUrl: process.env.GITEA_BASE_URL ?? 'https://gitea.stephenmann.io',
token,
owner: process.env.GITEA_OWNER ?? 'christian',
repo: process.env.GITEA_REPO ?? 'commitea',
}
}
export function registerGiteaIpc(): void {
const config = resolveConfig()
const client = config ? createGiteaClient(config, fetch) : null
const repo = config ? `${config.owner}/${config.repo}` : null
ipcMain.handle('gitea:status', () => ({ configured: !!config, repo }))
ipcMain.handle('gitea:reconcile', async () => {
if (!client) return { configured: false, issues: [], milestones: [], deps: [], timelines: {} }
const [issues, milestones] = await Promise.all([client.listIssues(), client.listMilestones()])
// dependency edges among the open scope (the scheduler only plans what's left)
const open = issues.filter((i) => i.state === 'open')
const perIssue = await Promise.all(
open.map(async (i) => ({ issue: i.number, dependsOn: await client.getIssueDependencies(i.number) })),
)
const deps = perIssue.flatMap(({ issue, dependsOn }) => dependsOn.map((d) => ({ issue, dependsOn: d })))
// lifecycle timelines for every issue (open → columns/badges, closed → calibration actuals)
const timelineEntries = await Promise.all(
issues.map(async (i) => [i.number, await client.getIssueTimeline(i.number)] as const),
)
const timelines: Record<number, LifecycleEvent[]> = Object.fromEntries(timelineEntries)
return { configured: true, issues, milestones, deps, timelines }
})
ipcMain.handle('gitea:getIssue', async (_event, index: number) => {
if (!client) return null
return client.getIssue(index)
})
// Cached label list for name→id resolution; refreshed on demand if a name misses.
let labelCache: GiteaLabel[] | null = null
async function resolveLabelIds(names: string[]): Promise<number[]> {
if (!client) return []
const lookup = () => new Map(labelCache!.map((l) => [l.name, l.id]))
if (!labelCache) labelCache = await client.listLabels()
let byName = lookup()
if (names.some((n) => !byName.has(n))) {
labelCache = await client.listLabels() // a name we don't know — refetch once
byName = lookup()
}
return names.map((n) => byName.get(n)).filter((id): id is number => id != null)
}
// The write path (apply_changes). Additive label swaps, applied only after the
// renderer's propose-approve. Returns the plan + the freshly-read issue.
ipcMain.handle('gitea:applyChange', async (_event, change: IssueChange) => {
if (!client) return { ok: false as const, reason: 'unconfigured' as const }
const current = await client.getIssue(change.issue)
const plan = planIssueChange(current.labels, change)
if (plan.noop) return { ok: true as const, plan, issue: current }
const ids = await resolveLabelIds(plan.labels)
await client.setIssueLabels(change.issue, ids)
const issue = await client.getIssue(change.issue)
return { ok: true as const, plan, issue }
})
}

View File

@@ -2,6 +2,8 @@ import { join } from 'node:path'
import { BrowserWindow, app, shell } from 'electron' import { BrowserWindow, app, shell } from 'electron'
import { registerGiteaIpc } from './gitea.js'
function createWindow(): void { function createWindow(): void {
const win = new BrowserWindow({ const win = new BrowserWindow({
width: 1440, width: 1440,
@@ -32,6 +34,7 @@ function createWindow(): void {
} }
void app.whenReady().then(() => { void app.whenReady().then(() => {
registerGiteaIpc()
createWindow() createWindow()
app.on('activate', () => { app.on('activate', () => {

View File

@@ -1,7 +1,17 @@
import { contextBridge } from 'electron' import { contextBridge, ipcRenderer } from 'electron'
const api = { const api = {
platform: process.platform, platform: process.platform,
gitea: {
/** Whether the main process has a gitea token + target repo configured. */
status: () => ipcRenderer.invoke('gitea:status'),
/** Full read of the managed repo — every issue + milestone. */
reconcile: () => ipcRenderer.invoke('gitea:reconcile'),
/** One issue by index, normalized (or null if unconfigured). */
getIssue: (index: number) => ipcRenderer.invoke('gitea:getIssue', index),
/** Apply an estimate/priority change (the write path); resolves to the plan + fresh issue. */
applyChange: (change: unknown) => ipcRenderer.invoke('gitea:applyChange', change),
},
} }
export type CommiteaApi = typeof api export type CommiteaApi = typeof api

View File

@@ -1,15 +1,21 @@
import type { BurnUpData } from '../../lib/dates.js'
/** /**
* Charts — geometry, not decoration. Ported from the handoff's Chart.js. The * Charts — geometry, not decoration. Ported from the handoff's Chart.js. When a
* fixed sample paths here stand in for scheduler/Monte Carlo output (P2); the * `data` prop is supplied the cone is drawn from real Monte Carlo output
* shapes (cone from today, 80% band, actual polyline, today rule) are final. * (#10); without it, the fixed sample paths below stand in (demo mode). The
* shapes (cone from today, 80% band, today rule) are final.
*/ */
export interface BurnUpConeProps { export interface BurnUpConeProps {
width?: number width?: number
height?: number height?: number
/** Real forecast geometry. When present it replaces the demo sample paths. */
data?: BurnUpData
} }
export function BurnUpCone({ width = 640, height = 220 }: BurnUpConeProps) { export function BurnUpCone({ width = 640, height = 220, data }: BurnUpConeProps) {
if (data) return <BurnUpConeReal width={width} height={height} data={data} />
const pad = { l: 34, r: 96, t: 16, b: 26 } const pad = { l: 34, r: 96, t: 16, b: 26 }
const W = width - pad.l - pad.r const W = width - pad.l - pad.r
const H = height - pad.t - pad.b const H = height - pad.t - pad.b
@@ -89,6 +95,62 @@ export function BurnUpCone({ width = 640, height = 220 }: BurnUpConeProps) {
) )
} }
/** Data-driven twin of BurnUpCone — same visual grammar, real forecast geometry. */
function BurnUpConeReal({ width, height, data }: { width: number; height: number; data: BurnUpData }) {
const pad = { l: 34, r: 96, t: 16, b: 26 }
const W = width - pad.l - pad.r
const H = height - pad.t - pad.b
const x = (day: number) => pad.l + (day / data.horizonDays) * W
const y = (frac: number) => pad.t + (1 - frac) * H
const hi = data.band.map((p) => `${x(p.hiDay)},${y(p.fraction)}`).join(' ')
const lo = data.band.map((p) => `${x(p.loDay)},${y(p.fraction)}`).join(' ')
const mid = data.band.map((p) => `${x(p.midDay)},${y(p.fraction)}`).join(' ')
const cone = [
...data.band.map((p) => `${x(p.hiDay)},${y(p.fraction)}`),
...[...data.band].reverse().map((p) => `${x(p.loDay)},${y(p.fraction)}`),
].join(' ')
return (
<svg width="100%" viewBox={`0 0 ${width} ${height}`} style={{ display: 'block' }}>
{[0, 0.25, 0.5, 0.75, 1].map((f) => (
<line key={f} x1={pad.l} x2={width - pad.r} y1={y(f)} y2={y(f)} stroke="var(--line-1)" strokeWidth="1" />
))}
{/* scope */}
<line x1={pad.l} x2={width - pad.r} y1={y(1)} y2={y(1)} stroke="var(--line-2)" strokeWidth="1.5" />
<text x={pad.l} y={y(1) - 6} style={{ font: '400 10.5px var(--font-mono)', fill: 'var(--ink-3)' }}>
scope · {data.scope} {data.scope === 1 ? 'issue' : 'issues'}
</text>
{/* cone */}
<polygon points={cone} fill="var(--cone-fill)" />
<polyline points={hi} fill="none" stroke="var(--cone-line)" strokeWidth="1.2" strokeDasharray="3 3" />
<polyline points={lo} fill="none" stroke="var(--cone-line)" strokeWidth="1.2" strokeDasharray="3 3" />
<polyline points={mid} fill="none" stroke="var(--cone-line)" strokeWidth="1.4" />
{/* origin = today, 0% of remaining scope */}
<circle cx={x(0)} cy={y(0)} r="3.5" fill="var(--cone-actual)" />
{/* today rule */}
<line x1={x(0)} x2={x(0)} y1={pad.t} y2={height - pad.b} stroke="var(--jade)" strokeWidth="1" />
<text x={x(0) + 5} y={pad.t + 10} style={{ font: '400 10.5px var(--font-mono)', fill: 'var(--jade-7)' }}>
today
</text>
{/* 80% band label */}
<text x={width - pad.r + 10} y={y(0.95)} style={{ font: '500 11.5px var(--font-mono)', fill: 'var(--ink-1)' }}>
80%
</text>
<text x={width - pad.r + 10} y={y(0.95) + 14} style={{ font: '400 11px var(--font-mono)', fill: 'var(--ink-2)' }}>
{data.rangeLabel}
</text>
{/* x labels */}
<text x={pad.l} y={height - 8} style={{ font: '400 10.5px var(--font-mono)', fill: 'var(--ink-3)' }}>
{data.startLabel}
</text>
<text x={width - pad.r - 34} y={height - 8} style={{ font: '400 10.5px var(--font-mono)', fill: 'var(--ink-3)' }}>
{data.endLabel}
</text>
</svg>
)
}
export interface RunwayBarMilestone { export interface RunwayBarMilestone {
tone: 'ok' | 'warn' tone: 'ok' | 'warn'
pos: number pos: number

View File

@@ -1,19 +1,29 @@
import React from 'react' import React from 'react'
import { COLUMNS, type BoardIssue, type IssueRef } from '../../data/fixtures.js' import { COLUMNS, type BoardColumn, type BoardIssue, type IssueRef } from '../../data/fixtures.js'
import { Card, Tag, Badge, Tabs, IconButton, Input, Icon } from '../ui/index.js' import { Card, Tag, Badge, Tabs, IconButton, Input, Icon } from '../ui/index.js'
import { EmptyState } from '../shell/states.js' import { EmptyState } from '../shell/states.js'
import { GanttView } from './gantt-view.js' import { GanttView } from './gantt-view.js'
import { DepsGraph } from './deps-graph.js' import { DepsGraph } from './deps-graph.js'
// Board — kanban over inferred lifecycle, with Gantt/Dependencies stubs // Board — kanban over inferred lifecycle, with Gantt/Dependencies stubs.
export function BoardScreen({ onOpenIssue }: { onOpenIssue: (issue: IssueRef) => void }) { // `columns` defaults to demo fixtures; the shell passes real reconciled data
// when gitea is configured. `loading` covers the first reconcile.
export function BoardScreen({
onOpenIssue,
columns = COLUMNS,
loading = false,
}: {
onOpenIssue: (issue: IssueRef) => void
columns?: BoardColumn[]
loading?: boolean
}) {
const [tab, setTab] = React.useState('board'); const [tab, setTab] = React.useState('board');
const [query, setQuery] = React.useState(''); const [query, setQuery] = React.useState('');
const q = query.trim().toLowerCase(); const q = query.trim().toLowerCase();
const filtered = COLUMNS.map((c) => ({ ...c, issues: q ? c.issues.filter((i) => (i.title + ' #' + i.id).toLowerCase().includes(q)) : c.issues })); const filtered = columns.map((c) => ({ ...c, issues: q ? c.issues.filter((i) => (i.title + ' #' + i.id).toLowerCase().includes(q)) : c.issues }));
const anyMatch = filtered.some((c) => c.issues.length > 0); const anyMatch = filtered.some((c) => c.issues.length > 0);
const openCount = COLUMNS.reduce((n, c) => n + (c.id === 'done' ? 0 : c.issues.length), 0); const openCount = columns.reduce((n, c) => n + (c.id === 'done' ? 0 : c.issues.length), 0);
const IssueCard = ({ issue }: { issue: BoardIssue }) => ( const IssueCard = ({ issue }: { issue: BoardIssue }) => (
<div <div
@@ -56,7 +66,12 @@ export function BoardScreen({ onOpenIssue }: { onOpenIssue: (issue: IssueRef) =>
active={tab} onChange={setTab} active={tab} onChange={setTab}
/> />
{tab === 'board' ? ( {tab === 'board' ? (
anyMatch ? ( loading ? (
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--ink-3)' }}>
<Icon name="loader-circle" size={16} />
<span style={{ font: 'var(--text-small)' }}>Reconciling with gitea</span>
</div>
) : anyMatch ? (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, alignItems: 'start', flex: 1, minHeight: 0, overflow: 'auto' }}> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12, alignItems: 'start', flex: 1, minHeight: 0, overflow: 'auto' }}>
{filtered.map((col) => ( {filtered.map((col) => (
<div key={col.id} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> <div key={col.id} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
@@ -71,7 +86,7 @@ export function BoardScreen({ onOpenIssue }: { onOpenIssue: (issue: IssueRef) =>
) : ( ) : (
<div style={{ flex: 1, border: '1px dashed var(--line-2)', borderRadius: 'var(--radius-3)' }}> <div style={{ flex: 1, border: '1px dashed var(--line-2)', borderRadius: 'var(--radius-3)' }}>
<EmptyState icon="search" title="Nothing by that name" <EmptyState icon="search" title="Nothing by that name"
line={`The pot holds ${COLUMNS.reduce((n, c) => n + c.issues.length, 0)} issues; none of them answer to “${query.trim()}”.`} /> line={`The pot holds ${columns.reduce((n, c) => n + c.issues.length, 0)} issues; none of them answer to “${query.trim()}”.`} />
</div> </div>
) )
) : tab === 'deps' ? ( ) : tab === 'deps' ? (

View File

@@ -1,11 +1,12 @@
import React from 'react' import React from 'react'
import { CALIBRATION } from '../../data/fixtures.js' import { CALIBRATION, type CalibrationData } from '../../data/fixtures.js'
import { Badge, Card, Icon } from '../ui/index.js' import { Badge, Card, Icon } from '../ui/index.js'
// Calibration report — estimate-vs-actual evidence behind the cones // Calibration report — estimate-vs-actual evidence behind the cones.
export function CalibrationScreen({ onBack }: { onBack: () => void }) { // `data` (real fit from closed-issue actuals) overrides the demo fixture.
const c = CALIBRATION export function CalibrationScreen({ onBack, data }: { onBack: () => void; data?: CalibrationData }) {
const c = data ?? CALIBRATION
// scatter chart geometry // scatter chart geometry
const W = 420, const W = 420,
@@ -68,7 +69,11 @@ export function CalibrationScreen({ onBack }: { onBack: () => void }) {
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Calibration</h1> <h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Calibration</h1>
<p style={{ font: 'var(--text-data)', color: 'var(--ink-3)', margin: '6px 0 0', whiteSpace: 'nowrap' }}>{c.n} closed issues with estimates · evidence, not opinion</p> <p style={{ font: 'var(--text-data)', color: 'var(--ink-3)', margin: '6px 0 0', whiteSpace: 'nowrap' }}>{c.n} closed issues with estimates · evidence, not opinion</p>
</div> </div>
<Badge tone="ok" dot>curve active · n 20</Badge> {c.active ? (
<Badge tone="ok" dot>curve active · n 20</Badge>
) : (
<Badge tone="warn" dot>cold-start · {c.n}/20</Badge>
)}
</header> </header>
</div> </div>
@@ -170,7 +175,9 @@ export function CalibrationScreen({ onBack }: { onBack: () => void }) {
<span style={{ font: '500 12.5px var(--font-mono)', color: 'var(--ink-1)', whiteSpace: 'nowrap' }}>{c.effect.banded}</span> <span style={{ font: '500 12.5px var(--font-mono)', color: 'var(--ink-1)', whiteSpace: 'nowrap' }}>{c.effect.banded}</span>
</div> </div>
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 0' }}> <p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 0' }}>
You are not bad at estimating; you are optimistic in a very stable way. Stable, I can work with. {c.active
? 'You are not bad at estimating; you are optimistic in a very stable way. Stable, I can work with.'
: 'Not enough closed history yet — Im forecasting from cold-start priors and widening the cone to stay honest. The curve takes over at 20.'}
</p> </p>
</Card> </Card>
</div> </div>

View File

@@ -0,0 +1,104 @@
import React from 'react'
import { DIRECTIVES, type DirectivePending, type DirectiveEntry } from '../../data/fixtures.js'
import { Card, Button, Badge, Icon } from '../ui/index.js'
// Directive log — append-only ledger + the consequence diff (propose-approve)
export function DirectivesScreen() {
const [pending, setPending] = React.useState<DirectivePending | null>(DIRECTIVES.pending)
const [entries, setEntries] = React.useState<DirectiveEntry[]>(DIRECTIVES.entries)
const resolve = (status: string) => {
setEntries((e) => [{
seq: pending!.seq, who: pending!.who, when: pending!.when, what: pending!.what, why: 'pilot demo on the 14th',
status, consequence: status === 'applied' ? '#78 +5d · Beta 80% Mar 514' : 'withdrawn before apply',
}, ...e]);
setPending(null);
};
const toneColor: Record<string, string> = { ok: 'var(--ok)', warn: 'var(--warn)', info: 'var(--info)', danger: 'var(--danger)' };
const statusBadge: Record<string, { tone: 'ok' | 'neutral' | 'info'; label: string }> = {
applied: { tone: 'ok', label: 'applied' },
withdrawn: { tone: 'neutral', label: 'withdrawn' },
superseded: { tone: 'info', label: 'superseded' },
};
return (
<div style={{ maxWidth: 760, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
<header style={{ borderBottom: 'var(--rule-double)', paddingBottom: 14 }}>
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Directives</h1>
<p style={{ font: 'var(--text-data)', color: 'var(--ink-3)', margin: '6px 0 0' }}>append-only · JSONL in pm-state · who, when, what, why</p>
</header>
{pending ? (
<Card overline={`Awaiting your word · directive #00${pending.seq}`} title="Consequence diff" jade
footer={<>
<Button onClick={() => resolve('applied')}>Make it so</Button>
<Button variant="secondary" onClick={() => {}}>Amend</Button>
<Button variant="ghost" onClick={() => resolve('withdrawn')}>Withdraw</Button>
</>}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<p style={{ font: 'var(--text-body)', margin: 0, color: 'var(--ink-2)' }}>
<span style={{ font: 'var(--text-body-strong)', color: 'var(--ink-1)' }}>{pending.who}</span>
<span style={{ font: '400 11.5px var(--font-mono)', color: 'var(--ink-3)' }}> · {pending.when}</span>
<br />{pending.what}
</p>
<div style={{ borderTop: '1px solid var(--line-1)' }}>
{pending.diff.map((r) => (
<div key={r.change} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 0', borderBottom: '1px solid var(--line-1)' }}>
<span style={{ width: 7, height: 7, borderRadius: '50%', background: toneColor[r.tone], flexShrink: 0 }}></span>
<span style={{ font: 'var(--text-small)', color: 'var(--ink-1)', flex: 1 }}>{r.change}</span>
<span style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>
{r.from} <span style={{ color: 'var(--ink-2)' }}></span> <span style={{ color: r.tone === 'warn' ? 'var(--warn)' : 'var(--ink-1)' }}>{r.to}</span>
</span>
</div>
))}
</div>
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
Cheap, as consequences go. Shall I make it so?
</p>
</div>
</Card>
) : (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, font: 'var(--text-small)', color: 'var(--ink-3)', padding: '2px 2px' }}>
<Icon name="circle-check" size={14} style={{ color: 'var(--ok)' }} />
Nothing awaits your word. Directives are given in chat; consequences appear here first.
</div>
)}
<Card overline="The ledger" flush>
<div>
{entries.map((e, i) => {
const sb = statusBadge[e.status];
return (
<div key={e.seq} style={{ display: 'flex', gap: 14, padding: '14px 20px', borderTop: i === 0 ? 'none' : '1px solid var(--line-1)' }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flexShrink: 0 }}>
<span style={{ font: '500 11px var(--font-mono)', color: 'var(--ink-3)' }}>#00{e.seq}</span>
<span style={{ width: 1, flex: 1, background: 'var(--line-1)' }}></span>
</div>
<div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 5 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<span style={{
width: 20, height: 20, borderRadius: '50%', background: 'var(--spruce-2)', color: 'var(--accent-text)',
font: '600 8.5px/20px var(--font-sans)', textAlign: 'center', flexShrink: 0,
}}>{e.who.split(' ').map((w: string) => w[0]).join('')}</span>
<span style={{ font: 'var(--text-body-strong)', color: 'var(--ink-1)', whiteSpace: 'nowrap' }}>{e.who}</span>
<span style={{ font: '400 11px var(--font-mono)', color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{e.when}</span>
{e.why ? <span style={{ font: '400 11px var(--font-mono)', color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>· why: {e.why}</span> : null}
<span style={{ marginLeft: 'auto' }}><Badge tone={sb.tone}>{sb.label}</Badge></span>
</div>
<p style={{ font: 'var(--text-body)', color: 'var(--ink-1)', margin: 0 }}>{e.what}</p>
<p style={{ font: '400 11.5px var(--font-mono)', color: 'var(--ink-2)', margin: 0 }}>{e.consequence}</p>
</div>
</div>
);
})}
</div>
</Card>
<p style={{ font: 'var(--text-caption)', color: 'var(--ink-3)', margin: 0 }}>
Entries are never edited. Corrections are new entries the ledger remembers everything, politely.
</p>
</div>
);
}

View File

@@ -1,14 +1,25 @@
import React from 'react' import React from 'react'
import { FOCUS, type FocusIssue, type IssueRef, TODAY } from '../../data/fixtures.js' import { FOCUS, type FocusIssue, type IssueRef, TODAY } from '../../data/fixtures.js'
import { type ForecastView, type FocusView } from '../../lib/backlog.js'
import { BurnUpCone } from '../charts/chart.js' import { BurnUpCone } from '../charts/chart.js'
import { Badge, Button, Card, IconButton, Tag } from '../ui/index.js' import { Badge, Button, Card, IconButton, Tag } from '../ui/index.js'
/** /**
* Morning service — the Now/Next/Later focus cards + the milestone burn-up cone. * Morning service — the Now/Next/Later focus cards + the burn-up cone.
* Data is fixture (data.js) until P2's scheduler + Monte Carlo feed it. * `focus` (scheduler) and `forecast` (Monte Carlo) override the demo fixtures
* when gitea is configured; both fall back to the handoff demo otherwise.
*/ */
export function FocusScreen({ onOpenIssue }: { onOpenIssue: (issue: IssueRef) => void }) { export function FocusScreen({
onOpenIssue,
focus,
forecast,
}: {
onOpenIssue: (issue: IssueRef) => void
focus?: FocusView
forecast?: ForecastView
}) {
const view: FocusView = focus ?? { now: FOCUS.now, next: FOCUS.next, later: FOCUS.later }
const FocusRow = ({ slot, issue, jade }: { slot: string; issue: FocusIssue; jade?: boolean }) => ( const FocusRow = ({ slot, issue, jade }: { slot: string; issue: FocusIssue; jade?: boolean }) => (
<Card <Card
overline={slot} overline={slot}
@@ -79,19 +90,29 @@ export function FocusScreen({ onOpenIssue }: { onOpenIssue: (issue: IssueRef) =>
</header> </header>
<div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 14, alignItems: 'start' }}> <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 14, alignItems: 'start' }}>
<FocusRow slot="Now" issue={FOCUS.now} jade /> {view.now ? <FocusRow slot="Now" issue={view.now} jade /> : null}
<FocusRow slot="Next" issue={FOCUS.next} /> {view.next ? <FocusRow slot="Next" issue={view.next} /> : null}
<FocusRow slot="Later" issue={FOCUS.later} /> {view.later ? <FocusRow slot="Later" issue={view.later} /> : null}
</div> </div>
<Card <Card
overline="Milestone · Beta" overline={forecast ? 'Backlog · open scope' : 'Milestone · Beta'}
title={<>80% this lands <span style={{ whiteSpace: 'nowrap' }}>Mar 312</span></>} title={
forecast ? (
<>80% of the open backlog lands by <span style={{ whiteSpace: 'nowrap' }}>{forecast.rangeLabel}</span></>
) : (
<>80% this lands <span style={{ whiteSpace: 'nowrap' }}>Mar 312</span></>
)
}
actions={<IconButton icon="chart-line" label="Open runway" size="sm" />} actions={<IconButton icon="chart-line" label="Open runway" size="sm" />}
> >
<BurnUpCone /> <BurnUpCone data={forecast?.cone} />
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 0' }}> <p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 0' }}>
The cone has narrowed since Friday. Im quietly pleased. {forecast
? forecast.coldStart
? `${forecast.scope} open ${forecast.scope === 1 ? 'issue' : 'issues'} in scope. Cold-start priors — ${forecast.calibratedN}/20 estimated closes so far; the cone tightens as the team closes work.`
: `${forecast.scope} open ${forecast.scope === 1 ? 'issue' : 'issues'} in scope, calibrated on ${forecast.calibratedN} closed ${forecast.calibratedN === 1 ? 'issue' : 'issues'} of your own.`
: 'The cone has narrowed since Friday. Im quietly pleased.'}
</p> </p>
</Card> </Card>
</div> </div>

View File

@@ -1,17 +1,33 @@
// Issue detail — human intent (gitea) on the left, machine-derived (pm-state) on the right // Issue detail — human intent (gitea) on the left, machine-derived (pm-state) on the right
import React from 'react' import React, { useState } from 'react'
import {
describeChange,
type EstimateLabel,
ESTIMATE_LABELS,
type IssueChange,
planIssueChange,
type PriorityLabel,
PRIORITY_LABELS,
} from '@commitea/core'
import { ISSUE_DETAIL, type IssueDetail, type IssueRef } from '../../data/fixtures.js' import { ISSUE_DETAIL, type IssueDetail, type IssueRef } from '../../data/fixtures.js'
import { Badge, Button, Card, Icon, Tag } from '../ui/index.js' import { Badge, Button, Card, Dialog, Icon, Select, Tag } from '../ui/index.js'
const NONE = '—'
export function IssueScreen({ export function IssueScreen({
issue, issue,
onBack, onBack,
onOpenIssue, onOpenIssue,
canWrite = false,
onApplyChange,
}: { }: {
issue: IssueRef issue: IssueRef
onBack: () => void onBack: () => void
onOpenIssue: (issue: IssueRef) => void onOpenIssue: (issue: IssueRef) => void
canWrite?: boolean
onApplyChange?: (change: IssueChange) => Promise<{ ok: boolean }>
}) { }) {
const det: IssueDetail = ISSUE_DETAIL[issue.id] || { const det: IssueDetail = ISSUE_DETAIL[issue.id] || {
state: 'triage', state: 'triage',
@@ -40,6 +56,44 @@ export function IssueScreen({
} as Record<string, { tone: 'warn' | 'neutral' | 'info' | 'ok'; label: string }> } as Record<string, { tone: 'warn' | 'neutral' | 'info' | 'ok'; label: string }>
)[det.state] || { tone: 'neutral', label: det.state } )[det.state] || { tone: 'neutral', label: det.state }
// ---- propose-approve write path (apply_changes) ----
const labels = issue.labels ?? []
const curEstimate = labels.find((l) => l.startsWith('est/')) ?? ''
const curPriority = labels.find((l) => l.startsWith('p/')) ?? ''
const [adjustOpen, setAdjustOpen] = useState(false)
const [estimate, setEstimate] = useState(curEstimate)
const [priority, setPriority] = useState(curPriority)
const [applying, setApplying] = useState(false)
const openAdjust = () => {
setEstimate(curEstimate)
setPriority(curPriority)
setAdjustOpen(true)
}
// the concrete changes this dialog would apply, one per axis that differs
const pendingChanges: IssueChange[] = []
if (estimate !== curEstimate)
pendingChanges.push({ kind: 'reestimate', issue: issue.id, estimate: (estimate || null) as EstimateLabel | null })
if (priority !== curPriority)
pendingChanges.push({ kind: 'reprioritize', issue: issue.id, priority: (priority || null) as PriorityLabel | null })
const diffs = pendingChanges.map((c) => describeChange(planIssueChange(labels, c)))
const apply = async () => {
if (!onApplyChange || pendingChanges.length === 0) return
setApplying(true)
try {
for (const c of pendingChanges) await onApplyChange(c)
setAdjustOpen(false)
} finally {
setApplying(false)
}
}
const estOptions = [{ value: '', label: NONE }, ...ESTIMATE_LABELS.map((l) => ({ value: l, label: l }))]
const prioOptions = [{ value: '', label: NONE }, ...PRIORITY_LABELS.map((l) => ({ value: l, label: l }))]
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
{/* breadcrumb + header */} {/* breadcrumb + header */}
@@ -65,10 +119,69 @@ export function IssueScreen({
</span> </span>
</div> </div>
</div> </div>
<Button variant="secondary" icon="arrow-up-right">Open in Gitea</Button> <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
{canWrite ? (
<Button variant="secondary" icon="pencil" onClick={openAdjust}>
Adjust
</Button>
) : null}
<Button variant="secondary" icon="arrow-up-right">Open in Gitea</Button>
</div>
</header> </header>
</div> </div>
<Dialog
open={adjustOpen}
onClose={() => setAdjustOpen(false)}
title="Adjust estimate & priority"
footer={
<>
<Button variant="ghost" onClick={() => setAdjustOpen(false)}>
Cancel
</Button>
<Button onClick={apply} disabled={pendingChanges.length === 0 || applying}>
{applying ? 'Applying…' : 'Apply to gitea'}
</Button>
</>
}
>
<div style={{ display: 'flex', gap: 14 }}>
<Select
label="Estimate"
options={estOptions}
value={estimate}
onChange={(e) => setEstimate(e.target.value)}
/>
<Select
label="Priority"
options={prioOptions}
value={priority}
onChange={(e) => setPriority(e.target.value)}
/>
</div>
<div style={{ marginTop: 14, minHeight: 40 }}>
{pendingChanges.length === 0 ? (
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-3)', margin: 0 }}>
No change yet pick a different estimate or priority.
</p>
) : (
<>
<p style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', margin: '0 0 6px' }}>
Proposed label change
</p>
{diffs.map((d) => (
<div key={d} style={{ font: '500 13px var(--font-mono)', color: 'var(--ink-1)' }}>
{d}
</div>
))}
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '8px 0 0' }}>
Writes the label to gitea and re-runs the plan. Nothing else changes.
</p>
</>
)}
</div>
</Dialog>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 16, alignItems: 'start' }}> <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 16, alignItems: 'start' }}>
{/* left: human intent */} {/* left: human intent */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

View File

@@ -0,0 +1,169 @@
import React from 'react'
import logoIcon from '../../design/assets/logo-icon.png'
import { Badge, Button, Icon, Input, Radio, Tag } from '../ui/index.js'
// Onboarding / first connect — welcome → connect gitea → choose repo → bootstrap
export function OnboardingScreen({ onDone }: { onDone: (dest: 'focus' | 'capture') => void }) {
const [step, setStep] = React.useState<number>(0)
const [conn, setConn] = React.useState<'idle' | 'testing' | 'ok'>('idle')
const [repo, setRepo] = React.useState('stephen/commitea')
const [boot, setBoot] = React.useState<number>(-1) // -1 idle, 0..2 running, 3 done
React.useEffect(() => {
if (conn !== 'testing') return
const t = setTimeout(() => setConn('ok'), 1100)
return () => clearTimeout(t)
}, [conn])
React.useEffect(() => {
if (boot < 0 || boot >= 3) return
const t = setTimeout(() => setBoot(boot + 1), 700)
return () => clearTimeout(t)
}, [boot])
const STEPS = ['Welcome', 'Connect', 'Repo', 'Bootstrap']
const BOOT_TASKS = [
'Create stephen/pm-state (the sidecar)',
'Apply the label schema to stephen/commitea',
'Install a webhook · endpoint :48731',
]
const Frame = ({ children, footer }: { children: React.ReactNode; footer?: React.ReactNode }) => (
<div style={{
background: 'var(--surface-card)', border: '1px solid var(--line-1)', borderRadius: 'var(--radius-3)',
boxShadow: 'var(--shadow-jade-line), var(--shadow-2)', padding: '30px 36px',
display: 'flex', flexDirection: 'column', gap: 16, width: '100%',
}}>
{children}
{footer ? <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', borderTop: '1px solid var(--line-1)', paddingTop: 16 }}>{footer}</div> : null}
</div>
)
return (
<div style={{
minHeight: '100vh', background: 'var(--surface-app)', display: 'flex', flexDirection: 'column',
alignItems: 'center', justifyContent: 'center', padding: 32, gap: 22,
}} data-screen-label="onboarding">
{/* brand */}
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<img src={logoIcon} width="34" height="34" alt="" style={{ borderRadius: 8, display: 'block' }} />
<span style={{ font: '400 27px/1 var(--font-serif-display)', color: 'var(--ink-1)' }}>
Commi<span style={{ color: 'var(--accent-text)' }}>Tea</span>
</span>
</div>
{/* stepper */}
<div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
{STEPS.map((s, i) => (
<div key={s} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}>
<span style={{
width: 20, height: 20, borderRadius: '50%', textAlign: 'center',
font: '500 10.5px/20px var(--font-mono)',
background: i < step ? 'var(--accent)' : i === step ? 'var(--spruce-2)' : 'var(--paper-2)',
color: i < step ? 'var(--ink-inverse)' : i === step ? 'var(--accent-text)' : 'var(--ink-3)',
}}>{i < step ? '✓' : i + 1}</span>
<span style={{ font: `${i === step ? 600 : 400} 12px/1 var(--font-sans)`, color: i === step ? 'var(--ink-1)' : 'var(--ink-3)' }}>{s}</span>
</span>
{i < STEPS.length - 1 ? <span style={{ width: 24, height: 1, background: 'var(--line-2)' }}></span> : null}
</div>
))}
</div>
<div style={{ width: 'min(540px, 100%)' }}>
{step === 0 ? (
<Frame footer={<Button iconRight="arrow-right" onClick={() => setStep(1)}>Begin</Button>}>
<h1 style={{ font: 'var(--text-title)', color: 'var(--ink-1)', margin: 0 }}>Good morning.</h1>
<p style={{ font: 'var(--text-agent-lg)', color: 'var(--ink-2)', margin: 0 }}>
I'm Reginald, your project manager. I interview you instead of making you fill in forms,
I forecast in honest ranges, and I never do the arithmetic myself — there's a scheduler for that.
</p>
<p style={{ font: 'var(--text-body)', color: 'var(--ink-2)', margin: 0 }}>
Your plans live in your own Gitea as ordinary issues and labels. Delete me and nothing human is lost.
</p>
</Frame>
) : null}
{step === 1 ? (
<Frame footer={<>
<Button variant="ghost" onClick={() => setStep(0)}>Back</Button>
<Button iconRight="arrow-right" disabled={conn !== 'ok'} onClick={() => setStep(2)}>Continue</Button>
</>}>
<h1 style={{ font: 'var(--text-title)', color: 'var(--ink-1)', margin: 0 }}>Your Gitea</h1>
<Input label="Base URL" icon="link" mono defaultValue="https://gitea.stephenmann.io" />
<Input label="Access token" icon="keyboard" mono type="password" defaultValue="ct_9f2e81c4a7d6" hint="Scopes: repo, issue. Nothing more." />
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<Button variant="secondary" icon={conn === 'testing' ? 'loader-circle' : 'zap'} disabled={conn === 'testing'} onClick={() => setConn('testing')}>
{conn === 'testing' ? 'Ringing the bell…' : 'Test connection'}
</Button>
{conn === 'ok' ? <Badge tone="ok" dot>connected · 3 repos visible</Badge> : null}
</div>
</Frame>
) : null}
{step === 2 ? (
<Frame footer={<>
<Button variant="ghost" onClick={() => setStep(1)}>Back</Button>
<Button iconRight="arrow-right" onClick={() => setStep(3)}>Continue</Button>
</>}>
<h1 style={{ font: 'var(--text-title)', color: 'var(--ink-1)', margin: 0 }}>Which repo shall I manage?</h1>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{['stephen/commitea', 'stephen/novelpad', 'stephen/infra'].map((r: string) => (
<label key={r} style={{
display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', cursor: 'pointer',
background: repo === r ? 'var(--spruce-1)' : 'var(--paper-0)',
border: `1px solid ${repo === r ? 'var(--spruce-3)' : 'var(--line-1)'}`,
borderRadius: 'var(--radius-2)',
}}>
<Radio name="repo" checked={repo === r} onChange={() => setRepo(r)} />
<Icon name="git-branch" size={14} style={{ color: 'var(--ink-3)' }} />
<span style={{ font: 'var(--text-data)', color: 'var(--ink-1)' }}>{r}</span>
</label>
))}
</div>
<p style={{ font: 'var(--text-caption)', color: 'var(--ink-3)', margin: 0 }}>One to start. You can add more later in Settings.</p>
</Frame>
) : null}
{step === 3 ? (
<Frame footer={boot === 3 ? <>
<Button variant="ghost" onClick={() => onDone('focus')}>Just look around</Button>
<Button icon="sparkles" onClick={() => onDone('capture')}>Start a capture</Button>
</> : <>
<Button variant="ghost" onClick={() => setStep(2)} disabled={boot >= 0}>Back</Button>
<Button disabled={boot >= 0} onClick={() => setBoot(0)}>Make it so</Button>
</>}>
<h1 style={{ font: 'var(--text-title)', color: 'var(--ink-1)', margin: 0 }}>
{boot === 3 ? 'All set.' : 'With your approval'}
</h1>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{BOOT_TASKS.map((t: string, i: number) => (
<div key={t} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span style={{ display: 'inline-flex', color: boot > i ? 'var(--ok)' : boot === i ? 'var(--warn)' : 'var(--ink-3)' }}>
<Icon name={boot > i ? 'circle-check' : boot === i ? 'loader-circle' : 'circle-dashed'} size={15} />
</span>
<span style={{ font: 'var(--text-body)', color: boot > i ? 'var(--ink-1)' : 'var(--ink-2)', whiteSpace: 'nowrap' }}>{t}</span>
</div>
))}
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, paddingLeft: 25 }}>
{['est/1d', 'est/2d', 'est/3d', 'est/5d', 'est/8d', 'p/1', 'p/2', 'p/3', 'p/4', 'deadline/hard'].map((l: string) => <Tag key={l} label={l} />)}
</div>
</div>
{boot === 3 ? (
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
The pot is empty. Tell me what you're planning and I'll draw up the tickets.
</p>
) : (
<p style={{ font: 'var(--text-caption)', color: 'var(--ink-3)', margin: 0 }}>
No bot comments, no body frontmatter, no synthetic issues ever. Labels are the only footprint.
</p>
)}
</Frame>
) : null}
</div>
<span style={{ font: '400 11px var(--font-mono)', color: 'var(--ink-3)' }}>first run · everything reversible</span>
</div>
)
}

View File

@@ -8,15 +8,22 @@ import { RUNWAY, CAPACITY } from '../../data/fixtures.js'
export function RunwayScreen({ export function RunwayScreen({
onOpenCalibration, onOpenCalibration,
onOpenMilestone, onOpenMilestone,
calibration,
}: { }: {
onOpenCalibration: () => void onOpenCalibration: () => void
onOpenMilestone: () => void onOpenMilestone: () => void
calibration?: { n: number; coldStart: boolean }
}) { }) {
const calibNote = calibration
? calibration.coldStart
? `cold-start priors · ${calibration.n}/20 closed issues estimated`
: `calibrated on ${calibration.n} closed ${calibration.n === 1 ? 'issue' : 'issues'}`
: 'calibrated on 27 closed issues'
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<header style={{ borderBottom: 'var(--rule-double)', paddingBottom: 14 }}> <header style={{ borderBottom: 'var(--rule-double)', paddingBottom: 14 }}>
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Runway</h1> <h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Runway</h1>
<p style={{ font: 'var(--text-data)', color: 'var(--ink-3)', margin: '6px 0 0' }}>capacity vs milestone dates · calibrated on 27 closed issues</p> <p style={{ font: 'var(--text-data)', color: 'var(--ink-3)', margin: '6px 0 0' }}>capacity vs milestone dates · {calibNote}</p>
</header> </header>
<Card overline="Milestones" flush> <Card overline="Milestones" flush>

View File

@@ -0,0 +1,137 @@
import React from 'react'
import { Badge, Button, Card, Icon, IconButton, Input, Radio, Select, Switch, Tag } from '../ui/index.js'
// Settings — gitea connection, sync, model roles, labels, rituals, appearance
export function SettingsScreen({ dark, setDark }: { dark: boolean; setDark: (v: boolean) => void }) {
const [webhooks, setWebhooks] = React.useState(true)
const [reconcile, setReconcile] = React.useState(true)
const [poll, setPoll] = React.useState(true)
const [nag, setNag] = React.useState(true)
const Row = ({ children, style }: { children: React.ReactNode; style?: React.CSSProperties }) => (
<div style={{ display: 'flex', alignItems: 'center', gap: 12, ...style }}>{children}</div>
)
const Note = ({ children }: { children: React.ReactNode }) => (
<p style={{ font: 'var(--text-caption)', color: 'var(--ink-3)', margin: 0 }}>{children}</p>
)
return (
<div style={{ maxWidth: 720, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
<header style={{ borderBottom: 'var(--rule-double)', paddingBottom: 14 }}>
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Settings</h1>
<p style={{ font: 'var(--text-data)', color: 'var(--ink-3)', margin: '6px 0 0' }}>config lives in pm-state · versioned, portable</p>
</header>
<Card overline="Gitea" title="Connection">
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<Input label="Base URL" icon="link" mono defaultValue="https://gitea.stephenmann.io" />
<Input label="Access token" icon="keyboard" mono type="password" defaultValue="ct_9f2e81c4a7d6" hint="Scopes: repo, issue. Nothing more." />
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<span style={{ font: '600 13px/1.2 var(--font-sans)', color: 'var(--ink-1)' }}>Managed repos</span>
<Row style={{ padding: '8px 12px', background: 'var(--paper-0)', border: '1px solid var(--line-1)', borderRadius: 'var(--radius-2)' }}>
<Icon name="git-branch" size={14} style={{ color: 'var(--ink-3)' }} />
<span style={{ font: 'var(--text-data)', color: 'var(--ink-1)', flex: 1 }}>stephen/commitea</span>
<Badge tone="ok" dot>syncing</Badge>
<IconButton icon="x" label="Stop managing" size="sm" />
</Row>
<Row style={{ padding: '8px 12px', background: 'var(--paper-0)', border: '1px solid var(--line-1)', borderRadius: 'var(--radius-2)' }}>
<Icon name="layers" size={14} style={{ color: 'var(--ink-3)' }} />
<span style={{ font: 'var(--text-data)', color: 'var(--ink-1)', flex: 1 }}>stephen/pm-state</span>
<Badge>sidecar</Badge>
</Row>
<Note>The sidecar holds machine-derived state only. Delete it and resync no truth is lost.</Note>
<Button variant="secondary" size="sm" icon="plus" style={{ alignSelf: 'flex-start' }}>Add repo</Button>
</div>
</div>
</Card>
<Card overline="Sync" title="Staying current">
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<Row>
<Switch label="Webhooks while running" checked={webhooks} onChange={(e) => setWebhooks(e.target.checked)} />
<span style={{ font: '400 11.5px var(--font-mono)', color: 'var(--ink-3)', marginLeft: 'auto' }}>endpoint :48731 · healthy</span>
</Row>
<Switch label="Full reconcile on launch" checked={reconcile} onChange={(e) => setReconcile(e.target.checked)} />
<Row>
<Switch label="Poll fallback" checked={poll} onChange={(e) => setPoll(e.target.checked)} />
<div style={{ marginLeft: 'auto', width: 140 }}>
<Select options={[{ value: '2', label: 'every 2 min' }, { value: '5', label: 'every 5 min' }, { value: '15', label: 'every 15 min' }]} defaultValue="5" />
</div>
</Row>
<Note>last reconcile 3.2s · 500 issues · nothing lost</Note>
</div>
</Card>
<Card overline="Models" title="The router">
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px 14px' }}>
<Select label="Prose & rituals" options={[
{ value: 'gemma-4b', label: 'gemma-4b · local' },
{ value: 'qwen-7b', label: 'qwen-7b · local' },
]} defaultValue="gemma-4b" />
<Input label="Base URL" mono defaultValue="http://localhost:1234/v1" />
<Select label="Decomposition & negotiation" options={[
{ value: 'qwen-72b', label: 'qwen-72b · lm-studio box' },
{ value: 'gpt-4o', label: 'gpt-4o · OpenAI API' },
]} defaultValue="qwen-72b" />
<Input label="Base URL" mono defaultValue="http://10.0.0.42:1234/v1" />
</div>
<Row>
<span style={{ font: '400 11.5px var(--font-mono)', color: 'var(--ink-3)' }}>hot memory 2k tokens · math is never delegated to either</span>
</Row>
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: 0 }}>
The small one writes my standup; the large one argues with your estimates. Neither is allowed near the arithmetic.
</p>
</div>
</Card>
<Card overline="Labels" title="Schema">
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<Row style={{ flexWrap: 'wrap', gap: 6 }}>
{['est/1d', 'est/2d', 'est/3d', 'est/5d', 'est/8d'].map((l) => <Tag key={l} label={l} />)}
</Row>
<Row style={{ flexWrap: 'wrap', gap: 6 }}>
{['p/1', 'p/2', 'p/3', 'p/4'].map((l) => <Tag key={l} label={l} />)}
<Tag label="deadline/hard" />
</Row>
<Note>Fixed sets, human-meaningful, visible in gitea. Not configurable that is rather the point.</Note>
</div>
</Card>
<Card overline="Rituals" title="Reginald's calendar">
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<Row>
<span style={{ font: 'var(--text-body)', color: 'var(--ink-1)' }}>Morning standup</span>
<div style={{ marginLeft: 'auto', width: 120 }}>
<Select options={[{ value: '0630', label: '06:30' }, { value: '0700', label: '07:00' }, { value: '0800', label: '08:00' }]} defaultValue="0700" />
</div>
</Row>
<Row>
<Switch label="Stale-blocker nagging" checked={nag} onChange={(e) => setNag(e.target.checked)} />
<div style={{ marginLeft: 'auto', width: 140 }}>
<Select options={[{ value: '2', label: 'after 2 days' }, { value: '3', label: 'after 3 days' }, { value: '5', label: 'after 5 days' }]} defaultValue="3" />
</div>
</Row>
</div>
</Card>
<Card overline="Appearance" title="Service">
<div style={{ display: 'flex', gap: 20 }}>
<Radio name="theme" label="Morning (light)" checked={!dark} onChange={() => setDark(false)} />
<Radio name="theme" label="Evening (dark)" checked={dark} onChange={() => setDark(true)} />
</div>
</Card>
<Card>
<Row>
<div style={{ flex: 1 }}>
<div style={{ font: 'var(--text-body-strong)', color: 'var(--ink-1)' }}>Forget this gitea</div>
<Note>Removes the connection and the local cache. Gitea itself is untouched.</Note>
</div>
<Button variant="danger">Forget</Button>
</Row>
</Card>
</div>
)
}

View File

@@ -1,16 +1,23 @@
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import logoIcon from '../../design/assets/logo-icon.png' import logoIcon from '../../design/assets/logo-icon.png'
import type { IssueChange } from '@commitea/core'
import type { IssueRef } from '../../data/fixtures.js' import type { IssueRef } from '../../data/fixtures.js'
import { backlogCalibration, forecastBacklog, issuesToBoardColumns, scheduleFocus } from '../../lib/backlog.js'
import { useBacklog } from '../../lib/use-backlog.js'
import { PrimitivesGallery } from '../gallery.js' import { PrimitivesGallery } from '../gallery.js'
import { BoardScreen } from '../screens/board-screen.js' import { BoardScreen } from '../screens/board-screen.js'
import { CalibrationScreen } from '../screens/calibration-screen.js' import { CalibrationScreen } from '../screens/calibration-screen.js'
import { CaptureScreen } from '../screens/capture-screen.js' import { CaptureScreen } from '../screens/capture-screen.js'
import { DirectivesScreen } from '../screens/directives-screen.js'
import { FocusScreen } from '../screens/focus-screen.js' import { FocusScreen } from '../screens/focus-screen.js'
import { InboxScreen } from '../screens/inbox-screen.js' import { InboxScreen } from '../screens/inbox-screen.js'
import { IssueScreen } from '../screens/issue-screen.js' import { IssueScreen } from '../screens/issue-screen.js'
import { MilestoneScreen } from '../screens/milestone-screen.js' import { MilestoneScreen } from '../screens/milestone-screen.js'
import { OnboardingScreen } from '../screens/onboarding-screen.js'
import { RunwayScreen } from '../screens/runway-screen.js' import { RunwayScreen } from '../screens/runway-screen.js'
import { SettingsScreen } from '../screens/settings-screen.js'
import { StandupScreen } from '../screens/standup-screen.js' import { StandupScreen } from '../screens/standup-screen.js'
import { Icon, Switch } from '../ui/index.js' import { Icon, Switch } from '../ui/index.js'
import { ChatPanel } from './chat-panel.js' import { ChatPanel } from './chat-panel.js'
@@ -80,6 +87,17 @@ export function AppShell() {
const [offline, setOffline] = useState(false) const [offline, setOffline] = useState(false)
const [issue, setIssue] = useState<IssueRef | null>(null) const [issue, setIssue] = useState<IssueRef | null>(null)
const [readIds, setReadIds] = useState<number[]>([]) const [readIds, setReadIds] = useState<number[]>([])
const [backlog, refetchBacklog] = useBacklog()
const boardColumns =
backlog.status === 'ready' ? issuesToBoardColumns(backlog.issues, backlog.timelines) : undefined
const focus =
backlog.status === 'ready' ? scheduleFocus(backlog.issues, backlog.deps, backlog.timelines) : undefined
const calibration =
backlog.status === 'ready' ? backlogCalibration(backlog.issues, backlog.timelines) : undefined
const forecast =
backlog.status === 'ready'
? (forecastBacklog(backlog.issues, backlog.deps, new Date(), calibration?.model) ?? undefined)
: undefined
useEffect(() => { useEffect(() => {
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light') document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light')
@@ -91,6 +109,17 @@ export function AppShell() {
setView('issue') setView('issue')
} }
// The write path: apply through the bridge, reflect the new labels on the open
// issue immediately, and re-reconcile so the board + forecast catch up.
const applyChange = async (change: IssueChange) => {
const res = await window.commitea.gitea.applyChange(change)
if (res.ok) {
setIssue((cur) => (cur && cur.id === res.issue.number ? { ...cur, labels: res.issue.labels } : cur))
refetchBacklog()
}
return res
}
const NAV: NavEntry[] = [ const NAV: NavEntry[] = [
{ id: 'standup', label: 'Standup', icon: 'sun' }, { id: 'standup', label: 'Standup', icon: 'sun' },
{ id: 'focus', label: 'Morning service', icon: 'coffee' }, { id: 'focus', label: 'Morning service', icon: 'coffee' },
@@ -150,20 +179,27 @@ export function AppShell() {
const renderScreen = () => { const renderScreen = () => {
switch (view) { switch (view) {
case 'focus': case 'focus':
return <FocusScreen onOpenIssue={openIssue} /> return <FocusScreen onOpenIssue={openIssue} focus={focus} forecast={forecast} />
case 'standup': case 'standup':
return <StandupScreen onBegin={() => setView('focus')} onOpenIssue={openIssue} /> return <StandupScreen onBegin={() => setView('focus')} onOpenIssue={openIssue} />
case 'board': case 'board':
return <BoardScreen onOpenIssue={openIssue} /> return (
<BoardScreen
onOpenIssue={openIssue}
columns={boardColumns}
loading={backlog.status === 'loading'}
/>
)
case 'runway': case 'runway':
return ( return (
<RunwayScreen <RunwayScreen
onOpenCalibration={() => setView('calibration')} onOpenCalibration={() => setView('calibration')}
onOpenMilestone={() => setView('milestone')} onOpenMilestone={() => setView('milestone')}
calibration={calibration ? { n: calibration.model.n, coldStart: calibration.model.coldStart } : undefined}
/> />
) )
case 'calibration': case 'calibration':
return <CalibrationScreen onBack={() => setView('runway')} /> return <CalibrationScreen onBack={() => setView('runway')} data={calibration?.data} />
case 'milestone': case 'milestone':
return <MilestoneScreen onBack={() => setView('runway')} onOpenIssue={openIssue} /> return <MilestoneScreen onBack={() => setView('runway')} onOpenIssue={openIssue} />
case 'inbox': case 'inbox':
@@ -177,9 +213,19 @@ export function AppShell() {
) )
case 'capture': case 'capture':
return <CaptureScreen onDone={() => setView('focus')} /> return <CaptureScreen onDone={() => setView('focus')} />
case 'directives':
return <DirectivesScreen />
case 'settings':
return <SettingsScreen dark={dark} setDark={setDark} />
case 'issue': case 'issue':
return issue ? ( return issue ? (
<IssueScreen issue={issue} onBack={() => setView(prevView)} onOpenIssue={openIssue} /> <IssueScreen
issue={issue}
onBack={() => setView(prevView)}
onOpenIssue={openIssue}
canWrite={backlog.status === 'ready'}
onApplyChange={applyChange}
/>
) : null ) : null
case 'states': case 'states':
return <StatesScreen onCapture={() => setView('capture')} /> return <StatesScreen onCapture={() => setView('capture')} />
@@ -190,6 +236,11 @@ export function AppShell() {
} }
} }
// First run is full-window — no rail, no chat panel
if (view === 'firstrun') {
return <OnboardingScreen onDone={(dest) => setView(dest)} />
}
return ( return (
<div <div
data-screen-label={`app-${view}`} data-screen-label={`app-${view}`}

View File

@@ -472,3 +472,57 @@ export const ISSUE_DETAIL: Record<number, IssueDetail> = {
note: 'It blocks #91 and #92. Id take it first — the critical path agrees with me.', note: 'It blocks #91 and #92. Id take it first — the critical path agrees with me.',
}, },
} }
// ---- Directives ----
export interface DirectiveDiffRow {
tone: 'ok' | 'warn' | 'info' | 'danger'
change: string
from: string
to: string
}
export interface DirectivePending {
seq: number
who: string
when: string
what: string
diff: DirectiveDiffRow[]
}
export interface DirectiveEntry {
seq: number
who: string
when: string
what: string
why: string
status: string
consequence: string
}
export interface DirectivesData {
pending: DirectivePending | null
entries: DirectiveEntry[]
}
export const DIRECTIVES: DirectivesData = {
pending: {
seq: 7,
who: 'Stephen',
when: 'today 09:12',
what: 'Pilots before calibration — push #78 to next week.',
diff: [
{ tone: 'info', change: '#78 Calibration store', from: 'this week', to: 'wk of Feb 23' },
{ tone: 'warn', change: 'Beta · 80% window', from: 'Mar 312', to: 'Mar 514' },
{ tone: 'ok', change: "Today's plan", from: '#87', to: '#87 · unchanged' },
],
},
entries: [
{ seq: 6, who: 'Stephen', when: 'Feb 8 · 16:40', what: 'Ana takes nothing new until #84 lands.', why: 'context thrash', status: 'applied', consequence: 'WIP capped · v1.0 unmoved' },
{ seq: 5, who: 'Stephen', when: 'Feb 6 · 09:03', what: 'Ship Beta a week early.', why: 'board meeting', status: 'withdrawn', consequence: '80% would need scope 9d — withdrawn after diff' },
{ seq: 4, who: 'Stephen', when: 'Feb 3 · 11:21', what: 'deadline/hard on Pilot-ready.', why: 'contract date', status: 'applied', consequence: 'label applied · runway flag raised' },
{ seq: 3, who: 'Stephen', when: 'Jan 28 · 08:47', what: 'Webhook work ahead of UI polish.', why: '', status: 'applied', consequence: '#91 +2 ranks · Beta unmoved' },
{ seq: 2, who: 'Stephen', when: 'Jan 20 · 14:02', what: 'Estimates in days, never hours.', why: 'sanity', status: 'applied', consequence: 'label schema est/* confirmed' },
{ seq: 1, who: 'Stephen', when: 'Jan 19 · 09:00', what: 'CommiTea manages its own backlog.', why: 'dogfood', status: 'applied', consequence: 'stephen/commitea under management' },
],
}

View File

@@ -0,0 +1,37 @@
import type {
DependencyEdge,
GiteaIssue,
GiteaMilestone,
IssueChange,
LabelPlan,
LifecycleEvent,
} from '@commitea/core'
/** The result of a write through the bridge. */
export type ApplyChangeResult =
| { ok: false; reason: 'unconfigured' }
| { ok: true; plan: LabelPlan; issue: GiteaIssue }
/** 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[]>
}>
getIssue(index: number): Promise<GiteaIssue | null>
applyChange(change: IssueChange): Promise<ApplyChangeResult>
}
declare global {
interface Window {
commitea: {
platform: string
gitea: GiteaBridge
}
}
}

View File

@@ -0,0 +1,234 @@
import {
type CalibrationModel,
type CalibrationSample,
calibrationSamples,
COLD_START_THRESHOLD,
type DependencyEdge,
fitCalibration,
forecast,
type GiteaIssue,
inferLifecycle,
type LifecycleColumn,
type LifecycleEvent,
type LifecycleInference,
PRIOR_BUCKETS,
schedule,
type ScheduledItem,
selectFocus,
toDurationModel,
} from '@commitea/core'
import { type BoardColumn, type BoardIssue, type CalibrationData, type FocusIssue } from '../data/fixtures.js'
import { type BurnUpData, buildBurnUpData } from './dates.js'
type Timelines = Record<number, LifecycleEvent[]>
/** Infer every issue's lifecycle once; callers index by issue number. */
function inferAll(issues: GiteaIssue[], timelines: Timelines, asOf: Date): Map<number, LifecycleInference> {
return new Map(issues.map((i) => [i.number, inferLifecycle(i, timelines[i.number] ?? [], asOf)]))
}
const COLUMN_LABELS: Record<LifecycleColumn, string> = {
diagnosis: 'Diagnosis',
triage: 'Triage',
steeping: 'Steeping',
review: 'In review',
done: 'Done',
}
const COLUMN_ORDER: LifecycleColumn[] = ['diagnosis', 'triage', 'steeping', 'review', 'done']
function initials(login: string): string {
return login.slice(0, 2).toUpperCase()
}
/**
* Shape real gitea issues into the Board's five columns via lifecycle inference
* (#5). Steeping / In-review are now populated from the event stream (first
* commit ref → steeping, first PR ref → review); the `days` badge is the
* steeping age in working days.
*/
export function issuesToBoardColumns(
issues: GiteaIssue[],
timelines: Timelines = {},
asOf: Date = new Date(),
): BoardColumn[] {
const inf = inferAll(issues, timelines, asOf)
return COLUMN_ORDER.map((key) => ({
id: key,
label: COLUMN_LABELS[key],
issues: issues
.filter((i) => inf.get(i.number)!.column === key)
.map((i): BoardIssue => {
const li = inf.get(i.number)!
return {
id: i.number,
title: i.title,
labels: i.labels,
who: i.assignee ? initials(i.assignee) : '·',
days: li.steepingDays != null ? `${li.steepingDays}d` : undefined,
}
}),
}))
}
export interface FocusView {
now: FocusIssue | null
next: FocusIssue | null
later: FocusIssue | null
}
function toFocusIssue(item: ScheduledItem | null, inf?: Map<number, LifecycleInference>): FocusIssue | null {
if (!item) return null
const steepingDays = inf?.get(item.number)?.steepingDays ?? null
return {
id: item.number,
title: item.title,
labels: item.labels,
rationale: item.rationale,
steeping: steepingDays != null ? `${steepingDays}d` : undefined,
}
}
function toSchedulable(issues: GiteaIssue[]) {
return issues
.filter((i) => i.state === 'open')
.map((i) => ({
number: i.number,
title: i.title,
labels: i.labels,
estimateDays: i.facts.estimateDays,
priority: i.facts.priority,
}))
}
export interface ForecastView {
scope: number
cone: BurnUpData
p80Label: string
rangeLabel: string
/** true while the forecast still runs on code priors (calibration not yet trusted). */
coldStart: boolean
/** Closed-with-estimate issues feeding calibration so far. */
calibratedN: number
}
/**
* Monte Carlo forecast over the open backlog, mapped onto a calendar-anchored
* burn-up cone. When a calibration model is supplied and past cold-start, its
* fitted params drive the sim. Returns null when there's nothing to forecast.
* `today` is injectable for tests.
*/
export function forecastBacklog(
issues: GiteaIssue[],
deps: DependencyEdge[],
today: Date = new Date(),
calibration?: CalibrationModel,
): ForecastView | null {
const model = calibration ? toDurationModel(calibration) : undefined
const f = forecast(toSchedulable(issues), deps, model ? { model } : {})
const cone = buildBurnUpData(f, today)
if (!cone) return null
return {
scope: f.scope,
cone,
p80Label: cone.p80Label,
rangeLabel: cone.rangeLabel,
coldStart: f.coldStart,
calibratedN: calibration?.n ?? 0,
}
}
/** Fit the calibration model from the closed backlog's inferred actuals (#1). */
export function calibrateBacklog(
issues: GiteaIssue[],
timelines: Timelines = {},
asOf: Date = new Date(),
): CalibrationModel {
return fitCalibration(calibrationSamples(issues, timelines, asOf))
}
/** Calibration model + its screen view in one pass over the closed backlog. */
export function backlogCalibration(
issues: GiteaIssue[],
timelines: Timelines = {},
asOf: Date = new Date(),
): { model: CalibrationModel; data: CalibrationData } {
const samples = calibrationSamples(issues, timelines, asOf)
const model = fitCalibration(samples)
return { model, data: calibrationData(model, samples, issues) }
}
const pctFromMu = (mu: number) => Math.round((Math.exp(mu) - 1) * 100)
/**
* Shape the calibration model + its samples into the screen's view. Buckets and
* people only earn a bias once their sample clears the fit floor; everything
* degrades honestly on a thin (cold-start) dataset.
*/
export function calibrationData(
model: CalibrationModel,
samples: CalibrationSample[],
openIssues: GiteaIssue[],
): CalibrationData {
const labels = PRIOR_BUCKETS.map((b) => {
const inBucket = samples.filter((s) => s.bucket === b)
const fit = model.byBucket[b]
const mu = fit ? fit.mu : model.global.mu
return {
label: `est/${b}d`,
n: fit ? fit.n : inBucket.length,
median: inBucket.length ? `${(b * Math.exp(mu)).toFixed(1)}d` : '—',
bias: fit ? pctFromMu(fit.mu) : null,
}
})
const people = Object.entries(model.byPerson).map(([who, pb]) => ({
who,
n: pb.n,
bias: pctFromMu(model.global.mu + pb.biasMu),
note: '',
}))
const openEst = openIssues
.filter((i) => i.state === 'open')
.reduce((sum, i) => sum + (i.facts.estimateDays ?? 2), 0)
const effect = model.coldStart
? { raw: `${model.n}/${COLD_START_THRESHOLD} estimated closes`, banded: 'cold-start priors', p50: '—' }
: {
raw: `${openEst}d estimated`,
banded: `×${Math.exp(model.global.mu).toFixed(2)} median drift`,
p50: `${Math.round(openEst * Math.exp(model.global.mu))}d`,
}
return {
n: model.n,
active: !model.coldStart,
labels,
people,
scatter: samples.map((s) => [s.estimateDays, s.actualWorkingDays]),
fit: Number(Math.exp(model.global.mu).toFixed(2)),
effect,
}
}
/**
* Run the deterministic scheduler over the open backlog and take the top three
* as Now/Next/Later. Estimates + priority come from label facts; dependency
* edges come from gitea's native issue dependencies.
*/
export function scheduleFocus(
issues: GiteaIssue[],
deps: DependencyEdge[],
timelines: Timelines = {},
asOf: Date = new Date(),
): FocusView {
const plan = schedule(toSchedulable(issues), deps)
const f = selectFocus(plan)
const inf = inferAll(issues, timelines, asOf)
return {
now: toFocusIssue(f.now, inf),
next: toFocusIssue(f.next, inf),
later: toFocusIssue(f.later, inf),
}
}

View File

@@ -0,0 +1,70 @@
import type { Forecast } from '@commitea/core'
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
/** Advance `base` by whole working days (skipping Sat/Sun). Fractions round to nearest day. */
export function addWorkingDays(base: Date, workingDays: number): Date {
const d = new Date(base.getFullYear(), base.getMonth(), base.getDate())
let remaining = Math.max(0, Math.round(workingDays))
while (remaining > 0) {
d.setDate(d.getDate() + 1)
const day = d.getDay()
if (day !== 0 && day !== 6) remaining -= 1
}
return d
}
/** "Mar 6" */
export function formatShort(d: Date): string {
return `${MONTHS[d.getMonth()]} ${d.getDate()}`
}
/** "Feb 24 Mar 6" (collapses the month when both ends share it → "Mar 312"). */
export function formatRange(lo: Date, hi: Date): string {
if (lo.getMonth() === hi.getMonth()) return `${MONTHS[lo.getMonth()]} ${lo.getDate()}${hi.getDate()}`
return `${formatShort(lo)} ${formatShort(hi)}`
}
export interface BurnUpBandPoint {
fraction: number
loDay: number
midDay: number
hiDay: number
}
/** Chart-ready geometry + calendar labels derived from a Monte Carlo forecast. */
export interface BurnUpData {
scope: number
horizonDays: number
band: BurnUpBandPoint[]
p80Day: number
p80Label: string
rangeLabel: string
startLabel: string
endLabel: string
}
/**
* Map a working-day forecast onto a calendar-anchored burn-up cone. `today`
* anchors day 0; the cone emanates from (today, 0) and widens to the right.
* The historical "actual" polyline behind today awaits lifecycle events (#5).
*/
export function buildBurnUpData(f: Forecast, today: Date): BurnUpData | null {
if (f.scope === 0 || f.curve.length === 0) return null
const last = f.curve[f.curve.length - 1]
const horizonDays = Math.max(1, Math.ceil(last.p90Day * 1.05))
const band: BurnUpBandPoint[] = [
{ fraction: 0, loDay: 0, midDay: 0, hiDay: 0 },
...f.curve.map((p) => ({ fraction: p.fraction, loDay: p.p10Day, midDay: p.p50Day, hiDay: p.p90Day })),
]
return {
scope: f.scope,
horizonDays,
band,
p80Day: f.p80Day,
p80Label: formatShort(addWorkingDays(today, f.p80Day)),
rangeLabel: formatRange(addWorkingDays(today, f.p50Day), addWorkingDays(today, last.p90Day)),
startLabel: formatShort(today),
endLabel: formatShort(addWorkingDays(today, horizonDays)),
}
}

View File

@@ -0,0 +1,55 @@
import { useCallback, useEffect, useState } from 'react'
import type { DependencyEdge, GiteaIssue, GiteaMilestone, LifecycleEvent } from '@commitea/core'
export type BacklogState =
| { status: 'loading' }
| { status: 'unconfigured' }
| { status: 'error'; message: string }
| {
status: 'ready'
issues: GiteaIssue[]
milestones: GiteaMilestone[]
deps: DependencyEdge[]
timelines: Record<number, LifecycleEvent[]>
}
/**
* 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`.
*/
export function useBacklog(): [BacklogState, () => void] {
const [state, setState] = useState<BacklogState>({ status: 'loading' })
const [nonce, setNonce] = useState(0)
const refetch = useCallback(() => setNonce((n) => n + 1), [])
useEffect(() => {
let alive = true
window.commitea.gitea
.reconcile()
.then((r) => {
if (!alive) return
setState(
r.configured
? {
status: 'ready',
issues: r.issues,
milestones: r.milestones,
deps: r.deps,
timelines: r.timelines,
}
: { status: 'unconfigured' },
)
})
.catch((e: unknown) => {
if (alive) setState({ status: 'error', message: e instanceof Error ? e.message : String(e) })
})
return () => {
alive = false
}
}, [nonce])
return [state, refetch]
}

View File

@@ -0,0 +1,121 @@
import { describe, expect, it } from 'vitest'
import { extractLabelFacts } from '../labels/label-schema.js'
import type { LifecycleEvent } from '../lifecycle/lifecycle-v0.js'
import type { GiteaIssue } from '../gitea/types.js'
import {
CALIBRATION_BUCKET_FLOOR,
calibrationSamples,
type CalibrationSample,
COLD_START_THRESHOLD,
fitCalibration,
toDurationModel,
} from './calibration-v0.js'
function sample(over: Partial<CalibrationSample> = {}): CalibrationSample {
return { issue: 1, estimateDays: 2, actualWorkingDays: 2, bucket: 2, person: null, ...over }
}
describe('fitCalibration', () => {
it('is cold-start below the threshold and reports the honest n', () => {
const m = fitCalibration([sample(), sample({ actualWorkingDays: 4 })])
expect(m.n).toBe(2)
expect(m.coldStart).toBe(true)
})
it('flips off cold-start at the threshold', () => {
const many = Array.from({ length: COLD_START_THRESHOLD }, (_, i) =>
sample({ issue: i, estimateDays: 2, actualWorkingDays: 3, bucket: 2 }),
)
const m = fitCalibration(many)
expect(m.n).toBe(COLD_START_THRESHOLD)
expect(m.coldStart).toBe(false)
})
it('recovers the global median ratio (mu = mean log-ratio)', () => {
// every actual is exactly 2x its estimate → mu = ln 2
const m = fitCalibration(Array.from({ length: 25 }, (_, i) => sample({ issue: i, estimateDays: 2, actualWorkingDays: 4 })))
expect(m.global.mu).toBeCloseTo(Math.log(2), 6)
})
it('fits a bucket only once it clears the floor', () => {
const twos = Array.from({ length: CALIBRATION_BUCKET_FLOOR }, (_, i) =>
sample({ issue: i, estimateDays: 2, actualWorkingDays: 3, bucket: 2 }),
)
const oneThin = [sample({ issue: 99, estimateDays: 5, actualWorkingDays: 9, bucket: 5 })]
const m = fitCalibration([...twos, ...oneThin])
expect(m.byBucket[2]?.n).toBe(CALIBRATION_BUCKET_FLOOR)
expect(m.byBucket[5]).toBeUndefined() // only 1 sample, below floor
})
it('drops non-positive estimates/actuals', () => {
const m = fitCalibration([sample({ actualWorkingDays: 0 }), sample({ estimateDays: 0 }), sample()])
expect(m.n).toBe(1)
})
it('derives a per-person bias relative to global', () => {
// one person consistently runs longer than the mean
const base = Array.from({ length: 20 }, (_, i) => sample({ issue: i, actualWorkingDays: 2, person: 'ak' }))
const slow = Array.from({ length: 3 }, (_, i) => sample({ issue: 100 + i, actualWorkingDays: 6, person: 'sm' }))
const m = fitCalibration([...base, ...slow])
expect(m.byPerson['sm'].biasMu).toBeGreaterThan(0)
expect(m.byPerson['ak'].biasMu).toBeLessThan(0)
})
})
describe('toDurationModel', () => {
it('projects the fit down to the params forecast needs', () => {
const m = fitCalibration(
Array.from({ length: 25 }, (_, i) => sample({ issue: i, estimateDays: 2, actualWorkingDays: 3, bucket: 2 })),
)
const dm = toDurationModel(m)
expect(dm.coldStart).toBe(false)
expect(dm.byBucket[2].mu).toBeCloseTo(m.byBucket[2].mu, 6)
expect(dm.global.mu).toBeCloseTo(m.global.mu, 6)
})
})
describe('calibrationSamples', () => {
const asOf = new Date('2026-02-01T00:00:00Z')
function issue(over: Partial<GiteaIssue>): GiteaIssue {
const labels = over.labels ?? []
return {
number: 1,
title: '#1',
body: '',
state: 'closed',
labels,
facts: extractLabelFacts(labels),
milestone: null,
assignee: null,
assignees: [],
createdAt: '2026-01-05T09:00:00Z',
updatedAt: '2026-01-12T09:00:00Z',
closedAt: '2026-01-12T09:00:00Z',
url: '',
...over,
}
}
const events = (i: number): Record<number, LifecycleEvent[]> => ({
[i]: [{ type: 'commit', at: '2026-01-07T09:00:00Z' }, { type: 'close', at: '2026-01-12T09:00:00Z' }],
})
it('samples closed, estimated issues with a resolvable actual', () => {
const i = issue({ number: 7, labels: ['est/2d'], assignee: 'sm', closedAt: '2026-01-12T09:00:00Z' })
const [s] = calibrationSamples([i], events(7), asOf)
expect(s.issue).toBe(7)
expect(s.estimateDays).toBe(2)
expect(s.bucket).toBe(2)
expect(s.person).toBe('sm')
// Wed 2026-01-07 → Mon 2026-01-12 = Wed,Thu,Fri = 3 working days
expect(s.actualWorkingDays).toBe(3)
})
it('skips open issues and closed ones without an estimate', () => {
const open = issue({ number: 8, state: 'open', labels: ['est/2d'], closedAt: null })
const noEst = issue({ number: 9, labels: [] })
expect(calibrationSamples([open, noEst], { ...events(8), ...events(9) }, asOf)).toEqual([])
})
})

View File

@@ -0,0 +1,127 @@
/**
* Calibration, v0 — fit the team's own estimate-vs-actual history so the
* forecast stops guessing (D3). The "actual" is the working time lifecycle
* inference derives from git events (#5), never manual tracking. Fit a
* lognormal on log(actual / estimate) globally and per estimate bucket; until
* the sample clears the cold-start threshold, the forecast keeps using the
* code-resident priors and this model just reports progress toward it.
*/
import { type DurationModel, type LognormalPrior, nearestBucket } from '../forecast/forecast-v0.js'
import { inferLifecycle, type LifecycleEvent } from '../lifecycle/lifecycle-v0.js'
import type { GiteaIssue } from '../gitea/types.js'
/** Global sample size at which the fit takes over from the cold-start priors. */
export const COLD_START_THRESHOLD = 20
/** Minimum per-bucket sample before that bucket earns its own fit. */
export const CALIBRATION_BUCKET_FLOOR = 3
/** Fallback spread when a group is too small to estimate one. */
const DEFAULT_SIGMA = 0.4
/** One closed issue's estimate vs its inferred actual. */
export interface CalibrationSample {
issue: number
estimateDays: number
actualWorkingDays: number
bucket: number
person: string | null
}
export interface BucketFit extends LognormalPrior {
n: number
}
export interface PersonBias {
/** Additive to global mu (log space). */
biasMu: number
n: number
}
export interface CalibrationModel {
/** Closed issues with an estimate + a resolvable actual. */
n: number
/** true while n < COLD_START_THRESHOLD — forecast keeps the code priors. */
coldStart: boolean
global: LognormalPrior
byBucket: Record<number, BucketFit>
byPerson: Record<string, PersonBias>
}
function mean(xs: number[]): number {
return xs.reduce((a, b) => a + b, 0) / xs.length
}
/** Sample standard deviation; falls back to DEFAULT_SIGMA below 2 points. */
function stddev(xs: number[], mu: number): number {
if (xs.length < 2) return DEFAULT_SIGMA
const variance = xs.reduce((a, x) => a + (x - mu) ** 2, 0) / (xs.length - 1)
return Math.sqrt(variance) || DEFAULT_SIGMA
}
/** Fit a calibration model from estimate-vs-actual samples. Pure. */
export function fitCalibration(samples: CalibrationSample[]): CalibrationModel {
const usable = samples.filter((s) => s.estimateDays > 0 && s.actualWorkingDays > 0)
const n = usable.length
const coldStart = n < COLD_START_THRESHOLD
const logRatios = usable.map((s) => Math.log(s.actualWorkingDays / s.estimateDays))
const globalMu = n ? mean(logRatios) : 0
const global: LognormalPrior = { mu: globalMu, sigma: n ? stddev(logRatios, globalMu) : DEFAULT_SIGMA }
const byBucket: Record<number, BucketFit> = {}
const byPerson: Record<string, PersonBias> = {}
const groups = new Map<number, number[]>()
const people = new Map<string, number[]>()
for (const s of usable) {
const lr = Math.log(s.actualWorkingDays / s.estimateDays)
;(groups.get(s.bucket) ?? groups.set(s.bucket, []).get(s.bucket)!).push(lr)
if (s.person) (people.get(s.person) ?? people.set(s.person, []).get(s.person)!).push(lr)
}
for (const [bucket, lrs] of groups) {
if (lrs.length < CALIBRATION_BUCKET_FLOOR) continue
const mu = mean(lrs)
byBucket[bucket] = { mu, sigma: stddev(lrs, mu), n: lrs.length }
}
for (const [person, lrs] of people) {
if (lrs.length < CALIBRATION_BUCKET_FLOOR) continue
byPerson[person] = { biasMu: mean(lrs) - globalMu, n: lrs.length }
}
return { n, coldStart, global, byBucket, byPerson }
}
/** The subset of a model `forecast` consumes. */
export function toDurationModel(model: CalibrationModel): DurationModel {
const byBucket: Record<number, LognormalPrior> = {}
for (const [bucket, fit] of Object.entries(model.byBucket)) {
byBucket[Number(bucket)] = { mu: fit.mu, sigma: fit.sigma }
}
return { coldStart: model.coldStart, global: model.global, byBucket }
}
/**
* Extract calibration samples from the closed backlog: each closed issue that
* carries an estimate and yields an inferred actual working duration.
*/
export function calibrationSamples(
issues: GiteaIssue[],
timelines: Record<number, LifecycleEvent[]>,
asOf: Date,
): CalibrationSample[] {
const out: CalibrationSample[] = []
for (const issue of issues) {
if (issue.state !== 'closed') continue
const estimateDays = issue.facts.estimateDays
if (estimateDays == null) continue
const inf = inferLifecycle(issue, timelines[issue.number] ?? [], asOf)
if (inf.actualWorkingDays == null || inf.actualWorkingDays <= 0) continue
out.push({
issue: issue.number,
estimateDays,
actualWorkingDays: inf.actualWorkingDays,
bucket: nearestBucket(estimateDays),
person: issue.assignee,
})
}
return out
}

View File

@@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest'
import { describeChange, type IssueChange, planIssueChange } from './apply-changes-v0.js'
describe('planIssueChange', () => {
it('swaps the estimate label, keeping non-axis labels', () => {
const plan = planIssueChange(['est/2d', 'p/1', 'backend'], { kind: 'reestimate', issue: 1, estimate: 'est/5d' })
expect(plan.removed).toEqual(['est/2d'])
expect(plan.added).toEqual(['est/5d'])
expect(plan.labels).toEqual(['p/1', 'backend', 'est/5d'])
expect(plan.noop).toBe(false)
})
it('adds an estimate when none was set', () => {
const plan = planIssueChange(['p/2'], { kind: 'reestimate', issue: 1, estimate: 'est/1d' })
expect(plan.removed).toEqual([])
expect(plan.added).toEqual(['est/1d'])
expect(plan.labels).toEqual(['p/2', 'est/1d'])
})
it('clears the axis when the target is null', () => {
const plan = planIssueChange(['est/3d', 'p/1'], { kind: 'reprioritize', issue: 1, priority: null })
expect(plan.removed).toEqual(['p/1'])
expect(plan.added).toEqual([])
expect(plan.labels).toEqual(['est/3d'])
})
it('is a noop when the target already holds the axis alone', () => {
const plan = planIssueChange(['est/2d', 'p/1'], { kind: 'reestimate', issue: 1, estimate: 'est/2d' })
expect(plan.noop).toBe(true)
expect(plan.labels).toEqual(['p/1', 'est/2d'])
})
it('cleans up a duplicated axis down to the target', () => {
// two est/* labels — the change collapses to one
const plan = planIssueChange(['est/2d', 'est/5d', 'p/1'], { kind: 'reestimate', issue: 1, estimate: 'est/5d' })
expect(plan.removed).toEqual(['est/2d'])
expect(plan.added).toEqual([]) // est/5d already present
expect(plan.labels).toEqual(['p/1', 'est/5d'])
expect(plan.noop).toBe(false)
})
it('reprioritize only touches the priority axis', () => {
const plan = planIssueChange(['est/2d', 'p/3'], { kind: 'reprioritize', issue: 1, priority: 'p/1' })
expect(plan.labels).toEqual(['est/2d', 'p/1'])
})
it('describeChange renders the diff', () => {
const change: IssueChange = { kind: 'reestimate', issue: 1, estimate: 'est/5d' }
expect(describeChange(planIssueChange(['est/2d'], change))).toBe('est/2d → est/5d')
expect(describeChange(planIssueChange(['p/1'], { kind: 'reprioritize', issue: 1, priority: null }))).toBe('p/1 → ∅')
expect(describeChange(planIssueChange(['est/5d'], change))).toBe('no change')
})
})

View File

@@ -0,0 +1,59 @@
/**
* Apply-changes, v0 — the write path's planning half. Estimates and priority
* live as exclusive label axes (`est/*`, `p/*`); a change swaps the axis label.
* This computes the resulting label set + a human-readable diff *purely*, so the
* UI can show a propose-approve consequence before the write and tests can pin
* the semantics. The actual PUT (name→id resolution + network) is the bridge's
* job — additive here, never assumed.
*/
import {
type EstimateLabel,
ESTIMATE_LABELS,
type PriorityLabel,
PRIORITY_LABELS,
} from '../labels/label-schema.js'
export type IssueChange =
| { kind: 'reestimate'; issue: number; estimate: EstimateLabel | null }
| { kind: 'reprioritize'; issue: number; priority: PriorityLabel | null }
export interface LabelPlan {
/** The full resulting label-name set (order: kept labels, then the new axis label). */
labels: string[]
/** Axis labels being added (0 or 1). */
added: string[]
/** Axis labels being removed (includes clearing a duplicated axis). */
removed: string[]
/** true when the change would leave the labels unchanged. */
noop: boolean
}
function axisFor(change: IssueChange): { labels: readonly string[]; target: string | null } {
return change.kind === 'reestimate'
? { labels: ESTIMATE_LABELS, target: change.estimate }
: { labels: PRIORITY_LABELS, target: change.priority }
}
/**
* Plan the label mutation for a single change. Removes every label on the
* change's axis except the target, adds the target if absent. Setting the axis
* to null clears it. Cleans up a duplicated axis (two `est/*`) as a side effect.
*/
export function planIssueChange(current: string[], change: IssueChange): LabelPlan {
const { labels: axis, target } = axisFor(change)
const onAxis = current.filter((l) => axis.includes(l))
const removed = onAxis.filter((l) => l !== target)
const added = target && !current.includes(target) ? [target] : []
const kept = current.filter((l) => !axis.includes(l))
const labels = target ? [...kept, target] : kept
return { labels, added, removed, noop: added.length === 0 && removed.length === 0 }
}
/** A short "est/2d → est/3d" (or "+p/1" / "est/5d") summary for the confirm UI. */
export function describeChange(plan: LabelPlan): string {
if (plan.noop) return 'no change'
const from = plan.removed.length ? plan.removed.join(', ') : '∅'
const to = plan.added.length ? plan.added.join(', ') : '∅'
return `${from}${to}`
}

View File

@@ -0,0 +1,123 @@
import { describe, expect, it } from 'vitest'
import { type DependencyEdge, type SchedulableIssue } from '../scheduler/scheduler-v0.js'
import { COLD_START_PRIORS, forecast, priorForEstimate } from './forecast-v0.js'
function issue(number: number, over: Partial<SchedulableIssue> = {}): SchedulableIssue {
return { number, title: `#${number}`, labels: [], estimateDays: 2, priority: 2, ...over }
}
describe('priorForEstimate', () => {
it('returns the exact prior for a bucket day count', () => {
expect(priorForEstimate(3)).toBe(COLD_START_PRIORS[3])
expect(priorForEstimate(8)).toBe(COLD_START_PRIORS[8])
})
it('snaps a non-bucket estimate to the nearest bucket', () => {
expect(priorForEstimate(4)).toBe(COLD_START_PRIORS[3]) // tie → smaller bucket
expect(priorForEstimate(6)).toBe(COLD_START_PRIORS[5])
expect(priorForEstimate(100)).toBe(COLD_START_PRIORS[8])
})
it('every prior is pessimistic (median actual runs longer than the estimate)', () => {
for (const p of Object.values(COLD_START_PRIORS)) expect(p.mu).toBeGreaterThan(0)
})
})
describe('forecast', () => {
const scope = [
issue(1, { estimateDays: 2 }),
issue(2, { estimateDays: 3 }),
issue(3, { estimateDays: 1 }),
]
it('is reproducible: same seed → identical result', () => {
const a = forecast(scope, [], { trials: 500, seed: 42 })
const b = forecast(scope, [], { trials: 500, seed: 42 })
expect(a).toEqual(b)
})
it('percentiles are ordered p50 <= p80 <= p95', () => {
const f = forecast(scope, [], { trials: 3000 })
expect(f.p50Day).toBeLessThanOrEqual(f.p80Day)
expect(f.p80Day).toBeLessThanOrEqual(f.p95Day)
})
it('the burn-up curve is monotonic in both fraction and day', () => {
const f = forecast(scope, [], { trials: 3000 })
expect(f.curve).toHaveLength(3)
for (let i = 1; i < f.curve.length; i++) {
expect(f.curve[i].fraction).toBeGreaterThan(f.curve[i - 1].fraction)
expect(f.curve[i].p50Day).toBeGreaterThan(f.curve[i - 1].p50Day)
}
expect(f.curve.at(-1)!.fraction).toBeCloseTo(1)
})
it('lo/mid/hi are ordered within each cone point', () => {
const f = forecast(scope, [], { trials: 3000 })
for (const pt of f.curve) {
expect(pt.p10Day).toBeLessThanOrEqual(pt.p50Day)
expect(pt.p50Day).toBeLessThanOrEqual(pt.p90Day)
}
})
it('the median landing runs longer than the raw estimate sum (pessimism)', () => {
const rawSum = 2 + 3 + 1
const f = forecast(scope, [], { trials: 4000 })
expect(f.p50Day).toBeGreaterThan(rawSum)
})
it('reports scope and cold-start honestly', () => {
const f = forecast(scope, [], { trials: 100 })
expect(f.scope).toBe(3)
expect(f.coldStart).toBe(true)
})
it('a dependency cycle yields an empty, zeroed forecast', () => {
const edges: DependencyEdge[] = [
{ issue: 1, dependsOn: 2 },
{ issue: 2, dependsOn: 1 },
]
const f = forecast([issue(1), issue(2)], edges, { trials: 100 })
expect(f.scope).toBe(0)
expect(f.curve).toEqual([])
expect(f.p80Day).toBe(0)
})
it('an empty scope forecasts nothing', () => {
const f = forecast([], [], { trials: 100 })
expect(f.scope).toBe(0)
expect(f.curve).toEqual([])
})
it('unestimated issues fall back to the default-estimate prior', () => {
const f = forecast([issue(1, { estimateDays: null }), issue(2, { estimateDays: null })], [], {
trials: 500,
})
expect(f.scope).toBe(2)
expect(f.p50Day).toBeGreaterThan(0)
})
it('a cold-start model changes nothing — the code priors still drive it', () => {
const priors = forecast(scope, [], { trials: 1000, seed: 7 })
const cold = forecast(scope, [], {
trials: 1000,
seed: 7,
model: { coldStart: true, global: { mu: 5, sigma: 0.1 }, byBucket: {} },
})
expect(cold.coldStart).toBe(true)
expect(cold.p50Day).toBeCloseTo(priors.p50Day, 6)
})
it('a fitted model drives the sim once past cold-start', () => {
// an optimistic fit (mu < 0, tight sigma) should land the scope sooner than the pessimistic priors
const priors = forecast(scope, [], { trials: 2000, seed: 7 })
const fitted = forecast(scope, [], {
trials: 2000,
seed: 7,
model: { coldStart: false, global: { mu: -0.2, sigma: 0.1 }, byBucket: {} },
})
expect(fitted.coldStart).toBe(false)
expect(fitted.p50Day).toBeLessThan(priors.p50Day)
})
})

View File

@@ -0,0 +1,193 @@
/**
* Monte Carlo forecast, v0. The LLM never does this — it's plain, seeded,
* reproducible code (evidence-based scheduling). It samples an actual duration
* per open issue from a lognormal prior, walks the scheduler's deterministic
* order on a single serial worker, and reads percentiles off the resulting
* completion-day distribution.
*
* v0 simplifications (each a later slice, not a hack):
* - single serial worker; per-person capacity + parallelism is #8.
* - cold-start priors only; the team's empirical calibration fit lands at
* n >= 20 closed-with-estimate issues (#5 supplies the actuals).
* - forecast covers remaining (open) scope from today forward; the historical
* burn-up "actual" polyline needs lifecycle event dates (#5).
*/
import {
type DependencyEdge,
schedule,
type SchedulableIssue,
} from '../scheduler/scheduler-v0.js'
export interface LognormalPrior {
/** Median log-ratio: sampled median duration = estimate * e^mu. */
mu: number
/** Spread of log(actual / estimate). */
sigma: number
}
/**
* Code-resident cold-start priors (D3). Lognormal on log(actual / estimate):
* sampled actual = estimateDays * exp(N(mu, sigma)). mu > 0 encodes the honest
* fact that actuals run long; sigma shrinks as tickets grow (a snag doubles a
* 1-day task but barely dents an 8-day one). The team's fitted model replaces
* these at n >= 20 (see calibration model in pm-state.md).
*/
export const COLD_START_PRIORS: Record<number, LognormalPrior> = {
1: { mu: 0.25, sigma: 0.55 },
2: { mu: 0.22, sigma: 0.48 },
3: { mu: 0.2, sigma: 0.44 },
5: { mu: 0.18, sigma: 0.4 },
8: { mu: 0.16, sigma: 0.36 },
}
export const PRIOR_BUCKETS = [1, 2, 3, 5, 8]
/** Nearest estimate bucket (ties resolve to the smaller bucket). */
export function nearestBucket(days: number): number {
let best = PRIOR_BUCKETS[0]
for (const b of PRIOR_BUCKETS) {
if (Math.abs(b - days) < Math.abs(best - days)) best = b
}
return best
}
/** The cold-start prior for the bucket nearest to `days`. */
export function priorForEstimate(days: number): LognormalPrior {
return COLD_START_PRIORS[nearestBucket(days)]
}
/** The lognormal parameters `forecast` needs, per estimate bucket. */
export interface DurationModel {
coldStart: boolean
/** Fallback params (used when a bucket lacks its own fit). */
global: LognormalPrior
/** Per-bucket fitted params; missing buckets fall back to `global`. */
byBucket: Record<number, LognormalPrior>
}
export interface ForecastOptions {
/** Simulation trials. More = smoother tails, linear cost. */
trials?: number
/** PRNG seed. Fixed by default so a forecast is reproducible. */
seed?: number
/**
* Fitted duration model. When present and not cold-start, its params drive
* the sim; otherwise the code-resident cold-start priors do.
*/
model?: DurationModel
}
/** Resolve the lognormal params for an estimate, preferring a fitted model. */
export function durationParams(days: number, model?: DurationModel): LognormalPrior {
if (model && !model.coldStart) {
return model.byBucket[nearestBucket(days)] ?? model.global
}
return priorForEstimate(days)
}
export interface BurnUpPoint {
/** Cumulative fraction of remaining scope complete (0 < f <= 1]. */
fraction: number
/** Working-day offset from today at the p10 / p50 / p90 of reaching it. */
p10Day: number
p50Day: number
p90Day: number
}
export interface Forecast {
/** Open issues in scope (== scheduled count). */
scope: number
trials: number
/** true while code priors drive the sim; false once the empirical fit is in (v1). */
coldStart: boolean
/** Working-day offsets from today for the whole scope landing. */
p50Day: number
p80Day: number
p95Day: number
/** Burn-up cone, one point per scheduled issue, fraction ascending. */
curve: BurnUpPoint[]
}
const DEFAULT_TRIALS = 2000
const DEFAULT_SEED = 0x9e3779b9
/** mulberry32 — small, fast, seedable PRNG (no reliance on Math.random). */
function mulberry32(seed: number): () => number {
let a = seed >>> 0
return () => {
a = (a + 0x6d2b79f5) | 0
let t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/** BoxMuller standard normal from a uniform PRNG. */
function standardNormal(rng: () => number): number {
let u1 = rng()
const u2 = rng()
if (u1 < 1e-12) u1 = 1e-12
return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2)
}
function percentile(sortedAsc: number[], q: number): number {
const idx = Math.min(sortedAsc.length - 1, Math.max(0, Math.round(q * (sortedAsc.length - 1))))
return sortedAsc[idx]
}
/**
* Monte Carlo over the deterministic schedule order. Order is fixed (it's
* derived from estimate labels + dependencies, not sampled), so only durations
* vary across trials — the cone stretches, it never reorders.
*/
export function forecast(
issues: SchedulableIssue[],
edges: DependencyEdge[],
options: ForecastOptions = {},
): Forecast {
const trials = options.trials ?? DEFAULT_TRIALS
const seed = options.seed ?? DEFAULT_SEED
const coldStart = options.model ? options.model.coldStart : true
const order = schedule(issues, edges).items // empty when a dependency cycle exists
const n = order.length
if (n === 0) {
return { scope: 0, trials, coldStart, p50Day: 0, p80Day: 0, p95Day: 0, curve: [] }
}
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.
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 curve: BurnUpPoint[] = endByRank.map((row, k) => {
const sorted = [...row].sort((a, b) => a - b)
return {
fraction: (k + 1) / n,
p10Day: percentile(sorted, 0.1),
p50Day: percentile(sorted, 0.5),
p90Day: percentile(sorted, 0.9),
}
})
const total = [...endByRank[n - 1]].sort((a, b) => a - b)
return {
scope: n,
trials,
coldStart,
p50Day: percentile(total, 0.5),
p80Day: percentile(total, 0.8),
p95Day: percentile(total, 0.95),
curve,
}
}

View File

@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest' import { describe, expect, it } from 'vitest'
import { createGiteaClient, normalizeIssue } from './client.js' import { createGiteaClient, normalizeIssue, normalizeTimeline } from './client.js'
import { GiteaApiError, type FetchLike, type GiteaConfig, type GiteaRequestInit } from './types.js' import { GiteaApiError, type FetchLike, type GiteaConfig, type GiteaRequestInit } from './types.js'
const CONFIG: GiteaConfig = { const CONFIG: GiteaConfig = {
@@ -44,6 +44,31 @@ function stubFetch(body: unknown, status = 200): {
return { fetch, calls } return { fetch, calls }
} }
describe('normalizeTimeline', () => {
it('maps known gitea event types to lifecycle signals and drops the rest', () => {
const events = normalizeTimeline([
{ type: 'label', created_at: '2026-01-06T09:00:00Z' },
{ type: 'milestone', created_at: '2026-01-06T09:05:00Z' },
{ type: 'commit_ref', created_at: '2026-01-07T12:00:00Z' },
{ type: 'pull_ref', created_at: '2026-01-08T12:00:00Z' },
{ type: 'comment', created_at: '2026-01-08T13:00:00Z' }, // dropped
{ type: 'add_dependency', created_at: '2026-01-08T14:00:00Z' }, // dropped
{ type: 'close', created_at: '2026-01-12T09:00:00Z' },
])
expect(events).toEqual([
{ type: 'triage', at: '2026-01-06T09:00:00Z' },
{ type: 'triage', at: '2026-01-06T09:05:00Z' },
{ type: 'commit', at: '2026-01-07T12:00:00Z' },
{ type: 'pull', at: '2026-01-08T12:00:00Z' },
{ type: 'close', at: '2026-01-12T09:00:00Z' },
])
})
it('skips events missing a timestamp', () => {
expect(normalizeTimeline([{ type: 'commit_ref', created_at: '' }])).toEqual([])
})
})
describe('createGiteaClient.getIssue', () => { describe('createGiteaClient.getIssue', () => {
it('returns a normalized, typed issue from canned JSON', async () => { it('returns a normalized, typed issue from canned JSON', async () => {
const { fetch } = stubFetch(RAW_ISSUE) const { fetch } = stubFetch(RAW_ISSUE)
@@ -98,6 +123,29 @@ describe('createGiteaClient.getIssue', () => {
) )
}) })
it('setIssueLabels PUTs the label ids to the issue labels endpoint', async () => {
const { fetch, calls } = stubFetch(null, 204)
await createGiteaClient(CONFIG, fetch).setIssueLabels(9, [3, 7])
expect(calls).toHaveLength(1)
expect(calls[0].url).toBe('https://gitea.stephenmann.io/api/v1/repos/christian/commitea/issues/9/labels')
expect(calls[0].init?.method).toBe('PUT')
expect(calls[0].init?.headers?.['Content-Type']).toBe('application/json')
expect(JSON.parse(calls[0].init?.body ?? '{}')).toEqual({ labels: [3, 7] })
})
it('listLabels returns id+name pairs', async () => {
const { fetch } = stubFetch([
{ id: 3, name: 'est/2d', color: 'fff' },
{ id: 7, name: 'p/1', color: '000' },
])
const labels = await createGiteaClient(CONFIG, fetch).listLabels()
expect(labels).toEqual([
{ id: 3, name: 'est/2d' },
{ id: 7, name: 'p/1' },
])
})
it('throws GiteaApiError carrying status + body on a non-2xx response', async () => { it('throws GiteaApiError carrying status + body on a non-2xx response', async () => {
const { fetch } = stubFetch('not found', 404) const { fetch } = stubFetch('not found', 404)
const client = createGiteaClient(CONFIG, fetch) const client = createGiteaClient(CONFIG, fetch)
@@ -107,6 +155,50 @@ describe('createGiteaClient.getIssue', () => {
}) })
}) })
describe('createGiteaClient.listIssues', () => {
/** Stub fetch that pages 50-at-a-time and records the paths it was asked for. */
function pagedFetch(pages: unknown[][]): { fetch: FetchLike; paths: string[] } {
const paths: string[] = []
const fetch: FetchLike = (url) => {
paths.push(url)
const page = Number(/[?&]page=(\d+)/.exec(url)?.[1] ?? '1')
const body = pages[page - 1] ?? []
return Promise.resolve({
ok: true,
status: 200,
json: () => Promise.resolve(body),
text: () => Promise.resolve(''),
})
}
return { fetch, paths }
}
it('walks every page until a short page ends it', async () => {
const full = Array.from({ length: 50 }, (_, i) => ({ ...RAW_ISSUE, number: i + 1 }))
const tail = [{ ...RAW_ISSUE, number: 51 }]
const { fetch, paths } = pagedFetch([full, tail])
const issues = await createGiteaClient(CONFIG, fetch).listIssues()
expect(issues).toHaveLength(51)
expect(paths).toHaveLength(2) // stopped after the short second page
expect(paths[0]).toContain('/issues?type=issues&state=all&page=1&limit=50')
})
it('excludes pull requests even if the API returns them', async () => {
const { fetch } = pagedFetch([
[{ ...RAW_ISSUE, number: 1 }, { ...RAW_ISSUE, number: 2, pull_request: { url: 'x' } }],
])
const issues = await createGiteaClient(CONFIG, fetch).listIssues()
expect(issues.map((i) => i.number)).toEqual([1])
})
it('passes the state filter through', async () => {
const { fetch, paths } = pagedFetch([[]])
await createGiteaClient(CONFIG, fetch).listIssues({ state: 'open' })
expect(paths[0]).toContain('state=open')
})
})
describe('normalizeIssue', () => { describe('normalizeIssue', () => {
it('defaults missing labels/assignees/body to empty and maps a closed state', () => { it('defaults missing labels/assignees/body to empty and maps a closed state', () => {
const issue = normalizeIssue({ const issue = normalizeIssue({

View File

@@ -1,16 +1,20 @@
/** /**
* Gitea read client. One method for now — `getIssue` — proving the vertical * Gitea read client. Config + injected fetch → typed, normalized domain
* slice end to end: config + injected fetch → typed, normalized `GiteaIssue` * objects with scheduler facts precomputed. `getIssue` proved the vertical
* with scheduler facts precomputed. Later reconcile work (P1-4) layers list * slice (P1-1); `listIssues`/`listMilestones` are the reconcile reads (P1-4)
* reads on the same `request` seam. * layered on the same `request` seam. Pagination is handled here so callers
* get the full set.
*/ */
import { type LifecycleEvent, type LifecycleEventType } from '../lifecycle/lifecycle-v0.js'
import { extractLabelFacts } from '../labels/label-schema.js' import { extractLabelFacts } from '../labels/label-schema.js'
import { import {
GiteaApiError, GiteaApiError,
type FetchLike, type FetchLike,
type GiteaConfig, type GiteaConfig,
type GiteaIssue, type GiteaIssue,
type GiteaLabel,
type GiteaMilestone,
type GiteaMilestoneRef, type GiteaMilestoneRef,
} from './types.js' } from './types.js'
@@ -39,11 +43,66 @@ interface RawIssue {
updated_at: string updated_at: string
closed_at: string | null closed_at: string | null
html_url: string html_url: string
/** Present (non-null) when the row is actually a pull request. */
pull_request?: unknown
}
interface RawMilestoneFull {
id: number
title: string
description: string | null
due_on: string | null
state: string
open_issues: number
closed_issues: number
}
/** The subset of a gitea timeline comment we read. */
interface RawTimelineComment {
type: string
created_at: string
}
/** gitea timeline `type` → our lifecycle signal. Unmapped types are dropped. */
const TIMELINE_TYPE_MAP: Record<string, LifecycleEventType> = {
label: 'triage',
milestone: 'triage',
assignees: 'triage',
commit_ref: 'commit',
pull_ref: 'pull',
close: 'close',
reopen: 'reopen',
}
/** Map a raw gitea timeline to normalized lifecycle events. Pure. */
export function normalizeTimeline(raw: RawTimelineComment[]): LifecycleEvent[] {
const out: LifecycleEvent[] = []
for (const c of raw) {
const type = TIMELINE_TYPE_MAP[c.type]
if (type && c.created_at) out.push({ type, at: c.created_at })
}
return out
}
export interface ListIssuesOptions {
/** @default 'all' */
state?: 'open' | 'closed' | 'all'
} }
export interface GiteaClient { export interface GiteaClient {
/** Fetch one issue by its per-repo index, normalized. */ /** Fetch one issue by its per-repo index, normalized. */
getIssue(index: number): Promise<GiteaIssue> getIssue(index: number): Promise<GiteaIssue>
/** Fetch every issue (all pages), pull requests excluded. */
listIssues(opts?: ListIssuesOptions): Promise<GiteaIssue[]>
/** Fetch every milestone (all pages). */
listMilestones(): Promise<GiteaMilestone[]>
/** The issue indices this issue depends on (its blockers). */
getIssueDependencies(index: number): Promise<number[]>
/** Normalized lifecycle events for one issue (all pages of its timeline). */
getIssueTimeline(index: number): Promise<LifecycleEvent[]>
/** Every label defined on the repo (id + name), for name→id resolution. */
listLabels(): Promise<GiteaLabel[]>
/** Replace an issue's entire label set with the given label ids. Write. */
setIssueLabels(index: number, labelIds: number[]): Promise<void>
} }
/** Map raw gitea issue JSON to the normalized domain shape. Pure. */ /** Map raw gitea issue JSON to the normalized domain shape. Pure. */
@@ -71,27 +130,97 @@ export function normalizeIssue(raw: RawIssue): GiteaIssue {
} }
} }
/** Map a raw milestone resource to the normalized shape. Pure. */
export function normalizeMilestone(raw: RawMilestoneFull): GiteaMilestone {
return {
id: raw.id,
title: raw.title,
description: raw.description ?? '',
dueOn: raw.due_on,
state: raw.state === 'closed' ? 'closed' : 'open',
openIssues: raw.open_issues,
closedIssues: raw.closed_issues,
}
}
const PAGE_LIMIT = 50
export function createGiteaClient(config: GiteaConfig, fetchImpl: FetchLike): GiteaClient { export function createGiteaClient(config: GiteaConfig, fetchImpl: FetchLike): GiteaClient {
const apiBase = `${config.baseUrl.replace(/\/+$/, '')}/api/v1` const apiBase = `${config.baseUrl.replace(/\/+$/, '')}/api/v1`
const repoBase = `${apiBase}/repos/${config.owner}/${config.repo}` const repoBase = `${apiBase}/repos/${config.owner}/${config.repo}`
async function request(path: string): Promise<unknown> { async function request(path: string, init?: { method?: string; body?: unknown }): Promise<unknown> {
const method = init?.method ?? 'GET'
const hasBody = init?.body !== undefined
const res = await fetchImpl(`${repoBase}${path}`, { const res = await fetchImpl(`${repoBase}${path}`, {
method,
headers: { headers: {
Authorization: `token ${config.token}`, Authorization: `token ${config.token}`,
Accept: 'application/json', Accept: 'application/json',
...(hasBody ? { 'Content-Type': 'application/json' } : {}),
}, },
body: hasBody ? JSON.stringify(init!.body) : undefined,
}) })
if (!res.ok) { if (!res.ok) {
const body = await res.text().catch(() => '') const body = await res.text().catch(() => '')
throw new GiteaApiError(res.status, `GET ${path} failed (${res.status})`, body) throw new GiteaApiError(res.status, `${method} ${path} failed (${res.status})`, body)
}
// writes may reply 204 No Content
return res.status === 204 ? null : res.json()
}
/** Follow gitea's page-limit pagination until a short page is returned. */
async function requestAll<T>(build: (page: number) => string): Promise<T[]> {
const out: T[] = []
for (let page = 1; ; page++) {
const batch = (await request(build(page))) as T[]
out.push(...batch)
if (batch.length < PAGE_LIMIT) return out
} }
return res.json()
} }
return { return {
async getIssue(index) { async getIssue(index) {
return normalizeIssue((await request(`/issues/${index}`)) as RawIssue) return normalizeIssue((await request(`/issues/${index}`)) as RawIssue)
}, },
async listIssues(opts) {
const state = opts?.state ?? 'all'
const raw = await requestAll<RawIssue>(
(page) => `/issues?type=issues&state=${state}&page=${page}&limit=${PAGE_LIMIT}`,
)
// `type=issues` should exclude PRs, but guard anyway.
return raw.filter((r) => r.pull_request == null).map(normalizeIssue)
},
async listMilestones() {
const raw = await requestAll<RawMilestoneFull>(
(page) => `/milestones?state=all&page=${page}&limit=${PAGE_LIMIT}`,
)
return raw.map(normalizeMilestone)
},
async getIssueDependencies(index) {
const raw = (await request(`/issues/${index}/dependencies`)) as { number: number }[]
return raw.map((d) => d.number)
},
async getIssueTimeline(index) {
const raw = await requestAll<RawTimelineComment>(
(page) => `/issues/${index}/timeline?page=${page}&limit=${PAGE_LIMIT}`,
)
return normalizeTimeline(raw)
},
async listLabels() {
const raw = await requestAll<{ id: number; name: string }>(
(page) => `/labels?page=${page}&limit=${PAGE_LIMIT}`,
)
return raw.map((l) => ({ id: l.id, name: l.name }))
},
async setIssueLabels(index, labelIds) {
await request(`/issues/${index}/labels`, { method: 'PUT', body: { labels: labelIds } })
},
} }
} }

View File

@@ -35,6 +35,12 @@ export interface GiteaHttpResponse {
export type FetchLike = (url: string, init?: GiteaRequestInit) => Promise<GiteaHttpResponse> export type FetchLike = (url: string, init?: GiteaRequestInit) => Promise<GiteaHttpResponse>
/** A repo label — just the id + name we need for name→id resolution. */
export interface GiteaLabel {
id: number
name: string
}
/** Milestone as referenced from an issue (not the full milestone resource). */ /** Milestone as referenced from an issue (not the full milestone resource). */
export interface GiteaMilestoneRef { export interface GiteaMilestoneRef {
id: number id: number
@@ -43,6 +49,17 @@ export interface GiteaMilestoneRef {
dueOn: string | null dueOn: string | null
} }
/** A milestone resource with its open/closed counts. */
export interface GiteaMilestone {
id: number
title: string
description: string
dueOn: string | null
state: 'open' | 'closed'
openIssues: number
closedIssues: number
}
/** /**
* Normalized issue — camelCase, label names flattened, scheduler-facing * Normalized issue — camelCase, label names flattened, scheduler-facing
* `facts` precomputed via `extractLabelFacts`. This is the domain shape the * `facts` precomputed via `extractLabelFacts`. This is the domain shape the

View File

@@ -9,14 +9,72 @@ export {
} from './labels/label-schema.js' } from './labels/label-schema.js'
export type { EstimateLabel, LabelFacts, PriorityLabel } from './labels/label-schema.js' export type { EstimateLabel, LabelFacts, PriorityLabel } from './labels/label-schema.js'
export { createGiteaClient, normalizeIssue } from './gitea/client.js' export { createGiteaClient, normalizeIssue, normalizeMilestone, normalizeTimeline } from './gitea/client.js'
export type { GiteaClient } from './gitea/client.js' export type { GiteaClient, ListIssuesOptions } from './gitea/client.js'
export { GiteaApiError } from './gitea/types.js' export { GiteaApiError } from './gitea/types.js'
export type { export type {
FetchLike, FetchLike,
GiteaConfig, GiteaConfig,
GiteaHttpResponse, GiteaHttpResponse,
GiteaIssue, GiteaIssue,
GiteaLabel,
GiteaMilestone,
GiteaMilestoneRef, GiteaMilestoneRef,
GiteaRequestInit, GiteaRequestInit,
} from './gitea/types.js' } from './gitea/types.js'
export { describeChange, planIssueChange } from './changes/apply-changes-v0.js'
export type { IssueChange, LabelPlan } from './changes/apply-changes-v0.js'
export {
inferColumnV0,
inferLifecycle,
LIFECYCLE_COLUMNS,
workingDaysBetween,
} from './lifecycle/lifecycle-v0.js'
export type {
LifecycleColumn,
LifecycleEvent,
LifecycleEventType,
LifecycleInference,
LifecycleStages,
} from './lifecycle/lifecycle-v0.js'
export { DEFAULT_ESTIMATE_DAYS, schedule, selectFocus } from './scheduler/scheduler-v0.js'
export type {
DependencyEdge,
Focus,
SchedulableIssue,
ScheduledItem,
SchedulePlan,
} from './scheduler/scheduler-v0.js'
export {
COLD_START_PRIORS,
durationParams,
forecast,
nearestBucket,
PRIOR_BUCKETS,
priorForEstimate,
} from './forecast/forecast-v0.js'
export type {
BurnUpPoint,
DurationModel,
Forecast,
ForecastOptions,
LognormalPrior,
} from './forecast/forecast-v0.js'
export {
CALIBRATION_BUCKET_FLOOR,
calibrationSamples,
COLD_START_THRESHOLD,
fitCalibration,
toDurationModel,
} from './calibration/calibration-v0.js'
export type {
BucketFit,
CalibrationModel,
CalibrationSample,
PersonBias,
} from './calibration/calibration-v0.js'

View File

@@ -0,0 +1,124 @@
import { describe, expect, it } from 'vitest'
import {
inferColumnV0,
inferLifecycle,
type LifecycleEvent,
workingDaysBetween,
} from './lifecycle-v0.js'
const base = { state: 'open' as const, labels: [] as string[], milestone: null }
describe('inferColumnV0', () => {
it('closed issues are done', () => {
expect(inferColumnV0({ ...base, state: 'closed' })).toBe('done')
})
it('open + labelled is triage', () => {
expect(inferColumnV0({ ...base, labels: ['est/2d'] })).toBe('triage')
})
it('open + milestoned is triage', () => {
expect(inferColumnV0({ ...base, milestone: { id: 6, title: 'P1', dueOn: null } })).toBe('triage')
})
it('open + bare is diagnosis', () => {
expect(inferColumnV0(base)).toBe('diagnosis')
})
it('never guesses steeping or review in v0', () => {
// even a closed, labelled, milestoned issue resolves to a real column, never the event-only ones
const col = inferColumnV0({ ...base, labels: ['est/2d', 'p/1'], milestone: { id: 6, title: 'P1', dueOn: null } })
expect(['steeping', 'review']).not.toContain(col)
})
})
describe('workingDaysBetween', () => {
it('counts weekdays in [start, end), excluding weekends', () => {
// Mon 2026-01-05 → Mon 2026-01-12 spans a full week = 5 working days
expect(workingDaysBetween(new Date('2026-01-05'), new Date('2026-01-12'))).toBe(5)
})
it('is 0 for same day or reversed', () => {
expect(workingDaysBetween(new Date('2026-01-05'), new Date('2026-01-05'))).toBe(0)
expect(workingDaysBetween(new Date('2026-01-12'), new Date('2026-01-05'))).toBe(0)
})
it('skips a weekend inside the interval', () => {
// Fri 2026-01-09 → Mon 2026-01-12: only Fri counts (Sat/Sun excluded) = 1
expect(workingDaysBetween(new Date('2026-01-09'), new Date('2026-01-12'))).toBe(1)
})
})
describe('inferLifecycle', () => {
const openBase = { ...base, createdAt: '2026-01-05T09:00:00Z', closedAt: null }
const asOf = new Date('2026-01-14T09:00:00Z')
const ev = (type: LifecycleEvent['type'], at: string): LifecycleEvent => ({ type, at })
it('bare open issue with no events is diagnosis', () => {
const inf = inferLifecycle(openBase, [], asOf)
expect(inf.column).toBe('diagnosis')
expect(inf.stages.opened).toBe(openBase.createdAt)
expect(inf.actualWorkingDays).toBeNull()
expect(inf.steepingDays).toBeNull()
})
it('a triage event (or a current label) moves it to triage', () => {
expect(inferLifecycle(openBase, [ev('triage', '2026-01-06T09:00:00Z')], asOf).column).toBe('triage')
expect(inferLifecycle({ ...openBase, labels: ['p/1'] }, [], asOf).column).toBe('triage')
})
it('a commit ref moves an open issue to steeping and counts its working age', () => {
const inf = inferLifecycle(
{ ...openBase, labels: ['est/2d'] },
[ev('triage', '2026-01-05T10:00:00Z'), ev('commit', '2026-01-07T12:00:00Z')],
asOf,
)
expect(inf.column).toBe('steeping')
expect(inf.stages.steeping).toBe('2026-01-07T12:00:00Z')
// Wed 2026-01-07 → Wed 2026-01-14 = 5 working days
expect(inf.steepingDays).toBe(5)
})
it('a pull ref outranks a commit ref → review', () => {
const inf = inferLifecycle(
openBase,
[ev('commit', '2026-01-07T12:00:00Z'), ev('pull', '2026-01-08T12:00:00Z')],
asOf,
)
expect(inf.column).toBe('review')
expect(inf.steepingDays).toBeNull() // only steeping issues carry an age
})
it('closed → done, with actual working time from work-start to close', () => {
const inf = inferLifecycle(
{ ...openBase, state: 'closed', closedAt: '2026-01-12T09:00:00Z' },
[ev('commit', '2026-01-07T09:00:00Z'), ev('pull', '2026-01-08T09:00:00Z'), ev('close', '2026-01-12T09:00:00Z')],
asOf,
)
expect(inf.column).toBe('done')
expect(inf.stages.done).toBe('2026-01-12T09:00:00Z')
// Wed 2026-01-07 → Mon 2026-01-12 = Wed,Thu,Fri = 3 working days
expect(inf.actualWorkingDays).toBe(3)
})
it('takes the earliest event of each kind for stage timestamps', () => {
const inf = inferLifecycle(
openBase,
[ev('commit', '2026-01-09T09:00:00Z'), ev('commit', '2026-01-07T09:00:00Z')],
asOf,
)
expect(inf.stages.steeping).toBe('2026-01-07T09:00:00Z')
})
it('falls back to opened when a closed issue has no work-start signal', () => {
const inf = inferLifecycle(
{ ...openBase, state: 'closed', closedAt: '2026-01-08T09:00:00Z' },
[ev('close', '2026-01-08T09:00:00Z')],
asOf,
)
// Mon 2026-01-05 → Thu 2026-01-08 = Mon,Tue,Wed = 3 working days
expect(inf.actualWorkingDays).toBe(3)
})
})

View File

@@ -0,0 +1,129 @@
/**
* Lifecycle inference.
*
* `inferColumnV0` places the coarse three columns from a single issues-list
* read (state/labels/milestone). `inferLifecycle` (#5) adds the issue timeline:
* first commit ref → Steeping, first PR ref → In review, close → Done — and
* derives the estimate-vs-actual working time that feeds calibration (D3).
*/
import type { GiteaIssue } from '../gitea/types.js'
export type LifecycleColumn = 'diagnosis' | 'triage' | 'steeping' | 'review' | 'done'
export const LIFECYCLE_COLUMNS: readonly LifecycleColumn[] = [
'diagnosis',
'triage',
'steeping',
'review',
'done',
]
/**
* Closed → done. Open with any human intent applied (a label or a milestone)
* → triage. Open and bare → diagnosis. Never returns steeping/review — that's
* `inferLifecycle`, which reads the event stream.
*/
export function inferColumnV0(issue: Pick<GiteaIssue, 'state' | 'labels' | 'milestone'>): LifecycleColumn {
if (issue.state === 'closed') return 'done'
const hasIntent = issue.labels.length > 0 || issue.milestone !== null
return hasIntent ? 'triage' : 'diagnosis'
}
/** A timeline signal, normalized from gitea's raw event stream. */
export type LifecycleEventType = 'triage' | 'commit' | 'pull' | 'close' | 'reopen'
export interface LifecycleEvent {
type: LifecycleEventType
/** ISO timestamp. */
at: string
}
/** Timestamps for the stages an issue has reached (absent = not yet reached). */
export interface LifecycleStages {
opened: string
/** First label / milestone / assignment. */
triaged?: string
/** First commit referencing the issue — work began. */
steeping?: string
/** First PR referencing the issue — in review. */
review?: string
/** Closed. */
done?: string
}
export interface LifecycleInference {
column: LifecycleColumn
stages: LifecycleStages
/**
* Working days from work-start (steeping → triaged → opened, first available)
* to done. Only for closed issues — this is the "actual" calibration learns
* from. null while open.
*/
actualWorkingDays: number | null
/** Working days the issue has been steeping (first commit → asOf); null unless currently steeping. */
steepingDays: number | null
}
const DAY_MS = 86_400_000
/**
* Whole working days (MonFri) in the half-open interval [start, end). Same day
* or reversed → 0. Day-granular by design — estimates are in days.
*/
export function workingDaysBetween(start: Date, end: Date): number {
const s = Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate())
const e = Date.UTC(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate())
if (e <= s) return 0
let count = 0
for (let t = s; t < e; t += DAY_MS) {
const dow = new Date(t).getUTCDay()
if (dow !== 0 && dow !== 6) count += 1
}
return count
}
/**
* The five-column inference. Column reflects the furthest stage still in play:
* closed → done; else an open PR ref → review; else a commit ref → steeping;
* else any triage signal (or a current label/milestone) → triage; else
* diagnosis. Stage timestamps are the earliest event of each kind.
*/
export function inferLifecycle(
issue: Pick<GiteaIssue, 'state' | 'labels' | 'milestone' | 'createdAt' | 'closedAt'>,
events: LifecycleEvent[],
asOf: Date,
): LifecycleInference {
const sorted = [...events].sort((a, b) => a.at.localeCompare(b.at))
const firstOf = (type: LifecycleEventType) => sorted.find((e) => e.type === type)?.at
const stages: LifecycleStages = { opened: issue.createdAt }
const triagedAt = firstOf('triage')
const steepingAt = firstOf('commit')
const reviewAt = firstOf('pull')
if (triagedAt) stages.triaged = triagedAt
if (steepingAt) stages.steeping = steepingAt
if (reviewAt) stages.review = reviewAt
const doneAt = issue.state === 'closed' ? (issue.closedAt ?? firstOf('close')) : undefined
if (doneAt) stages.done = doneAt
let column: LifecycleColumn
if (issue.state === 'closed') column = 'done'
else if (reviewAt) column = 'review'
else if (steepingAt) column = 'steeping'
else if (triagedAt || issue.labels.length > 0 || issue.milestone !== null) column = 'triage'
else column = 'diagnosis'
let actualWorkingDays: number | null = null
if (stages.done) {
const start = stages.steeping ?? stages.triaged ?? stages.opened
actualWorkingDays = workingDaysBetween(new Date(start), new Date(stages.done))
}
let steepingDays: number | null = null
if (column === 'steeping' && stages.steeping) {
steepingDays = workingDaysBetween(new Date(stages.steeping), asOf)
}
return { column, stages, actualWorkingDays, steepingDays }
}

View File

@@ -0,0 +1,99 @@
import { describe, expect, it } from 'vitest'
import { type DependencyEdge, schedule, type SchedulableIssue, selectFocus } from './scheduler-v0.js'
function issue(number: number, over: Partial<SchedulableIssue> = {}): SchedulableIssue {
return { number, title: `#${number}`, labels: [], estimateDays: 2, priority: 2, ...over }
}
describe('schedule', () => {
it('lays open issues out serially with cumulative start/finish', () => {
const plan = schedule([issue(1, { estimateDays: 2 }), issue(2, { estimateDays: 3 })], [])
expect(plan.cycle).toBeNull()
const byN = Object.fromEntries(plan.items.map((i) => [i.number, i]))
// total span = sum of durations, no overlap (single serial worker)
const spans = plan.items.map((i) => [i.startDay, i.endDay])
expect(spans).toContainEqual([0, expect.any(Number)])
expect(byN[1].durationDays + byN[2].durationDays).toBe(5)
expect(Math.max(...plan.items.map((i) => i.endDay))).toBe(5)
})
it('respects dependencies: a dependency is scheduled before its dependent', () => {
// #2 depends on #1
const edges: DependencyEdge[] = [{ issue: 2, dependsOn: 1 }]
const plan = schedule([issue(2, { priority: 1 }), issue(1, { priority: 4 })], edges)
const order = plan.items.map((i) => i.number)
expect(order.indexOf(1)).toBeLessThan(order.indexOf(2))
// #2 records #1 as a blocker; #1 records #2 as blocked
const two = plan.items.find((i) => i.number === 2)!
expect(two.blockedBy).toEqual([1])
const one = plan.items.find((i) => i.number === 1)!
expect(one.blocks).toEqual([2])
})
it('breaks ties among ready roots by priority, then estimate', () => {
const plan = schedule(
[issue(1, { priority: 3 }), issue(2, { priority: 1 }), issue(3, { priority: 2 })],
[],
)
expect(plan.items.map((i) => i.number)).toEqual([2, 3, 1])
})
it('detects a dependency cycle instead of looping', () => {
const edges: DependencyEdge[] = [
{ issue: 1, dependsOn: 2 },
{ issue: 2, dependsOn: 1 },
]
const plan = schedule([issue(1), issue(2)], edges)
expect(plan.items).toHaveLength(0)
expect(plan.cycle).not.toBeNull()
expect(plan.cycle!.sort()).toEqual([1, 2])
})
it('drops dependencies on out-of-scope (closed) issues', () => {
// #2 depends on #9 which isn't in scope → treated as satisfied
const plan = schedule([issue(2)], [{ issue: 2, dependsOn: 9 }])
expect(plan.cycle).toBeNull()
expect(plan.items.find((i) => i.number === 2)!.blockedBy).toEqual([])
})
it('marks the longest dependency chain critical', () => {
// chain 1→2→3 (each 3d = 9d) vs standalone 4 (2d): 1,2,3 critical, 4 not
const edges: DependencyEdge[] = [
{ issue: 2, dependsOn: 1 },
{ issue: 3, dependsOn: 2 },
]
const issues = [
issue(1, { estimateDays: 3 }),
issue(2, { estimateDays: 3 }),
issue(3, { estimateDays: 3 }),
issue(4, { estimateDays: 2 }),
]
const plan = schedule(issues, edges)
const crit = plan.items.filter((i) => i.critical).map((i) => i.number).sort()
expect(crit).toEqual([1, 2, 3])
expect(plan.items.find((i) => i.number === 4)!.critical).toBe(false)
})
it('defaults a null estimate to DEFAULT_ESTIMATE_DAYS', () => {
const plan = schedule([issue(1, { estimateDays: null })], [])
expect(plan.items[0].durationDays).toBe(2)
})
})
describe('selectFocus', () => {
it('picks the first three of the ordered plan as now/next/later', () => {
const plan = schedule([issue(1, { priority: 1 }), issue(2, { priority: 2 }), issue(3, { priority: 3 })], [])
const focus = selectFocus(plan)
expect(focus.now?.number).toBe(1)
expect(focus.next?.number).toBe(2)
expect(focus.later?.number).toBe(3)
})
it('returns nulls past the end of a short plan', () => {
const focus = selectFocus(schedule([issue(1)], []))
expect(focus.now?.number).toBe(1)
expect(focus.next).toBeNull()
expect(focus.later).toBeNull()
})
})

View File

@@ -0,0 +1,182 @@
/**
* Deterministic scheduler, v0. Orders the open backlog by dependency topology,
* then priority, then estimate; lays it out on a single serial capacity and
* marks the critical path. The LLM never does this — it's plain code.
*
* v0 simplifications (each is a later slice, not a hack):
* - single serial worker; per-person capacity is #8.
* - point durations from estimate labels; Monte Carlo cones are #10.
* - a null estimate defaults to DEFAULT_ESTIMATE_DAYS.
* Dependencies on out-of-scope issues (closed/done, or not passed in) are
* treated as satisfied and dropped — you schedule what's left to do.
*/
export const DEFAULT_ESTIMATE_DAYS = 2
export interface SchedulableIssue {
number: number
title: string
labels: string[]
/** From label facts; null when unestimated. */
estimateDays: number | null
/** 1 (most urgent) … 4; null when unset. */
priority: number | null
}
export interface DependencyEdge {
issue: number
dependsOn: number
}
export interface ScheduledItem {
number: number
title: string
labels: string[]
/** 0-based position in the plan. */
order: number
/** Working-day offsets from now. */
startDay: number
endDay: number
durationDays: number
/** In-scope dependencies (all still open, so all still blocking). */
blockedBy: number[]
/** Issues that depend on this one. */
blocks: number[]
/** On a longest-duration dependency chain. */
critical: boolean
rationale: string
}
export interface SchedulePlan {
items: ScheduledItem[]
/** A dependency cycle (issue numbers) if one was found — the plan is then empty. */
cycle: number[] | null
}
function durationOf(issue: SchedulableIssue): number {
return issue.estimateDays ?? DEFAULT_ESTIMATE_DAYS
}
/** Best-first comparison among ready nodes: priority (1 first), then larger estimate, then number. */
function readyRank(a: SchedulableIssue, b: SchedulableIssue): number {
const pa = a.priority ?? 99
const pb = b.priority ?? 99
if (pa !== pb) return pa - pb
const da = durationOf(a)
const db = durationOf(b)
if (da !== db) return db - da
return a.number - b.number
}
function rationaleFor(item: {
critical: boolean
blockedBy: number[]
blocks: number[]
priority: number | null
}): string {
const blocksNote = item.blocks.length ? `unblocks ${item.blocks.map((n) => `#${n}`).join(', ')}` : ''
if (item.critical) return ['on the critical path', blocksNote].filter(Boolean).join(' · ')
if (item.blockedBy.length) return `waits on ${item.blockedBy.map((n) => `#${n}`).join(', ')}`
if (blocksNote) return blocksNote
if (item.priority != null) return `p/${item.priority} · ready`
return 'ready'
}
export function schedule(issues: SchedulableIssue[], edges: DependencyEdge[]): SchedulePlan {
const byNumber = new Map(issues.map((i) => [i.number, i]))
// keep only edges whose endpoints are both in scope
const scoped = edges.filter((e) => byNumber.has(e.issue) && byNumber.has(e.dependsOn))
const deps = new Map<number, number[]>() // issue → its dependencies
const dependents = new Map<number, number[]>() // issue → who depends on it
for (const i of issues) {
deps.set(i.number, [])
dependents.set(i.number, [])
}
for (const e of scoped) {
deps.get(e.issue)!.push(e.dependsOn)
dependents.get(e.dependsOn)!.push(e.issue)
}
// Kahn topo with priority tie-break
const indegree = new Map(issues.map((i) => [i.number, deps.get(i.number)!.length]))
const order: number[] = []
const ready = issues.filter((i) => indegree.get(i.number) === 0)
while (ready.length) {
ready.sort(readyRank)
const next = ready.shift()!
order.push(next.number)
for (const dep of dependents.get(next.number)!) {
const d = indegree.get(dep)! - 1
indegree.set(dep, d)
if (d === 0) ready.push(byNumber.get(dep)!)
}
}
if (order.length < issues.length) {
// cycle: report the nodes that never became ready
const stuck = issues.filter((i) => indegree.get(i.number)! > 0).map((i) => i.number)
return { items: [], cycle: stuck }
}
// longest-path (by duration) for critical-path marking
const longestThrough = new Map<number, number>() // node → longest chain duration passing through it
const before = new Map<number, number>() // longest duration of chain ending at node's start
for (const n of order) {
const depMax = Math.max(0, ...deps.get(n)!.map((d) => before.get(d)! + durationOf(byNumber.get(d)!)))
before.set(n, depMax)
}
const after = new Map<number, number>()
for (const n of [...order].reverse()) {
const depMax = Math.max(0, ...dependents.get(n)!.map((d) => after.get(d)! + durationOf(byNumber.get(d)!)))
after.set(n, depMax)
}
let globalMax = 0
for (const n of order) {
const total = before.get(n)! + durationOf(byNumber.get(n)!) + after.get(n)!
longestThrough.set(n, total)
globalMax = Math.max(globalMax, total)
}
// serial layout
let cursor = 0
const items: ScheduledItem[] = order.map((n, idx) => {
const issue = byNumber.get(n)!
const dur = durationOf(issue)
const start = cursor
cursor += dur
const blockedBy = deps.get(n)!
const blocks = dependents.get(n)!
const critical = globalMax > 0 && longestThrough.get(n) === globalMax
return {
number: n,
title: issue.title,
labels: issue.labels,
order: idx,
startDay: start,
endDay: cursor,
durationDays: dur,
blockedBy,
blocks,
critical,
rationale: rationaleFor({ critical, blockedBy, blocks, priority: issue.priority }),
}
})
return { items, cycle: null }
}
export interface Focus {
now: ScheduledItem | null
next: ScheduledItem | null
later: ScheduledItem | null
}
/** Now/Next/Later = the first three of the plan (already dependency- + priority-ordered). */
export function selectFocus(plan: SchedulePlan): Focus {
return {
now: plan.items[0] ?? null,
next: plan.items[1] ?? null,
later: plan.items[2] ?? null,
}
}