diff --git a/pm-stack/README.md b/pm-stack/README.md index 6a6824388b..209492ec79 100644 --- a/pm-stack/README.md +++ b/pm-stack/README.md @@ -17,12 +17,12 @@ Phase 2 (2026-10-24) added three layers, each in its own subdirectory with the same deploy shape (SOPS → mode-600 env → compose/unit → health gate): -| Layer | Piece | Version / pin | Reach | Deployment definition | -| --------- | --------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------- | -| Dispatch | ready-for-agent | npm `ready-for-agent@1.1.0` (no container image exists upstream) | UI + GraphQL on `6056`, all interfaces (loopback + tailnet + LAN) | `ready-for-agent/` | -| Planning | Pad | `ghcr.io/perpetualsoftware/pad:0.18.1`, pinned by digest | `127.0.0.1:7777` + tailnet `100.99.113.103:7777`; no tunnel hostname | `pad/` | -| Tables | Grist | `gristlabs/grist-oss:v1.7.21`, pinned by digest | `127.0.0.1:8484` + tailnet `100.99.113.103:8484`; no tunnel hostname | `grist/` | -| Dashboard | Aggregator | this repo (Bun app, user unit `pm-aggregator`) | `127.0.0.1:4870` + tailnet `100.99.113.103:4870`; no public route | `aggregator/` | +| Layer | Piece | Version / pin | Reach | Deployment definition | +| --------- | --------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------- | --------------------- | +| Dispatch | ready-for-agent | npm `ready-for-agent@1.1.0` (no container image exists upstream) | UI + GraphQL on `6056`, all interfaces (loopback + tailnet + LAN) | `ready-for-agent/` | +| Planning | Pad | `ghcr.io/perpetualsoftware/pad:0.18.1`, pinned by digest | `127.0.0.1:7777` + tailnet `amd-6.raptor-pumpkinseed.ts.net:7777`; no tunnel hostname | `pad/` | +| Tables | Grist | `gristlabs/grist-oss:v1.7.21`, pinned by digest | `127.0.0.1:8484` + tailnet `amd-6.raptor-pumpkinseed.ts.net:8484`; no tunnel hostname | `grist/` | +| Dashboard | Aggregator | this repo (Bun app, user unit `pm-aggregator`) | `127.0.0.1:4870` + tailnet `amd-6.raptor-pumpkinseed.ts.net:4870`; no public route | `aggregator/` | ready-for-agent runs as a systemd **user unit** (like `pm-tunnel`) because upstream ships only an npm package; Pad and Grist run as diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index d02882b9e9..a972049760 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -9,15 +9,45 @@ works standalone (design record, "Data flow"). Design record (source of truth): [`doc/2026-10-24T11-05-38Z_design_project-management-stack/`](../../doc/2026-10-24T11-05-38Z_design_project-management-stack/). -## The four views - -| Route | View | Machine-first JSON | -| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| `/` | **Cross-repo WIP board** — the curated in-flight set across all four repos, with an execution strip per card (implementing → review → merged → queued). | `/api/board.json` | -| `/roadmap` | **Roadmap** — Grist's `Program roadmap` table as a timeline (theme × quarter lane); each row drills down to its linked issues/PRs with live state. | `/api/roadmap.json` | -| `/quota` | **Quota + throughput** (#851) — all pooled quotas, resets, burn rates, and model-choice guidance. | `/api/quota.json` | -| `/attention` | **Needs you** (#852) — every live agent session, classified and attention-ordered, with the evidence inline. | `/api/attention.json` | -| `/item/` | Drill-down for one board card or roadmap row: linked refs + a unified comment stream. | — | +## The views + +| Route | View | Machine-first JSON | +| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| `/today` | **Today** (slice 2, #898) — the day's top objectives, prioritized, plus per-project momentum (moving / stalled / blocked-by-what, recent accomplishments). From the orchestration job's goal measurements (#899) when a section exists; derived from board + roadmap + item activity, and labelled as derived, until then. | `/api/today.json` | +| `/attention` | **Needs you** (#852, tiered in slice 2) — **NEEDS DREW** (default; only items that genuinely require Drew, each with its reason), **NEEDS ORCHESTRATOR** (the fleet's own queue), then every current session with source labels and plain-language states. Finished runs and stale items expire out. | `/api/attention.json`, `/api/coverage.json` | +| `/` | **Cross-repo WIP board** — the curated in-flight set across all four repos, with an execution strip per card (implementing → review → merged → queued). | `/api/board.json` | +| `/roadmap` | **Roadmap** — Grist's `Program roadmap` table as a timeline; `?h=` switches the horizon: `quarter` (default), `month`, `week`, `3d`, `today` — one data model at every grain. | `/api/roadmap.json` | +| `/quota` | **Quota + throughput** (#851) — all pooled quotas, resets, burn rates, and model-choice guidance. | `/api/quota.json` | +| `/item/` | Drill-down for one board card or roadmap row: linked refs + a unified comment stream. | — | + +All views are mobile-first (single-column stacking, scrollable tables, +touch-sized switchers) — verify at phone width, not by resizing a desktop +window. The canonical tailnet URL is +`http://amd-6.raptor-pumpkinseed.ts.net:4870` (MagicDNS); links never use +the raw tailnet IP (bind addresses and the feed-push transport still do — +that is plumbing, not links). + +### Needs-you tiers + session clarity (slice 2, #898) + +- **Tiering** (`buildAttention` in `src/derive.ts`): every classified + session lands in NEEDS DREW (with an explainable `drewReason`), + NEEDS ORCHESTRATOR (with the fleet's next step), or in-motion. Drew + rules, in order: the orchestration job's own classification (#899 — + its tiers win for anything they name, reason verbatim) → a keeper + "escalate" supervision note → a decision-shaped question → a + destructive permission request → a credential/sign-in wall. Routine + questions, errors, and tool permissions are the orchestrator's — + and so are Jules' questions (the keeper answers those itself). +- **Expiry**: a finished run (the runtime reported an outcome) expires + 2 h after its last activity; anything expires at 24 h. The page counts + what expired. +- **Sources**: every entry is stamped `opencode-sandbox` / + `opencode-laptop` / `jules` / `claude-code`; OpenCode sub-sessions + carry `parentId` and collapse under their parent. **Jules is wired** + via the keeper's `jules-review-state.json` (collector-side, + `src/sources/jules.ts`). **Muse is not wired** — the assistant + runtime exposes no session registry to read; the coverage note on the + page says so, and the gap is tracked in #898. Each view is **machine-first**: the `/api/*.json` endpoint returns the exact same data the GUI renders, so Muse can poll it in one call. @@ -119,8 +149,26 @@ a file. `scripts/collect-fleet-feed.ts` runs on the sandbox: registry: exactly one Meta pool (Muse API High Usage, `meta` provider the only door); no "muse plan" pool exists. - **Sandbox attention** — sessions mapped by the shared OpenCode v2 - mapper (`src/sources/opencode.ts`); keeper supervision entries - from `jules-review-state.json` annotate matching sessions. + mapper (`src/sources/opencode.ts`), stamped `opencode-sandbox` with + parent/agent/outcome; keeper supervision entries from + `jules-review-state.json` annotate matching sessions. +- **Jules attention** (slice 2) — the keeper's tracked Jules sessions + from the same state file, mapped by `src/sources/jules.ts`, plus the + keeper's run totals as `julesSummary`. +- **Orchestration section** (slice 2, #899 — the unified contract) — + the orchestration job republishes + `~/workspace/goals/keep-the-four-repos-healthy/hidden_files/orchestration.json` + on the sandbox every run: an `OrchestrationSection` v1 (types in + `src/model.ts`) with tiered queue items (`tiers.needsDrew` / + `tiers.needsOrchestrator`, each with its reason), a flat dependency + view, per-goal measurements (momentum, tasks lined up by horizon, + what progressed), and the actions the run pushed back into motion. + The collector embeds it as `feed.orchestration` after a structural + check (fail-soft; override the path with `ORCHESTRATION_PATH`). The + aggregator serves it raw at `/api/orchestration.json`; the needs-you + view lets its classification win for anything it names (non-session + items render as tier cards), and the today view maps its goals — + until a section exists, the today view derives and labels itself. `scripts/push-fleet-feed.sh` pushes the feed to the laptop over the tailnet proxy route; a systemd timer on the sandbox runs it every @@ -198,6 +246,7 @@ src/ fixtures.ts fixture data (real Grist seed + design-record refs) live.ts Kaneo/Grist/projector readers with per-facet fallback opencode.ts OpenCode v2 server -> SessionFeedEntry mapper (shared) + jules.ts keeper state -> Jules SessionFeedEntry mapper (shared) scripts/ collect-fleet-feed.ts sandbox collector: quota + sandbox attention -> feed push-fleet-feed.sh collect + push the feed to the laptop (~5 min timer) @@ -209,4 +258,6 @@ test/ projector.test.ts projector wire-schema mapping + stub-server reads opencode.test.ts mapper against a stub OpenCode v2 server quota.test.ts extractors + guidance against the dated-read format + slice2.test.ts tiers, expiry, hierarchy, Jules mapping, roadmap + grains, today derivation, slice-2 render smoke ``` diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index b558926a69..d246c749f9 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -25,9 +25,10 @@ import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { isOrchestrationSection, type FleetFeed } from "../src/feed.ts"; -import type { OrchestrationSection, QuotaPool, SessionFeedEntry } from "../src/model.ts"; +import type { JulesSummary, OrchestrationSection, QuotaPool, SessionFeedEntry } from "../src/model.ts"; import { extractQuotaPools } from "../src/quota-extract.ts"; import { computeChoices } from "../src/quota-guidance.ts"; +import { julesSummary, mapJulesItems, type JulesReviewState } from "../src/sources/jules.ts"; import { mapServerSessions, poolBurn } from "../src/sources/opencode.ts"; const PKG = join(dirname(fileURLToPath(import.meta.url)), ".."); @@ -112,7 +113,9 @@ async function main(): Promise { let attention: SessionFeedEntry[] = []; try { const password = (await readFile(passwordFile, "utf8")).trim(); - const mapped = await mapServerSessions({ baseUrl: serverUrl, password }, now.getTime()); + const mapped = await mapServerSessions({ baseUrl: serverUrl, password }, now.getTime(), { + source: "opencode-sandbox", + }); if (mapped) { attention = mapped.entries; const notes = await supervisionNotes(); @@ -143,6 +146,17 @@ async function main(): Promise { console.error(`collector: sandbox server read failed (${err}); attention empty`); } + // --- Jules sessions + keeper totals (slice 2, #898 §5) ------------------ + let jules: JulesSummary | undefined; + try { + const state = JSON.parse(await readFile(julesStatePath, "utf8")) as JulesReviewState; + const entries = mapJulesItems(state); + if (entries.length) attention = [...attention, ...entries]; + jules = julesSummary(state); + } catch { + console.error("collector: jules-review state unreadable; no Jules sessions this run"); + } + // --- orchestration section (#899) -------------------------------------- let orchestration: OrchestrationSection | undefined; try { @@ -162,12 +176,13 @@ async function main(): Promise { generatedAt: now.toISOString(), quota: { pools, burn: [], choices: computeChoices(pools, now.getTime()) }, attention, + julesSummary: jules, ...(orchestration ? { orchestration } : {}), }; await writeFile(outPath, JSON.stringify(feed, null, 2)); const withReads = pools.filter((p) => p.windows.length > 0).length; console.log( - `collector: wrote ${outPath} — ${pools.length} pools (${withReads} with reads), ${attention.length} sandbox sessions` + + `collector: wrote ${outPath} — ${pools.length} pools (${withReads} with reads), ${attention.length} sessions (sandbox + jules${jules ? `, ${jules.tracked} jules tracked` : ""})` + (orchestration ? `, orchestration ${orchestration.runId}` : ", no orchestration section"), ); } diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index e79b6a14f6..f9eb66a4c0 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -205,3 +205,496 @@ export function classifyAttention(e: SessionFeedEntry, now = Date.now()): Attent export function attentionSorted(feed: SessionFeedEntry[], now = Date.now()): AttentionEntry[] { return feed.map((e) => classifyAttention(e, now)).sort((a, b) => a.order - b.order); } + +// --------------------------------------------------------------------------- +// Slice 2 (#898): session sources, freshness expiry, NEEDS DREW / NEEDS +// ORCHESTRATOR tiering, session hierarchy, roadmap grains, today view. +// --------------------------------------------------------------------------- + +import type { AttentionTier, BoardItem, OrchestrationSection, SessionSource, TierItem, TieredEntry } from "./model.ts"; + +export function sourceOf(e: SessionFeedEntry): SessionSource { + if (e.source) return e.source; + return "opencode-sandbox"; // fleet-feed entries predate the stamp +} + +/** Human labels for the six machine states (#898 §5: comprehensible). */ +export const STATE_LABELS: Record = { + "in-motion": "working now", + "stopped-for-question": "waiting for an answer", + errored: "errored", + "needs-poke": "idle — needs a poke", + "stalled-on-cli": "long-running command", + "stuck-retrying": "stuck retrying", +}; + +/** A finished run (runtime reported an outcome) expires after this long. */ +export const FINISHED_EXPIRY_MS = 2 * 3_600_000; +/** Nothing presents as current past this age. */ +export const MAX_ENTRY_AGE_MS = 24 * 3_600_000; + +export function isFinished(e: SessionFeedEntry): boolean { + return typeof e.outcome === "string" && e.outcome !== ""; +} + +/** + * Split a feed into current entries and expired ones (#898 §2/§5): + * finished-run leftovers expire FINISHED_EXPIRY_MS after their last + * activity; anything older than MAX_ENTRY_AGE_MS expires regardless. + * Entries with no timestamp are kept (no evidence of staleness). + */ +export function partitionFresh( + feed: SessionFeedEntry[], + now = Date.now(), +): { current: SessionFeedEntry[]; expired: SessionFeedEntry[] } { + const current: SessionFeedEntry[] = []; + const expired: SessionFeedEntry[] = []; + for (const e of feed) { + const t = e.lastActivityAt ? Date.parse(e.lastActivityAt) : NaN; + if (!Number.isFinite(t)) { + current.push(e); + continue; + } + const age = now - t; + if (age > MAX_ENTRY_AGE_MS || (isFinished(e) && age > FINISHED_EXPIRY_MS)) expired.push(e); + else current.push(e); + } + return { current, expired }; +} + +const DECISION_Q = + /(should (i|we)\b|which (option|approach|repo|one|of|path)|approve|approval|choose|pick one|sign[- ]?off|go ahead\?)/i; +const DESTRUCTIVE_Q = /(\brm\b|delete|drop table|destroy|force[- ]?push|reset --hard|spend|purchase|\bpay\b|deploy)/i; +const CREDENTIAL_ERR = + /(otp|one[- ]?time code|verification code|passkey|2fa|sign[- ]?in required|login required|authentication required)/i; +const ESCALATION_NOTE = /(escalat|needs drew|drew decision|decision needed)/i; + +const ORCHESTRATOR_NOTES: Record = { + "in-motion": "", + "stopped-for-question": "Orchestrator answers from recorded context, or pokes the session to continue.", + errored: "Orchestrator triages the error, then retries or reroutes the session.", + "needs-poke": "Orchestrator pokes it — or closes it if the work is actually done.", + "stuck-retrying": "Orchestrator breaks the retry loop and reroutes the work.", + "stalled-on-cli": "Orchestrator checks the long-running command and nudges the session.", +}; + +/** The session id a #899 tier item names, when it names one. */ +export function tierItemSessionId(item: TierItem): string | null { + if (item.sessionId) return item.sessionId; + if (item.id.startsWith("jules:")) return item.id.slice("jules:".length); + if (item.kind === "session") return item.id; + return null; +} + +export interface SectionMatch { + item: TierItem; + tier: "needs-drew" | "needs-orchestrator"; +} + +/** + * Assign each classified entry its tier. Rule order matters — the first + * match wins, and the orchestration job's own classification (#899) + * outranks every local rule, carrying its reason verbatim: the job + * reviews these queues so Drew doesn't have to. + */ +export function tierEntry(e: AttentionEntry, match?: SectionMatch | null): TieredEntry { + if (match && e.state !== "in-motion") { + if (match.tier === "needs-drew") return { ...e, tier: "needs-drew", drewReason: match.item.reason }; + const next = match.item.recommendedAction ? ` Next: ${match.item.recommendedAction}` : ""; + return { ...e, tier: "needs-orchestrator", orchestratorNote: `${match.item.reason}${next}` }; + } + if (e.state !== "in-motion" && e.supervisionNote && ESCALATION_NOTE.test(e.supervisionNote)) { + return { ...e, tier: "needs-drew", drewReason: `Keeper escalated this session — ${e.supervisionNote}` }; + } + if (e.state !== "in-motion" && e.awaitingQuestion) { + const q = e.awaitingQuestion; + if (/^permission pending:/i.test(q)) { + if (DESTRUCTIVE_Q.test(q)) { + return { + ...e, + tier: "needs-drew", + drewReason: `A session is asking permission for something destructive — ${q}`, + }; + } + // Routine tool permissions are the fleet's to review, not Drew's. + } else if (DECISION_Q.test(q) && sourceOf(e) !== "jules") { + // Jules questions are the keeper's to answer (it replies with the + // standard proceed/feedback messages) — they never need Drew + // unless the orchestration job escalates them explicitly. + return { ...e, tier: "needs-drew", drewReason: `Waiting on your decision — ${q}` }; + } + } + if (e.state !== "in-motion" && e.lastTurnError && CREDENTIAL_ERR.test(e.lastTurnError)) { + return { + ...e, + tier: "needs-drew", + drewReason: `Blocked on a sign-in only you can complete — ${e.lastTurnError}`, + }; + } + if (e.state === "in-motion") return { ...e, tier: "in-motion" }; + return { ...e, tier: "needs-orchestrator", orchestratorNote: ORCHESTRATOR_NOTES[e.state] }; +} + +export interface AttentionView { + drew: TieredEntry[]; + orchestrator: TieredEntry[]; + /** #899 tier items that are not live sessions (decisions, tasks, gaps). */ + drewExtra: TierItem[]; + orchestratorExtra: TierItem[]; + /** Every current entry, tier-annotated, attention-ordered. */ + all: TieredEntry[]; + /** Finished/stale entries dropped before display. */ + expiredCount: number; +} + +/** Classify, expire, and tier a raw session feed in one pass. */ +export function buildAttention( + feed: SessionFeedEntry[], + section?: OrchestrationSection | null, + now = Date.now(), +): AttentionView { + const { current, expired } = partitionFresh(feed, now); + const bySession = new Map(); + if (section) { + for (const item of section.tiers.needsDrew) { + const sid = tierItemSessionId(item); + if (sid && !bySession.has(sid)) bySession.set(sid, { item, tier: "needs-drew" }); + } + for (const item of section.tiers.needsOrchestrator) { + const sid = tierItemSessionId(item); + if (sid && !bySession.has(sid)) bySession.set(sid, { item, tier: "needs-orchestrator" }); + } + } + const consumed = new Set(); + const all = current + .map((raw) => { + const e = classifyAttention(raw, now); + const match = bySession.get(e.sessionId) ?? null; + if (match) consumed.add(match.item.id); + return tierEntry(e, match); + }) + .sort((a, b) => a.order - b.order || (b.lastActivityAt ?? "").localeCompare(a.lastActivityAt ?? "")); + // Section items that name a session in the feed are consumed by it + // (tiered above, or in motion again); items naming expired sessions + // expire with them. The rest are non-session queue items — decisions, + // tasks, gaps — and render as cards in their tier. + const knownIds = new Set([...current, ...expired].map((e) => e.sessionId)); + const extras = (items: TierItem[] | undefined): TierItem[] => + (items ?? []).filter((item) => { + if (consumed.has(item.id)) return false; + const sid = tierItemSessionId(item); + return !(sid && knownIds.has(sid)); + }); + return { + drew: all.filter((e) => e.tier === "needs-drew"), + orchestrator: all.filter((e) => e.tier === "needs-orchestrator"), + drewExtra: extras(section?.tiers.needsDrew), + orchestratorExtra: extras(section?.tiers.needsOrchestrator), + all, + expiredCount: expired.length, + }; +} + +/** + * Parent/child structure over a set of entries: an entry whose parentId + * names another entry in the set is its child; anything else is a root + * (a child whose parent is absent renders as a root with its chip). + */ +export function sessionChildren(entries: TieredEntry[]): Map { + const ids = new Set(entries.map((e) => e.sessionId)); + const children = new Map(); + for (const e of entries) { + if (e.parentId && e.parentId !== e.sessionId && ids.has(e.parentId)) { + children.set(e.parentId, [...(children.get(e.parentId) ?? []), e]); + } + } + return children; +} + +export function sessionRoots(entries: TieredEntry[]): TieredEntry[] { + const ids = new Set(entries.map((e) => e.sessionId)); + return entries.filter((e) => !(e.parentId && e.parentId !== e.sessionId && ids.has(e.parentId))); +} + +// --- Calendar helpers (America/Chicago — Drew's timezone) --------------- + +const YMD = /^(\d{4})-(\d{2})-(\d{2})/; + +/** "2026-10-25" in America/Chicago for an instant. */ +export function chicagoYmd(now = new Date()): string { + return new Intl.DateTimeFormat("en-CA", { + timeZone: "America/Chicago", + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(now); +} + +export function addDaysYmd(ymd: string, n: number): string { + const d = new Date(`${ymd}T12:00:00Z`); + d.setUTCDate(d.getUTCDate() + n); + return d.toISOString().slice(0, 10); +} + +/** Monday (Chicago) of the week containing `ymd`. */ +export function weekStartYmd(ymd: string): string { + const dow = new Date(`${ymd}T12:00:00Z`).getUTCDay(); // 0=Sun + return addDaysYmd(ymd, -((dow + 6) % 7)); +} + +const MONTH_NAMES = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; +const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + +export function ymdLabel(ymd: string): string { + const d = new Date(`${ymd}T12:00:00Z`); + return `${DAY_NAMES[d.getUTCDay()]} ${MONTH_NAMES[d.getUTCMonth()].slice(0, 3)} ${d.getUTCDate()}`; +} + +export function monthLabel(ym: string): string { + const [y, m] = ym.split("-").map(Number); + return `${MONTH_NAMES[m - 1]} ${y}`; +} + +// --- Roadmap grains (#898 §3) ---------------------------------------------- + +export type RoadmapGrain = "quarter" | "month" | "week" | "3d" | "today"; + +/** The row's calendar date when its Horizon is an ISO date, else null. */ +export function rowDate(row: RoadmapRow): string | null { + const m = YMD.exec(row.horizon.trim()); + return m ? `${m[1]}-${m[2]}-${m[3]}` : null; +} + +export interface DayLane { + key: string; + label: string; + rows: RoadmapRow[]; +} + +export interface DayGrain { + lanes: DayLane[]; + /** Dated rows outside the window. */ + outside: number; + /** Rows with no calendar date (quarter grain, ongoing, unscheduled). */ + coarse: RoadmapRow[]; +} + +/** Day-grained roadmap: week (Mon–Sun), next 3 days, or today. */ +export function roadmapDayGrain(rows: RoadmapRow[], grain: "week" | "3d" | "today", now = new Date()): DayGrain { + const today = chicagoYmd(now); + const days: string[] = + grain === "today" + ? [today] + : grain === "3d" + ? [today, addDaysYmd(today, 1), addDaysYmd(today, 2)] + : Array.from({ length: 7 }, (_, i) => addDaysYmd(weekStartYmd(today), i)); + const inWindow = new Set(days); + const lanes = new Map(days.map((d) => [d, [] as RoadmapRow[]])); + let outside = 0; + const coarse: RoadmapRow[] = []; + for (const row of rows) { + const d = rowDate(row); + if (!d) { + coarse.push(row); + } else if (inWindow.has(d)) { + lanes.get(d)?.push(row); + } else { + outside++; + } + } + return { + lanes: days.map((d) => ({ + key: d, + label: d === today ? `${ymdLabel(d)} · today` : ymdLabel(d), + rows: lanes.get(d) ?? [], + })), + outside, + coarse, + }; +} + +/** Month-grained timeline: dated rows by month; quarter rows keep their grain. */ +export function monthTimeline(rows: RoadmapRow[]): Timeline { + const lanes = new Map(); + const cells = new Map>(); + const put = (row: RoadmapRow, lane: Lane) => { + lanes.set(lane.key, lane); + const theme = row.area || "Unthemed"; + if (!cells.has(theme)) cells.set(theme, new Map()); + const byLane = cells.get(theme) as Map; + byLane.set(lane.key, [...(byLane.get(lane.key) ?? []), row]); + }; + for (const row of rows) { + const d = rowDate(row); + if (d) { + const ym = d.slice(0, 7); + const [y, m] = ym.split("-").map(Number); + put(row, { key: ym, label: monthLabel(ym), order: y * 12 + m }); + } else { + put(row, laneFor(row.horizon)); // quarter / ongoing / unscheduled lanes + } + } + return { + lanes: [...lanes.values()].sort((a, b) => a.order - b.order), + themes: [...cells.keys()], + cells, + }; +} + +// --- Today view (#898 §4) ---------------------------------------------------- + +export interface TodayObjective { + title: string; + detail?: string; + /** Where the objective came from, e.g. "orchestrator · today". */ + chip: string; + ref?: RefKey; +} + +export interface ProjectMomentum { + project: string; + state: "moving" | "stalled" | "blocked"; + accomplished: string[]; + blockedBy?: string; + detail?: string; +} + +export interface TodayView { + objectives: TodayObjective[]; + momentum: ProjectMomentum[]; + /** True when rendered from the #899 orchestration section. */ + fromOrchestrator: boolean; + generatedAt?: string; + /** What the orchestrator pushed back into motion (section path only). */ + actions?: { at: string; kind: string; target: string; summary: string }[]; +} + +const PRIORITY_ORDER: Record = { urgent: 0, high: 1, normal: 2, medium: 2, low: 3 }; + +/** Map the #899 section's goal measurements into the today view. */ +export function todayFromSection(section: OrchestrationSection): TodayView { + const blockedText = (deps?: { task: string; status: string; workerLabel?: string }[]): string | undefined => + deps?.length + ? deps.map((d) => `${d.task} (${d.status}${d.workerLabel ? `, ${d.workerLabel}` : ""})`).join("; ") + : undefined; + const objectives: TodayObjective[] = []; + for (const g of section.goals) { + for (const task of g.linedUp.filter((t) => t.horizon === "today")) { + objectives.push({ + title: task.title, + detail: + [task.status, task.horizonWhy, blockedText(task.blockedBy) && `blocked by ${blockedText(task.blockedBy)}`] + .filter(Boolean) + .join(" — ") || undefined, + chip: `orchestrator · today · ${g.goal}`, + ref: task.ref, + }); + } + } + if (objectives.length === 0) { + for (const g of section.goals) { + objectives.push({ title: g.goal, detail: g.summary, chip: "orchestrator · goal" }); + } + } + const momentum: ProjectMomentum[] = section.goals.map((g) => { + const blockers = [ + ...g.stalled.filter((s) => s.blocker).map((s) => `${s.title}: ${s.blocker}`), + ...g.linedUp.flatMap((t) => (t.blockedBy?.length ? [`${t.title} — blocked by ${blockedText(t.blockedBy)}`] : [])), + ]; + return { + project: g.goal, + state: g.momentum === "moving" ? "moving" : g.momentum === "blocked" ? "blocked" : "stalled", + accomplished: g.progressedSinceLastRun, + blockedBy: blockers.join("; ") || undefined, + detail: [g.summary, ...g.gaps].filter(Boolean).join(" "), + }; + }); + return { + fromOrchestrator: true, + generatedAt: section.generatedAt, + objectives, + momentum, + actions: section.actions.slice(-5).reverse(), + }; +} + +export function deriveToday( + board: BoardItem[], + rows: RoadmapRow[], + items: Map, + section: OrchestrationSection | null, + now = new Date(), +): TodayView { + if (section) return todayFromSection(section); + + // Derived until #899 lands: today's dated roadmap rows first, then the + // board's in-progress work by priority, then what's in review. + const today = chicagoYmd(now); + const objectives: TodayObjective[] = []; + for (const row of rows) { + if (rowDate(row) === today && !/^done$/i.test(row.status)) { + objectives.push({ title: row.title, chip: "roadmap · today", detail: `${row.area} · ${row.status}` }); + } + } + const byPriority = (a: BoardItem, b: BoardItem) => + (PRIORITY_ORDER[(a.priority ?? "normal").toLowerCase()] ?? 2) - + (PRIORITY_ORDER[(b.priority ?? "normal").toLowerCase()] ?? 2) || + (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""); + for (const item of board + .filter((b) => b.status === "in-progress") + .sort(byPriority) + .slice(0, 5)) { + objectives.push({ title: item.title, chip: `in progress · ${item.repo}` }); + } + for (const item of board + .filter((b) => b.status === "in-review") + .sort(byPriority) + .slice(0, 3)) { + objectives.push({ title: item.title, chip: `in review · ${item.repo}` }); + } + + const weekAgo = now.getTime() - 7 * 86_400_000; + const twoDaysAgo = now.getTime() - 2 * 86_400_000; + const momentum: ProjectMomentum[] = []; + const repos = [...new Set(board.map((b) => b.repo))]; + for (const repo of repos) { + const repoBoard = board.filter((b) => b.repo === repo); + const linked = new Map(); + for (const b of repoBoard) { + for (const l of b.links) { + const it = items.get(l.ref); + if (it) linked.set(it.ref, it); + } + } + const all = [...linked.values()]; + const accomplished = all + .filter((i) => (i.state === "merged" || i.state === "closed") && Date.parse(i.updatedAt) >= weekAgo) + .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) + .slice(0, 3) + .map((i) => `${i.ref} — ${i.title}`); + const blocked = all.filter((i) => i.state === "open" && i.labels.some((l) => /blocked/i.test(l))); + const recent = all.some((i) => Date.parse(i.updatedAt) >= twoDaysAgo); + const inProgress = repoBoard.some((b) => b.status === "in-progress" || b.status === "in-review"); + momentum.push({ + project: repo, + state: blocked.length > 0 ? "blocked" : accomplished.length > 0 || (inProgress && recent) ? "moving" : "stalled", + accomplished, + blockedBy: blocked.length ? blocked.map((i) => `${i.ref} — ${i.title}`).join("; ") : undefined, + detail: inProgress ? undefined : "nothing in progress on the board", + }); + } + return { fromOrchestrator: false, objectives, momentum }; +} diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index b0d52e390e..a165323a4f 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -4,15 +4,17 @@ // record live on the sandbox). The aggregator renders the feed as-is; // a stale feed keeps rendering with its age stated in provenance. import { readFile } from "node:fs/promises"; -import type { OrchestrationSection, QuotaView, SessionFeedEntry } from "./model.ts"; +import type { JulesSummary, OrchestrationSection, QuotaView, SessionFeedEntry } from "./model.ts"; export interface FleetFeed { version: 1; /** ISO timestamp of collection on the sandbox. */ generatedAt: string; quota: QuotaView; - /** Sandbox-server sessions, pre-classification (render classifies). */ + /** Sandbox-server + Jules sessions, pre-classification (render classifies). */ attention: SessionFeedEntry[]; + /** Jules keeper totals (slice 2); absent when the keeper state is unreadable. */ + julesSummary?: JulesSummary; /** The orchestration job's latest section (#899), when one exists. */ orchestration?: OrchestrationSection; } diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 090ee31c5e..daef33b9df 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -111,6 +111,7 @@ export interface Provenance { comments: string; quota: string; attention: string; + orchestration: string; } // --------------------------------------------------------------------------- @@ -186,9 +187,28 @@ export type AttentionState = | "stalled-on-cli" | "stuck-retrying"; +/** Which runtime a session belongs to (slice 2, #898 §5). */ +export type SessionSource = "opencode-sandbox" | "opencode-laptop" | "jules" | "claude-code"; + +export const SESSION_SOURCE_LABELS: Record = { + "opencode-sandbox": "OpenCode · sandbox", + "opencode-laptop": "OpenCode · laptop", + jules: "Jules", + "claude-code": "Muse", +}; + /** The raw feed entry for one session, as the projector / watch cron emits. */ export interface SessionFeedEntry { sessionId: string; + /** Owning runtime; feed entries default to the sandbox server. */ + source?: SessionSource; + /** Parent session id for sub-sessions (OpenCode `parentID`), else null/absent. */ + parentId?: string | null; + /** Subagent name when the session is a spawned sub-session (e.g. "explore"). */ + agent?: string; + /** Run outcome when the runtime reports one (succeeded/failed/interrupted). */ + outcome?: string | null; + createdAt?: string; title?: string; directory?: string; branch?: string; @@ -218,6 +238,44 @@ export interface AttentionEntry extends SessionFeedEntry { evidence: string; } +/** + * Slice 2 tiers (#898 §2): who has to act on a session. NEEDS DREW is the + * default view and only holds items with an explainable `drewReason`; + * everything else the fleet can work itself is NEEDS ORCHESTRATOR. + */ +export type AttentionTier = "needs-drew" | "needs-orchestrator" | "in-motion"; + +export interface TieredEntry extends AttentionEntry { + tier: AttentionTier; + /** Why this needs Drew — present iff tier is "needs-drew". */ + drewReason?: string; + /** What the fleet will do with it — present iff tier is "needs-orchestrator". */ + orchestratorNote?: string; +} + +/** One session source's wiring status, for the coverage note (#898 §5). */ +export interface SourceCoverage { + source: SessionSource; + label: string; + wired: boolean; + detail: string; +} + +/** Keeper run totals for Jules, parsed from jules-review-state.json. */ +export interface JulesSummary { + /** When the keeper last ran (its `last_run`). */ + at: string | null; + /** Sessions the keeper currently tracks in its `items` map. */ + tracked: number; + /** Totals from the keeper's freshest run note, when it parses. */ + total?: number; + completed?: number; + failed?: number; + inProgress?: number; + awaitingFeedback?: number; + awaitingPlan?: number; +} + export function refKey(ref: GhRef): RefKey { return `${ref.repo}#${ref.number}`; } diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 61c3480287..0cb5568663 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -2,23 +2,34 @@ // returns a full HTML string — nothing here does I/O, which keeps the smoke // tests cheap (render from fixtures and assert on output). import { + type AttentionView, + type RoadmapGrain, + type TodayView, allRefs, - attentionSorted, commentStream, executionStrip, + monthTimeline, + roadmapDayGrain, + sessionChildren, + sessionRoots, + sourceOf, + STATE_LABELS, timeline as buildTimeline, windowPercent, } from "./derive.ts"; -import type { - AttentionEntry, - BoardItem, - Comment, - GhItem, - Provenance, - QuotaView, - RefKey, - RoadmapRow, - SessionFeedEntry, +import { + type BoardItem, + type Comment, + type GhItem, + type Provenance, + type QuotaView, + type RefKey, + type RoadmapRow, + type SourceCoverage, + type TieredEntry, + type TierItem, + SESSION_SOURCE_LABELS, + refUrl, } from "./model.ts"; export function esc(s: unknown): string { @@ -44,13 +55,13 @@ const CSS = ` :root { color-scheme: light dark; } * { box-sizing: border-box; } body { margin: 0; font: 14px/1.45 system-ui, -apple-system, sans-serif; background: #0e1117; color: #e6edf3; } -nav { display: flex; gap: 4px; padding: 10px 16px; border-bottom: 1px solid #30363d; background: #161b22; position: sticky; top: 0; } -nav a { color: #58a6ff; text-decoration: none; padding: 4px 10px; border-radius: 6px; } +nav { display: flex; gap: 4px; padding: 10px 16px; border-bottom: 1px solid #30363d; background: #161b22; position: sticky; top: 0; overflow-x: auto; -webkit-overflow-scrolling: touch; } +nav a { color: #58a6ff; text-decoration: none; padding: 6px 10px; border-radius: 6px; white-space: nowrap; } nav a.active, nav a:hover { background: #21262d; } main { max-width: 1180px; margin: 0 auto; padding: 20px 16px 80px; } h1 { font-size: 18px; } h2 { font-size: 15px; } a { color: #58a6ff; } -.card { border: 1px solid #30363d; border-radius: 8px; padding: 10px 12px; margin: 8px 0; background: #161b22; } +.card { border: 1px solid #30363d; border-radius: 8px; padding: 10px 12px; margin: 8px 0; background: #161b22; overflow-wrap: anywhere; } .muted { color: #8b949e; font-size: 12px; } .badge { display: inline-block; font-size: 11px; padding: 1px 7px; border-radius: 999px; border: 1px solid #30363d; margin: 1px 2px 1px 0; white-space: nowrap; } .badge.open { background: #1f6feb33; border-color: #1f6feb; color: #58a6ff; } @@ -61,25 +72,59 @@ a { color: #58a6ff; } .badge.healthy { background: #2ea04333; border-color: #2ea043; color: #3fb950; } .badge.near { background: #d2992233; border-color: #d29922; color: #e3b341; } .badge.walled { background: #f8514933; border-color: #f85149; color: #f85149; } +.badge.src { background: #21262d; color: #e6edf3; } +.badge.drew { background: #f8514933; border-color: #f85149; color: #f85149; } +.badge.orch { background: #1f6feb33; border-color: #1f6feb; color: #58a6ff; } +.badge.moving { background: #2ea04333; border-color: #2ea043; color: #3fb950; } +.badge.stalled { background: #d2992233; border-color: #d29922; color: #e3b341; } +.badge.blocked { background: #f8514933; border-color: #f85149; color: #f85149; } .strip { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 6px; } .board { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; align-items: start; } .col { border: 1px solid #30363d; border-radius: 8px; padding: 8px; background: #0d1117; } .col h2 { margin: 2px 0 8px; font-size: 13px; text-transform: uppercase; letter-spacing: .04em; color: #8b949e; } +.tblwrap { overflow-x: auto; -webkit-overflow-scrolling: touch; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #30363d; padding: 6px 8px; vertical-align: top; text-align: left; } th { background: #161b22; } .tl-cell { min-width: 110px; } .banner { border: 1px solid #d29922; background: #d2992211; border-radius: 8px; padding: 8px 12px; margin: 12px 0; color: #e3b341; } +.banner.drew { border-color: #f85149; background: #f8514911; color: #f85149; } .pool { display: grid; grid-template-columns: 220px 1fr; gap: 8px 16px; } meter { width: 140px; height: 14px; } +.chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 10px 0; } +.chips a { border: 1px solid #30363d; border-radius: 999px; padding: 5px 12px; text-decoration: none; color: #e6edf3; background: #161b22; } +.chips a.active { border-color: #1f6feb; background: #1f6feb33; color: #58a6ff; } +.reason { border-left: 3px solid #f85149; padding: 6px 10px; margin: 8px 0 2px; background: #f851490d; } +.orch-note { border-left: 3px solid #1f6feb; padding: 6px 10px; margin: 8px 0 2px; background: #1f6feb0d; } +.cov { border: 1px solid #30363d; border-radius: 8px; padding: 8px 12px; margin: 12px 0; background: #0d1117; } +.cov li { margin: 3px 0; } +.kids { margin: 6px 0 2px 14px; border-left: 2px solid #30363d; padding-left: 10px; } +.kids summary { cursor: pointer; color: #58a6ff; font-size: 12px; padding: 4px 0; } +.obj { display: flex; gap: 10px; align-items: flex-start; } +.obj .n { font-size: 16px; font-weight: 700; color: #58a6ff; min-width: 22px; } .foot { margin-top: 40px; border-top: 1px solid #30363d; padding-top: 10px; color: #8b949e; font-size: 12px; } +@media (max-width: 720px) { + body { font-size: 13.5px; } + main { padding: 12px 10px 60px; } + nav { padding: 8px 10px; } + h1 { font-size: 16px; } + .board { grid-template-columns: 1fr; } + .pool { grid-template-columns: 1fr; } + th, td { padding: 5px 6px; } + meter { width: 96px; } + .card { padding: 8px 10px; } +} `; +/** Canonical tailnet URL for this dashboard (MagicDNS — never the raw IP). */ +export const TAILNET_URL = "http://amd-6.raptor-pumpkinseed.ts.net:4870"; + const NAV = [ + ["/today", "Today"], + ["/attention", "Needs you"], ["/", "Board"], ["/roadmap", "Roadmap"], ["/quota", "Quota"], - ["/attention", "Needs you"], ] as const; function layout(title: string, body: string, provenance: Provenance, active: string): string { @@ -90,10 +135,20 @@ function layout(title: string, body: string, provenance: Provenance, active: str ${esc(title)} · aggregator
${body} -
board: ${esc(provenance.board)} · roadmap: ${esc(provenance.roadmap)} · items: ${esc(provenance.items)} · comments: ${esc(provenance.comments)} · quota: ${esc(provenance.quota)} · attention: ${esc(provenance.attention)}
+
board: ${esc(provenance.board)} · roadmap: ${esc(provenance.roadmap)} · items: ${esc(provenance.items)} · comments: ${esc(provenance.comments)} · quota: ${esc(provenance.quota)} · attention: ${esc(provenance.attention)} · orchestration: ${esc(provenance.orchestration)}
tailnet: ${TAILNET_URL.replace("http://", "")}
`; } +export function coverageHtml(coverage: SourceCoverage[]): string { + const rows = coverage + .map( + (c) => + `
  • ${c.wired ? "✓" : "⚠"} ${esc(c.label)} — ${c.wired ? "wired" : "not wired"} · ${esc(c.detail)}
  • `, + ) + .join(""); + return `
    Session coverage
      ${rows}
    `; +} + function itemBadge(item: GhItem): string { const cls = item.state === "merged" ? "merged" : item.state === "open" ? "open" : "closed"; const kind = item.kind === "pr" ? (item.state === "merged" ? "PR merged" : "PR") : "issue"; @@ -155,34 +210,74 @@ export function renderBoard(board: BoardItem[], items: Map, prov // --- Roadmap view ---------------------------------------------------------- -export function renderRoadmap(rows: RoadmapRow[], items: Map, provenance: Provenance): string { - const tl = buildTimeline(rows); +const GRAINS: [RoadmapGrain, string][] = [ + ["quarter", "Quarter"], + ["month", "Month"], + ["week", "Week"], + ["3d", "Next 3 days"], + ["today", "Today"], +]; + +function roadmapCard(row: RoadmapRow, items: Map): string { + const refs = allRefs([row]); + const refBadges = refs + .map((r) => items.get(r)) + .filter((x): x is GhItem => Boolean(x)) + .map(itemBadge) + .join(" "); + return `
    ${esc(row.title)}
    ${esc(row.status)} ${esc(row.area)} · ${esc(row.horizon)}${refBadges}
    `; +} + +function timelineTable(tl: ReturnType, items: Map): string { const head = `Theme${tl.lanes.map((l) => `${esc(l.label)}`).join("")}`; const body = tl.themes .map((theme) => { const cells = tl.lanes .map((lane) => { const rs = tl.cells.get(theme)?.get(lane.key) ?? []; - const chips = rs - .map((row) => { - const refs = allRefs([row]); - const refBadges = refs - .map((r) => items.get(r)) - .filter((x): x is GhItem => Boolean(x)) - .map(itemBadge) - .join(" "); - return `
    ${esc(row.title)}
    ${esc(row.status)}${refBadges}
    `; - }) - .join(""); - return `${chips}`; + return `${rs.map((r) => roadmapCard(r, items)).join("")}`; }) .join(""); return `${esc(theme)}${cells}`; }) .join(""); + return `
    ${head}${body}
    `; +} + +export function renderRoadmap( + rows: RoadmapRow[], + items: Map, + provenance: Provenance, + grain: RoadmapGrain = "quarter", +): string { + const chips = GRAINS.map( + ([g, label]) => `${label}`, + ).join(""); + let body: string; + if (grain === "quarter") { + body = timelineTable(buildTimeline(rows), items); + } else if (grain === "month") { + body = timelineTable(monthTimeline(rows), items); + } else { + const dg = roadmapDayGrain(rows, grain); + const sections = dg.lanes + .map( + (lane) => + `

    ${esc(lane.label)}

    ${lane.rows.length ? lane.rows.map((r) => roadmapCard(r, items)).join("") : '

    Nothing dated this day.

    '}`, + ) + .join(""); + const notes: string[] = []; + if (dg.outside > 0) notes.push(`${dg.outside} dated row${dg.outside === 1 ? "" : "s"} fall outside this window`); + if (dg.coarse.length > 0) { + notes.push( + `${dg.coarse.length} row${dg.coarse.length === 1 ? "" : "s"} have no calendar date (quarter grain, ongoing, or unscheduled) — see the Quarter view`, + ); + } + body = `${sections}${notes.length ? `

    ${notes.join(" · ")}

    ` : ""}`; + } return layout( "Roadmap", - `

    Roadmap

    Grist's Program roadmap table as a timeline; each row drills down to its linked GitHub issues and their live state.

    ${head}${body}
    `, + `

    Roadmap

    Grist's Program roadmap table at every grain — one data model, switchable horizon. Rows with a calendar date land on their day; quarter-labelled rows stay at quarter grain.

    ${chips}
    ${body}`, provenance, "/roadmap", ); @@ -218,9 +313,9 @@ export function renderItem( return layout( title, `

    ${esc(title)}

    subject: ${esc(subject)}

    ${stripHtml(items, links)} -

    Linked issues / PRs

    ${refRows || ''}
    RefTitleLabelsUpdated
    none resolved
    +

    Linked issues / PRs

    ${refRows || ''}
    RefTitleLabelsUpdated
    none resolved
    ${noteList ? `

    Planning notes

      ${noteList}
    ` : ""} -

    Activity stream

    ${commentRows || ''}
    WhenKindAuthorBody
    no comments
    `, +

    Activity stream

    ${commentRows || ''}
    WhenKindAuthorBody
    no comments
    `, provenance, "/", ); @@ -259,36 +354,144 @@ export function renderQuota(view: QuotaView, provenance: Provenance): string { "Quota + throughput", `

    Quota + throughput

    All pooled quotas, resets, and burn rates. Machine-first: the same data is at /api/quota.json.

    Pools

    ${pools} -

    Burn between resets

    ${burn || ''}
    ProviderPoolFromToTokens
    none
    -

    Model choice

    +

    Burn between resets

    RulePools
    ${burn || ''}
    ProviderPoolFromToTokens
    none
    +

    Model choice

    -
    RulePools
    Headroom for a new session${choices(view.choices.hasHeadroom)}
    Burn-it-before-reset (unused headroom)${choices(view.choices.burnBeforeReset)}
    Do not start a second session${choices(view.choices.doNotStart)}
    `, +Do not start a second session${choices(view.choices.doNotStart)}
    `, provenance, "/quota", ); } -// --- Attention view (#852) -------------------------------------------------- +// --- Attention view (#852, tiered in slice 2) ------------------------------- -export function renderAttention(feed: SessionFeedEntry[], provenance: Provenance): string { - const entries: AttentionEntry[] = attentionSorted(feed); - const rows = entries - .map((e) => { - const extra = - e.awaitingQuestion ?? - e.lastTurnError ?? - (e.repeatedErrorCount ? `${e.repeatedErrorCount} repeated errors` : null) ?? - (e.longRunningCall ? `CLI: ${e.longRunningCall.command ?? "?"}` : null); - const evidence = e.supervisionNote ? `${e.evidence} Keeper: ${e.supervisionNote}` : e.evidence; - return `${esc(e.state)}${esc(e.title ?? e.sessionId)}
    ${esc(e.sessionId)} · ${esc(e.directory ?? "—")} · ${esc(e.branch ?? "—")}${esc(e.model ?? "—")} / ${esc(e.provider ?? "—")}${fmtDate(e.lastActivityAt)}${esc(e.messageCount ?? "—")}${e.messageDelta ? ` (+${e.messageDelta})` : ""}${esc(evidence)}`; - }) - .join(""); +function sessionCard(e: TieredEntry, children: Map, depth = 0): string { + const src = SESSION_SOURCE_LABELS[sourceOf(e)]; + const sub = + e.parentId && depth === 0 + ? ` sub-session${e.agent ? ` · ${esc(e.agent)}` : ""} ↳ ${esc(e.parentId)}` + : e.agent + ? ` ${esc(e.agent)}` + : ""; + const tierBadge = + e.tier === "needs-drew" + ? `needs Drew` + : e.tier === "needs-orchestrator" + ? `needs orchestrator` + : ""; + const evidence = e.supervisionNote ? `${e.evidence} Keeper: ${e.supervisionNote}` : e.evidence; + const reason = e.drewReason ? `
    Why you: ${esc(e.drewReason)}
    ` : ""; + const orch = e.orchestratorNote ? `
    ${esc(e.orchestratorNote)}
    ` : ""; + const kids = children.get(e.sessionId) ?? []; + const kidsHtml = kids.length + ? `
    ${kids.length} sub-session${kids.length === 1 ? "" : "s"}${kids.map((k) => sessionCard(k, children, depth + 1)).join("")}
    ` + : ""; + return `
    ${esc(e.title ?? e.sessionId)} ${esc(src)} ${esc(STATE_LABELS[e.state])}${tierBadge}${sub}
    ${esc(e.sessionId)} · ${esc(e.directory ?? "—")}${e.branch ? ` · ${esc(e.branch)}` : ""} · ${esc(e.model ?? "—")}${e.provider ? ` / ${esc(e.provider)}` : ""} · last activity ${fmtDate(e.lastActivityAt)} · ${esc(e.messageCount ?? "—")} msgs${e.outcome ? ` · outcome: ${esc(e.outcome)}` : ""}
    ${esc(evidence)}${reason}${orch}${kidsHtml}
    `; +} + +/** A #899 tier item that is not a live session — a decision, task, or gap. */ +function tierItemCard(item: TierItem, whyLabel: string): string { + const blocked = item.blockedBy?.length + ? `
    Blocked by: ${item.blockedBy + .map((d) => esc(`${d.task} (${d.status}${d.workerLabel ? `, ${d.workerLabel}` : ""})`)) + .join("; ")}` + : ""; + const question = item.question ? `
    “${esc(item.question)}”` : ""; + const action = item.recommendedAction + ? `
    Recommended: ${esc(item.recommendedAction)}` + : ""; + const ref = item.ref ? `
    ${esc(item.ref)}` : ""; + return `
    ${esc(item.source)} ${esc(item.kind)} ${esc(item.title)}
    ${esc(whyLabel)}: ${esc(item.reason)}${question}${blocked}${action}${ref}
    `; +} + +export function renderAttention(view: AttentionView, coverage: SourceCoverage[], provenance: Provenance): string { + const children = sessionChildren(view.all); + const roots = sessionRoots(view.all); + const drewTotal = view.drew.length + view.drewExtra.length; + const orchTotal = view.orchestrator.length + view.orchestratorExtra.length; + const chips = ``; + const drewCards = + [...view.drew.map((e) => sessionCard(e, children)), ...view.drewExtra.map((i) => tierItemCard(i, "Why you"))].join( + "", + ) || `

    Nothing needs you right now.

    `; + const orchCards = + [ + ...view.orchestrator.map((e) => sessionCard(e, children)), + ...view.orchestratorExtra.map((i) => tierItemCard(i, "Why the fleet")), + ].join("") || `

    The fleet's queue is empty.

    `; + const sessionCards = roots.length + ? roots.map((e) => sessionCard(e, children)).join("") + : `

    No current sessions.

    `; return layout( "Needs you", - `

    Needs you

    Every live agent session, classified and attention-ordered. Machine-first: /api/attention.json.

    -${rows || ''}
    StateSessionModel / providerLast activityMsgsEvidence
    no sessions
    `, + `

    Needs you

    Only what genuinely requires Drew lands in NEEDS DREW — each with its reason. Everything else the fleet can work is the orchestrator's queue. Finished runs and stale items expire out (2 h after a run finishes, 24 h at the latest). Machine-first: /api/attention.json · /api/coverage.json.

    +${chips} +${coverageHtml(coverage)} +

    Needs Drew (${drewTotal})

    ${drewCards} +

    Needs orchestrator (${orchTotal})

    The orchestration job (#899) reviews this queue and pushes work back into motion; it escalates here only what truly needs Drew.

    ${orchCards} +

    All sessions (${roots.length})

    Every current session with its source and state; sub-sessions collapse under their parent.

    ${sessionCards} +${view.expiredCount ? `

    ${view.expiredCount} finished or stale ${view.expiredCount === 1 ? "entry" : "entries"} expired out of this view.

    ` : ""}`, provenance, "/attention", ); } + +// --- Today view (slice 2, #898 §4) ------------------------------------------- + +export function renderToday( + today: TodayView, + attention: AttentionView, + quota: QuotaView, + coverage: SourceCoverage[], + provenance: Provenance, +): string { + const walled = quota.pools.filter((p) => p.state === "walled"); + const alerts: string[] = []; + const drewTotal = attention.drew.length + attention.drewExtra.length; + if (drewTotal) { + alerts.push( + ``, + ); + } + if (walled.length) { + alerts.push( + ``, + ); + } + const provenanceLine = today.fromOrchestrator + ? `

    From the orchestration job's goal measurements (section written ${fmtDate(today.generatedAt)}). Machine-first: /api/today.json · /api/orchestration.json.

    ` + : ``; + const actions = today.actions?.length + ? `

    Pushed back into motion

    ${today.actions.map((a) => `
    ${esc(a.kind)} ${esc(a.target)}
    ${esc(a.summary)}
    ${esc(fmtDate(a.at))}
    `).join("")}` + : ""; + const objectives = today.objectives.length + ? today.objectives + .map( + (o, i) => + `
    ${i + 1}
    ${esc(o.title)} ${esc(o.chip)}${o.detail ? `
    ${esc(o.detail)}` : ""}${o.ref ? `
    ${esc(o.ref)}` : ""}
    `, + ) + .join("") + : `

    No objectives lined up for today.

    `; + const momentum = today.momentum.length + ? today.momentum + .map((m) => { + const done = (m.accomplished ?? []).length + ? `
    Recently accomplished:
      ${(m.accomplished ?? []).map((a) => `
    • ${esc(a)}
    • `).join("")}
    ` + : ""; + const blocked = m.blockedBy ? `
    Blocked by: ${esc(m.blockedBy)}` : ""; + const detail = m.detail ? `
    ${esc(m.detail)}` : ""; + return `
    ${esc(m.project)} ${esc(m.state)}${done}${blocked}${detail}
    `; + }) + .join("") + : `

    No projects to measure yet.

    `; + return layout( + "Today", + `

    Today

    ${provenanceLine}${alerts.join("")} +

    Top objectives

    ${objectives} +

    Project momentum

    ${momentum} +${actions}${coverageHtml(coverage)}`, + provenance, + "/today", + ); +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index a121abaa91..57752487be 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -1,8 +1,8 @@ // The aggregator's HTTP server. Read-mostly: every route is a GET. Pages are // server-rendered HTML; /api/*.json serve the same data machine-first. import { loadConfig } from "./config.ts"; -import { allRefs } from "./derive.ts"; -import { renderAttention, renderBoard, renderItem, renderQuota, renderRoadmap } from "./render.ts"; +import { allRefs, buildAttention, deriveToday, type RoadmapGrain } from "./derive.ts"; +import { renderAttention, renderBoard, renderItem, renderQuota, renderRoadmap, renderToday } from "./render.ts"; import type { Source } from "./source.ts"; import { fixtureSource } from "./sources/fixtures.ts"; import { liveSource } from "./sources/live.ts"; @@ -40,6 +40,24 @@ async function roadmapContext() { return { rows, items }; } +async function attentionContext() { + const [feed, summary, coverage] = await Promise.all([source.attention(), source.orchestration(), source.coverage()]); + return { view: buildAttention(feed, summary), coverage }; +} + +async function todayContext() { + const [{ board, items }, { rows }, { view, coverage }, quota, summary] = await Promise.all([ + boardContext(), + roadmapContext(), + attentionContext(), + source.quota(), + source.orchestration(), + ]); + return { today: deriveToday(board, rows, items, summary), view, coverage, quota }; +} + +const GRAINS = new Set(["quarter", "month", "week", "3d", "today"]); + async function handler(req: Request): Promise { const url = new URL(req.url); const path = url.pathname; @@ -50,9 +68,16 @@ async function handler(req: Request): Promise { return html(renderBoard(board, items, prov())); } + if (path === "/today") { + const { today, view, coverage, quota } = await todayContext(); + return html(renderToday(today, view, quota, coverage, prov())); + } + if (path === "/roadmap") { const { rows, items } = await roadmapContext(); - return html(renderRoadmap(rows, items, prov())); + const g = url.searchParams.get("h") ?? "quarter"; + const grain: RoadmapGrain = GRAINS.has(g) ? (g as RoadmapGrain) : "quarter"; + return html(renderRoadmap(rows, items, prov(), grain)); } if (path === "/quota") { @@ -60,7 +85,8 @@ async function handler(req: Request): Promise { } if (path === "/attention") { - return html(renderAttention(await source.attention(), prov())); + const { view, coverage } = await attentionContext(); + return html(renderAttention(view, coverage, prov())); } if (path === "/api/board.json") { @@ -75,7 +101,19 @@ async function handler(req: Request): Promise { return json(await source.quota()); } if (path === "/api/attention.json") { - return json(await source.attention()); + // Slice 2: the flat array shape stays; entries are now current-only + // (expired dropped) and tier-annotated (tier/drewReason/ + // orchestratorNote, source, parentId). + const { view } = await attentionContext(); + return json(view.all); + } + if (path === "/api/coverage.json") { + const { view, coverage } = await attentionContext(); + return json({ coverage, expired: view.expiredCount }); + } + if (path === "/api/today.json") { + const { today } = await todayContext(); + return json(today); } if (path === "/api/orchestration.json") { // #899: the orchestration job's tiers + goal measurements. Absent diff --git a/pm-stack/aggregator/src/source.ts b/pm-stack/aggregator/src/source.ts index b434376d22..bcb59eb558 100644 --- a/pm-stack/aggregator/src/source.ts +++ b/pm-stack/aggregator/src/source.ts @@ -11,6 +11,7 @@ import type { RefKey, RoadmapRow, SessionFeedEntry, + SourceCoverage, } from "./model.ts"; export interface Source { @@ -28,5 +29,7 @@ export interface Source { attention(): Promise; /** The orchestration job's latest section (#899); null = not measured yet. */ orchestration(): Promise; + /** Which session sources are wired, for the coverage note (slice 2). */ + coverage(): Promise; provenance(): Provenance; } diff --git a/pm-stack/aggregator/src/sources/fixtures.ts b/pm-stack/aggregator/src/sources/fixtures.ts index cb14a6e32a..56e35d7def 100644 --- a/pm-stack/aggregator/src/sources/fixtures.ts +++ b/pm-stack/aggregator/src/sources/fixtures.ts @@ -16,6 +16,7 @@ import { type RefKey, type RoadmapRow, type SessionFeedEntry, + type SourceCoverage, refsInText, refUrl, } from "../model.ts"; @@ -436,28 +437,50 @@ export const FIXTURE_QUOTA: QuotaView = { }; // "Needs you" view (#852). One entry per state so the classifier's ordering -// is exercised; values are illustrative. +// is exercised; values are illustrative. Timestamps are relative to load +// time so the slice-2 freshness expiry behaves the same whenever the +// fixtures render: current entries are minutes old, the finished probe +// is 30 h old and expires out. +const ago = (h: number): string => new Date(Date.now() - h * 3_600_000).toISOString(); export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ { sessionId: "ses_k_wip", + source: "opencode-laptop", title: "pm wave K — aggregator UI", directory: "/home/user/work/id-train/pm-aggregator-ui", branch: "pm/aggregator-ui", model: "deepseek-v4-pro", provider: "cloudflare-gateway", - lastActivityAt: "2026-10-25T02:45:00Z", + lastActivityAt: ago(0.4), messageCount: 41, messageDelta: 3, activeToolCalls: 1, }, + { + // A sub-session of ses_k_wip: collapses under its parent (slice 2). + sessionId: "ses_k_wip_explore", + source: "opencode-laptop", + parentId: "ses_k_wip", + agent: "explore", + outcome: "interrupted", + title: "Explore: locate the projector schema", + directory: "/home/user/work/id-train/pm-aggregator-ui", + model: "deepseek-v4-flash", + provider: "opencode-go", + lastActivityAt: ago(0.5), + messageCount: 6, + messageDelta: 0, + activeToolCalls: 0, + }, { sessionId: "ses_h_connect", + source: "opencode-laptop", title: "pm wave H — connect repos", directory: "/home/user/work/id-train/pm-connect-repos", branch: "pm/connect-repos", model: "claude-opus-5-5", provider: "claude-code", - lastActivityAt: "2026-10-25T02:30:00Z", + lastActivityAt: ago(0.6), messageCount: 88, messageDelta: 0, activeToolCalls: 0, @@ -465,12 +488,13 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ }, { sessionId: "ses_i_kaneo", + source: "opencode-sandbox", title: "pm wave I — Kaneo fork", directory: "/home/user/work/kaneo-fork", branch: "main", model: "muse-wonder-1.0", provider: "muse", - lastActivityAt: "2026-10-25T02:20:00Z", + lastActivityAt: ago(0.8), messageCount: 19, messageDelta: 0, activeToolCalls: 0, @@ -478,31 +502,60 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ }, { sessionId: "ses_j_proj", + source: "opencode-laptop", title: "pm wave J — projector", directory: "/home/user/work/id-train/pm-projector", branch: "pm/projector", model: "claude-opus-5-5", provider: "claude-code", - lastActivityAt: "2026-10-25T02:10:00Z", + lastActivityAt: ago(1), messageCount: 55, messageDelta: 0, activeToolCalls: 1, - longRunningCall: { command: "cargo build --release", startedAt: "2026-10-25T01:40:00Z" }, + longRunningCall: { command: "cargo build --release", startedAt: ago(1.8) }, }, { sessionId: "ses_f_phase13", + source: "opencode-sandbox", title: "id train F — Phase 13", directory: "/home/user/work/id-train/phase-13-impl", branch: "phase-13-impl", model: "claude-opus-5-5", provider: "claude-code", - lastActivityAt: "2026-10-25T01:55:00Z", + lastActivityAt: ago(1.2), messageCount: 102, messageDelta: 0, activeToolCalls: 0, repeatedErrorCount: 4, lastTurnError: "claude_session_limit (retry)", }, + { + // Jules, wired via the keeper's state in slice 2. + sessionId: "4259424002214698449", + source: "jules", + title: "Fix #811: id phase-9: a joiner's resize (up to 500x200) can permanently…", + directory: "developing-today/code", + createdAt: ago(5), + lastActivityAt: ago(0.2), + messageCount: 0, + activeToolCalls: 0, + awaitingQuestion: "Does this look good, and should I proceed?", + supervisionNote: "Jules AWAITING_USER_FEEDBACK · keeper: replied", + }, + { + // A finished one-shot probe: expires out of the view (slice 2). + sessionId: "ses_old_probe", + source: "opencode-sandbox", + outcome: "succeeded", + title: "one-shot probe: GEMINI LIVE", + directory: "/home/hatch/tmp/gemini-probe", + model: "gemini-3.8-flash", + provider: "google", + lastActivityAt: ago(30), + messageCount: 2, + messageDelta: 0, + activeToolCalls: 0, + }, ]; export function fixtureSource(): Source { @@ -514,6 +567,7 @@ export function fixtureSource(): Source { comments: "fixtures", quota: "fixtures", attention: "fixtures", + orchestration: "fixtures", }; return { board: async () => FIXTURE_BOARD, @@ -528,6 +582,33 @@ export function fixtureSource(): Source { // Fixtures carry no orchestration section: "not measured" is the // honest fixture state for a job that only runs live (#899). orchestration: async () => null, + coverage: async (): Promise => [ + { + source: "opencode-sandbox", + label: "OpenCode · sandbox server", + wired: true, + detail: "fixtures", + }, + { + source: "opencode-laptop", + label: "OpenCode · laptop server", + wired: true, + detail: "fixtures", + }, + { + source: "jules", + label: "Jules", + wired: true, + detail: "fixtures (keeper state)", + }, + { + source: "claude-code", + label: "Muse", + wired: false, + detail: + "Not wired — Muse subagents run inside the assistant runtime, which exposes no session registry for the aggregator to read. Gap tracked in #898.", + }, + ], provenance: () => provenance, }; } diff --git a/pm-stack/aggregator/src/sources/jules.ts b/pm-stack/aggregator/src/sources/jules.ts new file mode 100644 index 0000000000..6fe04bc9e9 --- /dev/null +++ b/pm-stack/aggregator/src/sources/jules.ts @@ -0,0 +1,105 @@ +// Jules sessions from the keeper's state file (#898 §5). jules-review +// (the keeper cron) tracks the Jules sessions it supervises in +// jules-review-state.json: an `items` map keyed by the Jules session id +// with { state, title, source, created, last_action, last_action_at, +// note }, plus free-text run notes (jules_note_) carrying the +// run totals. This module maps that shape to SessionFeedEntry rows +// with source "jules" — pure functions, no I/O, so the collector owns +// the file read and tests can feed it literals. +import type { JulesSummary, SessionFeedEntry } from "../model.ts"; + +export interface JulesItem { + state?: string; + title?: string; + /** "sources/github//" */ + source?: string; + created?: string; + last_action?: string; + last_action_at?: string; + note?: string; +} + +export interface JulesReviewState { + items?: Record; + last_run?: string; + [key: string]: unknown; +} + +function repoOf(item: JulesItem): string | undefined { + const m = /^sources\/github\/(.+)$/.exec(item.source ?? ""); + return m ? m[1] : item.source; +} + +/** The question a Jules session is waiting on, when its note quotes one. */ +function askedQuestion(note: string | undefined): string | null { + if (!note) return null; + const m = /asked ['"]([^'"]{4,200})['"]/i.exec(note) ?? /['"]([^'"]{4,200}\?)['"]/.exec(note); + return m ? m[1] : null; +} + +/** Map the keeper's tracked Jules sessions to feed entries. */ +export function mapJulesItems(state: JulesReviewState): SessionFeedEntry[] { + const out: SessionFeedEntry[] = []; + for (const [id, item] of Object.entries(state.items ?? {})) { + const entry: SessionFeedEntry = { + sessionId: id, + source: "jules", + title: item.title, + directory: repoOf(item), + createdAt: item.created, + lastActivityAt: item.last_action_at ?? item.created ?? null, + activeToolCalls: 0, + supervisionNote: `Jules ${item.state ?? "UNKNOWN"}${item.last_action ? ` · keeper: ${item.last_action}` : ""}`, + }; + switch ((item.state ?? "").toUpperCase()) { + case "IN_PROGRESS": + entry.activeToolCalls = 1; + break; + case "AWAITING_USER_FEEDBACK": + entry.awaitingQuestion = + askedQuestion(item.note) ?? "Awaiting feedback in Jules (the keeper usually replies automatically)"; + break; + case "AWAITING_PLAN_APPROVAL": + entry.awaitingQuestion = "Plan awaiting approval in Jules"; + break; + case "FAILED": + entry.lastTurnError = "Jules run failed"; + entry.outcome = "failed"; + break; + case "COMPLETED": + entry.outcome = "succeeded"; + break; + } + out.push(entry); + } + return out; +} + +const TOTALS = + /(\d+) sessions - (\d+) COMPLETED, (\d+) FAILED, (\d+) AWAITING_USER_FEEDBACK, (\d+) AWAITING_PLAN_APPROVAL, (\d+) IN_PROGRESS/; + +/** Keeper totals from the freshest jules_note_ run note, when it parses. */ +export function julesSummary(state: JulesReviewState): JulesSummary { + const summary: JulesSummary = { + at: state.last_run ?? null, + tracked: Object.keys(state.items ?? {}).length, + }; + let bestKey = ""; + let bestText = ""; + for (const [k, v] of Object.entries(state)) { + if (/^jules_note_\d+$/.test(k) && typeof v === "string" && k > bestKey) { + bestKey = k; + bestText = v; + } + } + const m = TOTALS.exec(bestText); + if (m) { + summary.total = Number(m[1]); + summary.completed = Number(m[2]); + summary.failed = Number(m[3]); + summary.awaitingFeedback = Number(m[4]); + summary.awaitingPlan = Number(m[5]); + summary.inProgress = Number(m[6]); + } + return summary; +} diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 0d256251bd..8de6d6739a 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -5,7 +5,7 @@ // provenance strings say exactly which facet is live vs fixture-backed. import { readFile } from "node:fs/promises"; import type { Config } from "../config.ts"; -import { feedAgeText, isOrchestrationSection, loadFeed } from "../feed.ts"; +import { feedAgeText, isOrchestrationSection, loadFeed, type FleetFeed } from "../feed.ts"; import { fixtureSource } from "./fixtures.ts"; import { mapServerSessions } from "./opencode.ts"; import { @@ -13,11 +13,13 @@ import { type Comment, type GhItem, type Link, + type OrchestrationSection, type Provenance, type QuotaView, type RefKey, type RoadmapRow, type SessionFeedEntry, + type SourceCoverage, refsInText, refUrl, } from "../model.ts"; @@ -336,6 +338,7 @@ export function liveSource(cfg: Config): Source { comments: "fixtures", quota: "fixtures", attention: "fixtures", + orchestration: "fixtures", }; async function kaneoCookieHeader(): Promise { @@ -361,6 +364,16 @@ export function liveSource(cfg: Config): Source { return value; } + // Slice-2 coverage state: what the last attention read actually saw, + // so the coverage note describes reality rather than config. + let lastFeed: FleetFeed | null = null; + let laptopSeen: boolean | null = null; + async function getFeed(): Promise { + const feed = await loadFeed(cfg.feedFile); + if (feed) lastFeed = feed; + return feed; + } + // The laptop's OpenChamber-managed OpenCode server: port + password // are read from its state file at request time (the port changes // across restarts). Mapped sessions are cached for 45 s (#890). @@ -372,10 +385,14 @@ export function liveSource(cfg: Config): Source { password?: string; }; if (!state.port || !state.password) return null; - const mapped = await mapServerSessions({ - baseUrl: `http://127.0.0.1:${state.port}`, - password: state.password, - }); + const mapped = await mapServerSessions( + { + baseUrl: `http://127.0.0.1:${state.port}`, + password: state.password, + }, + Date.now(), + { source: "opencode-laptop" }, + ); if (!mapped) return null; laptopCache = { value: mapped.entries, at: Date.now() }; return mapped.entries; @@ -442,7 +459,7 @@ export function liveSource(cfg: Config): Source { // on the sandbox by scripts/collect-fleet-feed.ts. A stale feed // keeps rendering, with its age in provenance; fixtures only when // no feed exists at all. - const feed = await loadFeed(cfg.feedFile); + const feed = await getFeed(); if (feed) { provenance.quota = `live (fleet feed · ${feedAgeText(feed.generatedAt)} · collected ${feed.generatedAt})`; return feed.quota; @@ -457,7 +474,7 @@ export function liveSource(cfg: Config): Source { const parts: string[] = []; const byId = new Map(); - const feed = await loadFeed(cfg.feedFile); + const feed = await getFeed(); if (feed) { for (const e of feed.attention) byId.set(e.sessionId, e); parts.push(`sandbox via fleet feed (${feedAgeText(feed.generatedAt)})`); @@ -466,10 +483,14 @@ export function liveSource(cfg: Config): Source { try { const laptop = await laptopSessions(); if (laptop) { + laptopSeen = true; for (const e of laptop) byId.set(e.sessionId, e); parts.push("laptop live"); + } else { + laptopSeen = false; } } catch { + laptopSeen = false; /* laptop part fails soft */ } @@ -480,16 +501,64 @@ export function liveSource(cfg: Config): Source { provenance.attention = "fixtures (no live attention source reachable)"; return fix.attention(); }, - async orchestration() { + async orchestration(): Promise { // #899: the orchestration section rides the fleet feed, embedded // by the collector from the orchestrator's own output file. The // section carries its own provenance; absent = not measured yet. - const feed = await loadFeed(cfg.feedFile); + const feed = await getFeed(); if (feed?.orchestration && isOrchestrationSection(feed.orchestration)) { + provenance.orchestration = `live (orchestration section ${feed.orchestration.runId} · ${feedAgeText(feed.orchestration.generatedAt)})`; return feed.orchestration; } + provenance.orchestration = feed + ? "none yet — the orchestration job (#899) has not published a section; the today view derives" + : "fixtures (no fleet feed file yet)"; return null; }, + async coverage(): Promise { + const feed = lastFeed ?? (await getFeed()); + const out: SourceCoverage[] = []; + out.push({ + source: "opencode-sandbox", + label: "OpenCode · sandbox server", + wired: Boolean(feed), + detail: feed + ? `via fleet feed (${feedAgeText(feed.generatedAt)}, collected ${feed.generatedAt})` + : "no fleet feed file — sandbox sessions are not visible", + }); + out.push({ + source: "opencode-laptop", + label: "OpenCode · laptop server", + wired: laptopSeen === true, + detail: + laptopSeen === true + ? "live from the OpenChamber-managed server (45 s cache)" + : laptopSeen === false + ? "unreachable on the last read — laptop sessions may be missing" + : "not read yet this process", + }); + const j = feed?.julesSummary; + out.push({ + source: "jules", + label: "Jules", + wired: Boolean(j), + detail: j + ? `via the keeper's state (jules-review) · ${j.tracked} tracked now · last keeper run ${j.at ?? "unknown"}${ + j.total != null + ? ` · last run totals: ${j.total} sessions — ${j.completed ?? 0} completed, ${j.failed ?? 0} failed, ${j.inProgress ?? 0} in progress, ${j.awaitingFeedback ?? 0} awaiting feedback (completed runs are pruned by the keeper)` + : "" + }` + : "keeper state not in the feed — Jules sessions are not visible", + }); + out.push({ + source: "claude-code", + label: "Muse", + wired: false, + detail: + "Not wired — Muse subagents run inside the assistant runtime, which exposes no session registry for the aggregator to read. Gap tracked in #898.", + }); + return out; + }, provenance: () => provenance, }; } diff --git a/pm-stack/aggregator/src/sources/opencode.ts b/pm-stack/aggregator/src/sources/opencode.ts index fe9ac1a08a..268b71b98e 100644 --- a/pm-stack/aggregator/src/sources/opencode.ts +++ b/pm-stack/aggregator/src/sources/opencode.ts @@ -10,7 +10,7 @@ // GET /api/session/{id}/message?limit=N -> { data: Message[] } (newest // first), GET /api/permission/request -> { data: PermissionRequest[] }, // GET /api/session/{id}/form -> { data: Form[] }. -import type { SessionFeedEntry } from "../model.ts"; +import type { SessionFeedEntry, SessionSource } from "../model.ts"; export interface OpenCodeTarget { baseUrl: string; @@ -24,6 +24,10 @@ interface V2Session { model?: { id?: string; providerID?: string }; tokens?: { input?: number; output?: number; reasoning?: number }; outcome?: string | null; + /** Present on sub-sessions: the spawning session's id (probed live). */ + parentID?: string | null; + /** Present on sub-sessions: the subagent name (e.g. "explore"). */ + agent?: string; time?: { created?: number; updated?: number; idle?: number }; location?: { directory?: string }; subpath?: string; @@ -112,7 +116,7 @@ export interface MappedSessions { export async function mapServerSessions( target: OpenCodeTarget, now = Date.now(), - opts: { messageLimit?: number; maxDetailed?: number } = {}, + opts: { messageLimit?: number; maxDetailed?: number; source?: SessionSource } = {}, ): Promise { const list = await getJson<{ data: V2Session[] }>(target, "/api/session?limit=100"); if (!list?.data) return null; @@ -146,7 +150,7 @@ export async function mapServerSessions( const entries: SessionFeedEntry[] = []; for (const s of included) { - entries.push(await mapOne(target, s, activeIds, pendingBySession.get(s.id), opts.messageLimit ?? 40)); + entries.push(await mapOne(target, s, activeIds, pendingBySession.get(s.id), opts.messageLimit ?? 40, opts.source)); } return { entries, tokensBySession, activeIds }; } @@ -157,9 +161,17 @@ async function mapOne( activeIds: Set, pending: V2PermissionRequest | undefined, messageLimit: number, + source?: SessionSource, ): Promise { const entry: SessionFeedEntry = { sessionId: s.id, + source, + parentId: s.parentID ?? null, + agent: s.agent, + // A session the server holds active is mid-run; any stored outcome + // belongs to an earlier run of it and must not mark it finished. + outcome: activeIds.has(s.id) ? null : (s.outcome ?? null), + createdAt: iso(s.time?.created) ?? undefined, title: s.title, directory: s.location?.directory, model: s.model?.id, diff --git a/pm-stack/aggregator/test/boot.test.ts b/pm-stack/aggregator/test/boot.test.ts index 29f2309e54..a28ee68980 100644 --- a/pm-stack/aggregator/test/boot.test.ts +++ b/pm-stack/aggregator/test/boot.test.ts @@ -63,6 +63,34 @@ describe("server boots from fixtures", () => { const attention = await (await fetch(`http://127.0.0.1:${port}/attention`)).text(); expect(quota.includes("Quota + throughput")).toBe(true); expect(attention.includes("Needs you")).toBe(true); + expect(attention.includes("Needs Drew")).toBe(true); + expect(attention.includes("Session coverage")).toBe(true); + expect(attention.includes("amd-6.raptor-pumpkinseed.ts.net")).toBe(true); + }); + + test("today page + slice-2 JSON endpoints (today, coverage, horizons)", async () => { + const today = await (await fetch(`http://127.0.0.1:${port}/today`)).text(); + expect(today.includes("Top objectives")).toBe(true); + expect(today.includes("Project momentum")).toBe(true); + const todayJson = (await (await fetch(`http://127.0.0.1:${port}/api/today.json`)).json()) as { + objectives: unknown[]; + momentum: unknown[]; + fromOrchestrator: boolean; + }; + expect(todayJson.objectives.length).toBeGreaterThan(0); + expect(todayJson.momentum.length).toBeGreaterThan(0); + // Fixtures carry no orchestration section (#899: "not measured" is + // the honest fixture state), so the today view derives — labelled. + expect(todayJson.fromOrchestrator).toBe(false); + const coverage = (await (await fetch(`http://127.0.0.1:${port}/api/coverage.json`)).json()) as { + coverage: { source: string; wired: boolean }[]; + expired: number; + }; + expect(coverage.coverage.find((c) => c.source === "jules")?.wired).toBe(true); + expect(coverage.coverage.find((c) => c.source === "claude-code")?.wired).toBe(false); + expect(coverage.expired).toBeGreaterThan(0); // the finished fixture probe + const week = await (await fetch(`http://127.0.0.1:${port}/roadmap?h=week`)).text(); + expect(week.includes("Next 3 days")).toBe(true); }); test("machine-first JSON endpoints", async () => { diff --git a/pm-stack/aggregator/test/opencode.test.ts b/pm-stack/aggregator/test/opencode.test.ts index 1e04bc88cf..34d4623aec 100644 --- a/pm-stack/aggregator/test/opencode.test.ts +++ b/pm-stack/aggregator/test/opencode.test.ts @@ -44,6 +44,17 @@ const sessions = [ time: { created: old, updated: old }, location: { directory: "/work/d" }, }, + { + id: "ses_child", + title: "explore child", + parentID: "ses_active", + agent: "explore", + model: { id: "deepseek-v4-flash", providerID: "opencode-go" }, + tokens: { input: 3, output: 1, reasoning: 0 }, + outcome: "interrupted", + time: { created: recent - 30_000, updated: recent }, + location: { directory: "/work/a" }, + }, ]; const messages: Record = { @@ -70,6 +81,7 @@ const messages: Record = { ], ses_question: [{ id: "m1", type: "user", time: { created: recent }, text: "go" }], ses_stale: [{ id: "m1", type: "user", time: { created: old }, text: "go" }], + ses_child: [{ id: "m1", type: "user", time: { created: recent }, text: "explore" }], }; let server: ReturnType; @@ -121,6 +133,18 @@ describe("opencode v2 mapper", () => { const question = byId.get("ses_question")!; expect(question.awaitingQuestion).toContain("Permission pending"); + + // Sub-session linkage (slice 2): parent, agent, outcome, created. + const child = byId.get("ses_child")!; + expect(child.parentId).toBe("ses_active"); + expect(child.agent).toBe("explore"); + expect(child.outcome).toBe("interrupted"); + expect(child.createdAt).toBeTruthy(); + }); + + test("stamps the entry source when asked", async () => { + const mapped = await mapServerSessions({ baseUrl, password: "x" }, NOW, { source: "opencode-laptop" }); + expect(mapped!.entries.every((e) => e.source === "opencode-laptop")).toBe(true); }); test("unreachable server fails soft (null)", async () => { diff --git a/pm-stack/aggregator/test/render.test.ts b/pm-stack/aggregator/test/render.test.ts index 1c5a9dd3d5..71cbd4a0f2 100644 --- a/pm-stack/aggregator/test/render.test.ts +++ b/pm-stack/aggregator/test/render.test.ts @@ -1,5 +1,13 @@ import { describe, expect, test } from "bun:test"; -import { attentionSorted, classifyAttention, executionStrip, laneFor, timeline, allRefs } from "../src/derive.ts"; +import { + attentionSorted, + buildAttention, + classifyAttention, + executionStrip, + laneFor, + timeline, + allRefs, +} from "../src/derive.ts"; import { parseRef, refKey, @@ -199,11 +207,14 @@ describe("render smoke (fixtures)", () => { expect(html).toContain("Headroom for a new session"); expect(html).toContain("Antigravity"); }); - test("attention view renders attention-ordered sessions with evidence", async () => { + test("attention view renders the tiered needs-you page", async () => { const src = fixtureSource(); - const html = renderAttention(await src.attention(), src.provenance()); + const view = buildAttention(await src.attention(), await src.orchestration()); + const html = renderAttention(view, await src.coverage(), src.provenance()); expect(html).toContain("Needs you"); - expect(html).toContain("stopped-for-question"); + expect(html).toContain("Needs Drew"); + expect(html).toContain("Needs orchestrator"); + expect(html).toContain("waiting for an answer"); expect(html).toContain("Waiting on:"); }); }); diff --git a/pm-stack/aggregator/test/slice2.test.ts b/pm-stack/aggregator/test/slice2.test.ts new file mode 100644 index 0000000000..50a1e6991f --- /dev/null +++ b/pm-stack/aggregator/test/slice2.test.ts @@ -0,0 +1,344 @@ +import { describe, expect, test } from "bun:test"; +import { + buildAttention, + chicagoYmd, + deriveToday, + monthTimeline, + partitionFresh, + roadmapDayGrain, + sessionChildren, + sessionRoots, +} from "../src/derive.ts"; +import { type OrchestrationSection, type RoadmapRow, type SessionFeedEntry, type TierItem } from "../src/model.ts"; +import { renderAttention, renderRoadmap, renderToday } from "../src/render.ts"; +import { + FIXTURE_ATTENTION, + FIXTURE_BOARD, + FIXTURE_ITEMS, + FIXTURE_ROADMAP, + fixtureSource, +} from "../src/sources/fixtures.ts"; +import { julesSummary, mapJulesItems, type JulesReviewState } from "../src/sources/jules.ts"; + +const NOW = Date.parse("2026-10-25T15:00:00Z"); +const iso = (ms: number) => new Date(ms).toISOString(); + +const tierItem = (over: Partial): TierItem => ({ + id: "x", + kind: "task", + title: "Item", + source: "github", + reason: "Because.", + since: iso(NOW), + lastSeenAt: iso(NOW), + ...over, +}); + +const section = (over: Partial): OrchestrationSection => ({ + version: 1, + generatedAt: iso(NOW), + runId: "orch-test", + provenance: "test run", + tiers: { needsDrew: [], needsOrchestrator: [] }, + dependencies: [], + goals: [], + actions: [], + ...over, +}); + +/** The fixture-feed section: ses_h_connect escalated to Drew by #899. */ +const SECTION = section({ + tiers: { + needsDrew: [ + tierItem({ + id: "ses_h_connect", + kind: "session", + sessionId: "ses_h_connect", + title: "Connect the app", + source: "opencode-laptop", + reason: "Only Drew can pick which repo installs the developing.today app first.", + }), + tierItem({ + id: "goal_plaid", + kind: "task", + title: "Link the Citi accounts in Plaid", + source: "tracked", + reason: "Only Drew can complete the bank sign-in in his own browser.", + }), + ], + needsOrchestrator: [], + }, +}); + +describe("freshness expiry (#898 §2/§5)", () => { + test("finished runs expire after 2h; anything after 24h; fresh stays", () => { + const feed: SessionFeedEntry[] = [ + { sessionId: "fresh-err", lastActivityAt: iso(NOW - 10 * 60_000), lastTurnError: "boom", activeToolCalls: 0 }, + { sessionId: "done-3h", lastActivityAt: iso(NOW - 3 * 3_600_000), outcome: "succeeded", activeToolCalls: 0 }, + { + sessionId: "done-1h", + lastActivityAt: iso(NOW - 1 * 3_600_000), + outcome: "failed", + lastTurnError: "x", + activeToolCalls: 0, + }, + { sessionId: "ancient", lastActivityAt: iso(NOW - 30 * 3_600_000), activeToolCalls: 1 }, + { sessionId: "no-time", lastActivityAt: null, lastTurnError: "boom", activeToolCalls: 0 }, + ]; + const { current, expired } = partitionFresh(feed, NOW); + expect(current.map((e) => e.sessionId).sort()).toEqual(["done-1h", "fresh-err", "no-time"]); + expect(expired.map((e) => e.sessionId).sort()).toEqual(["ancient", "done-3h"]); + }); +}); + +describe("tiering (#898 §2)", () => { + const entry = (extra: Partial): SessionFeedEntry => ({ + sessionId: "s", + lastActivityAt: iso(NOW - 60_000), + activeToolCalls: 0, + ...extra, + }); + + test("decision-shaped questions need Drew, with the reason stated", () => { + const view = buildAttention([entry({ awaitingQuestion: "Should I merge this now, or wait?" })], null, NOW); + expect(view.drew).toHaveLength(1); + expect(view.drew[0].drewReason).toContain("Waiting on your decision"); + }); + + test("routine questions and errors are the orchestrator's", () => { + const view = buildAttention( + [ + entry({ sessionId: "q", awaitingQuestion: "What is the capital of France?" }), + entry({ sessionId: "e", lastTurnError: "429 subscription quota exhausted" }), + entry({ sessionId: "p", awaitingQuestion: "Permission pending: bash: bun test" }), + ], + null, + NOW, + ); + expect(view.drew).toHaveLength(0); + expect(view.orchestrator).toHaveLength(3); + expect(view.orchestrator.every((e) => (e.orchestratorNote ?? "").length > 0)).toBe(true); + }); + + test("destructive permission requests need Drew", () => { + const view = buildAttention([entry({ awaitingQuestion: "Permission pending: bash: rm -rf build" })], null, NOW); + expect(view.drew).toHaveLength(1); + expect(view.drew[0].drewReason).toContain("destructive"); + }); + + test("credential walls need Drew", () => { + const view = buildAttention( + [entry({ lastTurnError: "sign-in required: verification code sent to your email" })], + null, + NOW, + ); + expect(view.drew).toHaveLength(1); + expect(view.drew[0].drewReason).toContain("sign-in only you can complete"); + }); + + test("the orchestration section's classification overrides local rules, reason verbatim", () => { + const sec = section({ + tiers: { + needsDrew: [tierItem({ id: "s", kind: "session", sessionId: "s", reason: "Only Drew can do this thing." })], + needsOrchestrator: [], + }, + }); + const view = buildAttention([entry({ lastTurnError: "plain error" })], sec, NOW); + expect(view.drew).toHaveLength(1); + expect(view.drew[0].drewReason).toBe("Only Drew can do this thing."); + // Section items not backed by a live session in this feed (a task, + // or a session on a server outside the feed) render as tier cards. + const withExtra = buildAttention([entry({ lastTurnError: "plain error" })], SECTION, NOW); + expect(withExtra.drewExtra.map((i) => i.id)).toEqual(["ses_h_connect", "goal_plaid"]); + }); + + test("Jules questions belong to the keeper, not Drew", () => { + const view = buildAttention( + [ + entry({ + sessionId: "4259424002214698449", + source: "jules", + awaitingQuestion: "Does this look good, and should I proceed?", + }), + ], + null, + NOW, + ); + expect(view.drew).toHaveLength(0); + expect(view.orchestrator).toHaveLength(1); + }); + + test("in-motion sessions are in neither queue", () => { + const view = buildAttention([entry({ activeToolCalls: 2 })], null, NOW); + expect(view.drew).toHaveLength(0); + expect(view.orchestrator).toHaveLength(0); + expect(view.all[0].tier).toBe("in-motion"); + }); +}); + +describe("session hierarchy (#898 §5)", () => { + test("children group under parents; roots exclude them", () => { + const view = buildAttention(FIXTURE_ATTENTION, SECTION); + const children = sessionChildren(view.all); + const roots = sessionRoots(view.all); + expect(children.get("ses_k_wip")?.map((e) => e.sessionId)).toEqual(["ses_k_wip_explore"]); + expect(roots.some((e) => e.sessionId === "ses_k_wip_explore")).toBe(false); + expect(roots.some((e) => e.sessionId === "ses_k_wip")).toBe(true); + // The finished fixture probe expired out entirely. + expect(view.all.some((e) => e.sessionId === "ses_old_probe")).toBe(false); + expect(view.expiredCount).toBeGreaterThanOrEqual(1); + // The section's classification puts ses_h_connect in NEEDS DREW. + expect(view.drew.some((e) => e.sessionId === "ses_h_connect")).toBe(true); + }); +}); + +describe("jules mapping (#898 §5)", () => { + const state: JulesReviewState = { + last_run: "2026-10-25T14:58:00Z", + items: { + "4259424002214698449": { + state: "AWAITING_USER_FEEDBACK", + title: "Fix #811: a joiner's resize", + source: "sources/github/developing-today/code", + created: "2026-10-25T12:44:14Z", + last_action: "replied", + last_action_at: "2026-10-25T14:58:25Z", + note: "Agent reported work done and asked 'Does this look good, and should I proceed?' Replied.", + }, + "999": { + state: "FAILED", + title: "Broke", + source: "sources/github/developing-today/opencode", + last_action_at: "2026-10-25T10:00:00Z", + }, + }, + jules_note_1458: + "Jules list this run: 84 sessions - 77 COMPLETED, 6 FAILED, 1 AWAITING_USER_FEEDBACK, 0 AWAITING_PLAN_APPROVAL, 0 IN_PROGRESS. 1 Jules response sent.", + }; + + test("maps keeper items to Jules feed entries", () => { + const entries = mapJulesItems(state); + const awaiting = entries.find((e) => e.sessionId === "4259424002214698449")!; + expect(awaiting.source).toBe("jules"); + expect(awaiting.directory).toBe("developing-today/code"); + expect(awaiting.awaitingQuestion).toBe("Does this look good, and should I proceed?"); + const failed = entries.find((e) => e.sessionId === "999")!; + expect(failed.outcome).toBe("failed"); + expect(failed.lastTurnError).toContain("failed"); + }); + + test("parses keeper totals", () => { + const s = julesSummary(state); + expect(s.total).toBe(84); + expect(s.completed).toBe(77); + expect(s.failed).toBe(6); + expect(s.tracked).toBe(2); + expect(s.at).toBe("2026-10-25T14:58:00Z"); + }); +}); + +describe("roadmap grains (#898 §3)", () => { + test("month timeline places dated rows by month and keeps quarter grain", () => { + const tl = monthTimeline(FIXTURE_ROADMAP); + const keys = tl.lanes.map((l) => l.key); + expect(keys).toContain("2026-10"); + expect(keys).toContain("2026-Q4"); + }); + + test("day grains window the dated rows and count the rest honestly", () => { + const now = new Date("2026-10-24T18:00:00Z"); // Sat Oct 24, Chicago + expect(chicagoYmd(now)).toBe("2026-10-24"); + const today = roadmapDayGrain(FIXTURE_ROADMAP, "today", now); + expect(today.lanes).toHaveLength(1); + expect(today.lanes[0].rows.length).toBeGreaterThan(0); // the 2026-10-24 seed row + expect(today.coarse.length).toBeGreaterThan(0); // quarter-grain rows + const week = roadmapDayGrain(FIXTURE_ROADMAP, "week", now); + expect(week.lanes).toHaveLength(7); + }); + + test("roadmap renders the horizon switcher at day grain", async () => { + const src = fixtureSource(); + const row: RoadmapRow = { + id: 99, + subject: "grist:doc/Roadmap/99", + title: "Dated today row", + area: "PM stack", + status: "Planned", + horizon: chicagoYmd(), + source: "", + notes: "", + links: [], + }; + const html = renderRoadmap([...FIXTURE_ROADMAP, row], await src.items([]), src.provenance(), "today"); + expect(html).toContain("Next 3 days"); + expect(html).toContain("Dated today row"); + expect(html).toContain("no calendar date"); + }); +}); + +describe("today view (#898 §4)", () => { + const items = new Map(FIXTURE_ITEMS.map((i) => [i.ref, i])); + + test("renders the orchestration section when present", () => { + const sec = section({ + goals: [ + { + goalId: null, + goal: "Keep the four repos healthy", + momentum: "blocked", + summary: "Waiting on the GitHub App route.", + linedUp: [ + { + title: "Ship aggregator slice 2", + status: "in-progress", + horizon: "today", + horizonWhy: "Drew asked for it today", + blockedBy: [{ task: "CI green", status: "in-progress" }], + }, + ], + progressedSinceLastRun: ["PR #892 merged"], + stalled: [], + gaps: [], + }, + ], + }); + const today = deriveToday(FIXTURE_BOARD, FIXTURE_ROADMAP, items, sec); + expect(today.fromOrchestrator).toBe(true); + expect(today.objectives[0].title).toBe("Ship aggregator slice 2"); + expect(today.objectives[0].chip).toContain("orchestrator"); + expect(today.objectives[0].detail).toContain("blocked by CI green"); + expect(today.momentum[0].state).toBe("blocked"); + expect(today.momentum[0].accomplished).toEqual(["PR #892 merged"]); + }); + + test("derives objectives + momentum without a summary, and says so on the page", async () => { + const today = deriveToday(FIXTURE_BOARD, FIXTURE_ROADMAP, items, null); + expect(today.fromOrchestrator).toBe(false); + expect(today.objectives.length).toBeGreaterThan(0); + expect(today.momentum.length).toBeGreaterThan(0); + const src = fixtureSource(); + const attention = buildAttention(await src.attention(), null); + const html = renderToday(today, attention, await src.quota(), await src.coverage(), src.provenance()); + expect(html).toContain("Top objectives"); + expect(html).toContain("Project momentum"); + expect(html).toContain("has not published a goal-measurement section yet"); + }); +}); + +describe("attention render (slice 2)", () => { + test("tiers, reasons, source labels, collapse, coverage, expiry all render", async () => { + const src = fixtureSource(); + const view = buildAttention(await src.attention(), SECTION); + const html = renderAttention(view, await src.coverage(), src.provenance()); + expect(html).toContain("Needs Drew"); + expect(html).toContain("Why you:"); + expect(html).toContain("Only Drew can pick which repo installs"); + expect(html).toContain("OpenCode · laptop"); + expect(html).toContain("Jules"); + expect(html).toContain("sub-session"); + expect(html).toContain("Session coverage"); + expect(html).toContain("not wired"); + expect(html).toContain("expired out of this view"); + expect(html).not.toContain("one-shot probe"); // the expired fixture entry + }); +});