From 81a83164518a081601d53b6e4b2ba4d855d86400 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:10:59 +0000 Subject: [PATCH 1/8] =?UTF-8?q?feat(aggregator):=20slice-2=20model=20?= =?UTF-8?q?=E2=80=94=20session=20sources,=20tiers,=20orchestration=20summa?= =?UTF-8?q?ry?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SessionFeedEntry gains source/parentId/agent/outcome/createdAt; new AttentionTier + TieredEntry, SourceCoverage, OrchestrationSummary and JulesSummary shapes; FleetFeed carries optional julesSummary and orchestration sections (contract posted on #899). Provenance gains an orchestration facet. --- pm-stack/aggregator/src/feed.ts | 20 ++++- pm-stack/aggregator/src/model.ts | 97 +++++++++++++++++++++ pm-stack/aggregator/src/sources/fixtures.ts | 1 + pm-stack/aggregator/src/sources/live.ts | 1 + 4 files changed, 117 insertions(+), 2 deletions(-) diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 277bd2cbc6..6909f35b4b 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -4,15 +4,31 @@ // 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 { QuotaView, SessionFeedEntry } from "./model.ts"; +import type { JulesSummary, OrchestrationSummary, 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; + /** Orchestration summary from #899's job (slice 2); absent until it writes one. */ + orchestration?: OrchestrationSummary; +} + +/** Loose validation of an orchestration summary (contract on #899). */ +export function isOrchestrationSummary(v: unknown): v is OrchestrationSummary { + if (typeof v !== "object" || v === null) return false; + const o = v as Partial; + return ( + typeof o.generatedAt === "string" && + Array.isArray(o.objectives) && + Array.isArray(o.momentum) && + Array.isArray(o.escalations) + ); } export function isFleetFeed(v: unknown): v is FleetFeed { diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index efcf1e5ff4..d33e8e9fff 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,83 @@ 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; +} + +// --------------------------------------------------------------------------- +// Orchestration summary (#899 -> today view, #898 §4). Written by the +// orchestration job on the sandbox as orchestration-state.json and +// embedded into the fleet feed by the collector. The aggregator renders +// it verbatim; until it exists the today view derives and says so. +// --------------------------------------------------------------------------- + +export interface OrchestrationObjective { + title: string; + horizon?: "today" | "tomorrow" | "3d" | "week" | "longer"; + status?: string; + detail?: string; + /** Repo-qualified ref the objective tracks, when it has one. */ + ref?: RefKey; +} + +export interface OrchestrationMomentum { + project: string; + state: "moving" | "stalled" | "blocked"; + accomplished?: string[]; + blockedBy?: string; + detail?: string; +} + +export interface OrchestrationEscalation { + sessionId?: string; + title?: string; + reason: string; + at: string; +} + +export interface OrchestrationSummary { + generatedAt: string; + objectives: OrchestrationObjective[]; + momentum: OrchestrationMomentum[]; + escalations: OrchestrationEscalation[]; + notes?: 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/sources/fixtures.ts b/pm-stack/aggregator/src/sources/fixtures.ts index dd8fcb1035..c2b2a00269 100644 --- a/pm-stack/aggregator/src/sources/fixtures.ts +++ b/pm-stack/aggregator/src/sources/fixtures.ts @@ -514,6 +514,7 @@ export function fixtureSource(): Source { comments: "fixtures", quota: "fixtures", attention: "fixtures", + orchestration: "fixtures", }; return { board: async () => FIXTURE_BOARD, diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index ad4ab233a6..2f6a6d977f 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -336,6 +336,7 @@ export function liveSource(cfg: Config): Source { comments: "fixtures", quota: "fixtures", attention: "fixtures", + orchestration: "fixtures", }; async function kaneoCookieHeader(): Promise { From 56d4bd0da3325cc03f97c81d5eff4c87d5112bdc Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:12:00 +0000 Subject: [PATCH 2/8] =?UTF-8?q?feat(aggregator):=20slice-2=20derivations?= =?UTF-8?q?=20=E2=80=94=20tiers,=20expiry,=20hierarchy,=20roadmap=20grains?= =?UTF-8?q?,=20today?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit buildAttention expires finished runs (>2h) and anything >24h, then tiers every classified session: orchestrator escalations first (reason verbatim), keeper escalations, decision-shaped questions, destructive permission requests and credential walls land in NEEDS DREW with a per-item reason; everything else actionable is NEEDS ORCHESTRATOR with the fleet's next step. Roadmap gains month/week/ 3-day/today grains over the same rows (Chicago calendar); deriveToday renders the #899 orchestration summary when present and otherwise derives objectives + per-project momentum from board/roadmap/items. --- pm-stack/aggregator/src/derive.ts | 405 ++++++++++++++++++++++++++++++ 1 file changed, 405 insertions(+) diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index e79b6a14f6..dd4c7e478e 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -205,3 +205,408 @@ 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, + OrchestrationSummary, + SessionSource, + 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.", +}; + +/** + * Assign each classified entry its tier. Rule order matters — the first + * match wins, and an orchestration escalation (#899) outranks every + * local rule, carrying its reason verbatim. + */ +export function tierEntry(e: AttentionEntry, summary?: OrchestrationSummary | null): TieredEntry { + const esc = summary?.escalations.find( + (x) => (x.sessionId && x.sessionId === e.sessionId) || (x.title && x.title === e.title), + ); + if (esc && e.state !== "in-motion") { + return { ...e, tier: "needs-drew", drewReason: esc.reason }; + } + 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)) { + 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[]; + /** 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[], + summary?: OrchestrationSummary | null, + now = Date.now(), +): AttentionView { + const { current, expired } = partitionFresh(feed, now); + const all = current + .map((e) => tierEntry(classifyAttention(e, now), summary)) + .sort((a, b) => a.order - b.order || (b.lastActivityAt ?? "").localeCompare(a.lastActivityAt ?? "")); + return { + drew: all.filter((e) => e.tier === "needs-drew"), + orchestrator: all.filter((e) => e.tier === "needs-orchestrator"), + 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 summary. */ + fromOrchestrator: boolean; + generatedAt?: string; +} + +const HORIZON_ORDER: Record = { today: 0, tomorrow: 1, "3d": 2, week: 3, longer: 4 }; +const PRIORITY_ORDER: Record = { urgent: 0, high: 1, normal: 2, medium: 2, low: 3 }; + +export function deriveToday( + board: BoardItem[], + rows: RoadmapRow[], + items: Map, + summary: OrchestrationSummary | null, + now = new Date(), +): TodayView { + if (summary) { + return { + fromOrchestrator: true, + generatedAt: summary.generatedAt, + objectives: [...summary.objectives] + .sort((a, b) => (HORIZON_ORDER[a.horizon ?? "longer"] ?? 5) - (HORIZON_ORDER[b.horizon ?? "longer"] ?? 5)) + .map((o) => ({ + title: o.title, + detail: [o.status, o.detail].filter(Boolean).join(" — ") || undefined, + chip: `orchestrator${o.horizon ? ` · ${o.horizon}` : ""}`, + ref: o.ref, + })), + momentum: summary.momentum.map((m) => ({ + project: m.project, + state: m.state, + accomplished: m.accomplished ?? [], + blockedBy: m.blockedBy, + detail: m.detail, + })), + }; + } + + // 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 }; +} From 0693dae7dde0fafb936422e4ec5942932b429682 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:12:50 +0000 Subject: [PATCH 3/8] =?UTF-8?q?feat(aggregator):=20slice-2=20session=20sou?= =?UTF-8?q?rces=20=E2=80=94=20parent/agent/outcome=20mapping,=20Jules=20wi?= =?UTF-8?q?ring?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The OpenCode v2 mapper now carries parentID (sub-sessions), agent, createdAt and outcome (cleared while the server holds the session active), stamping each entry with its source. New sources/jules.ts maps the keeper's jules-review-state.json items to Jules feed entries (AWAITING_USER_FEEDBACK -> awaiting a question, FAILED -> errored, COMPLETED -> finished) and parses the keeper's run totals. The collector stamps sandbox entries, merges Jules in, and embeds the #899 orchestration summary (orchestration-state.json) when present. --- .../aggregator/scripts/collect-fleet-feed.ts | 37 +++++- pm-stack/aggregator/src/sources/jules.ts | 105 ++++++++++++++++++ pm-stack/aggregator/src/sources/opencode.ts | 18 ++- 3 files changed, 152 insertions(+), 8 deletions(-) create mode 100644 pm-stack/aggregator/src/sources/jules.ts diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 3f92b6e31a..ff436da51c 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -16,15 +16,16 @@ // // Usage: bun run scripts/collect-fleet-feed.ts [--out ] // Env overrides: QUOTA_VIEW_PATH, JULES_STATE_PATH, SANDBOX_OPENCODE_URL, -// OPENCODE_SERVER_PASSWORD_FILE. +// OPENCODE_SERVER_PASSWORD_FILE, ORCHESTRATION_STATE_PATH. import { readFile, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; -import type { FleetFeed } from "../src/feed.ts"; -import type { QuotaPool, SessionFeedEntry } from "../src/model.ts"; +import { isOrchestrationSummary, type FleetFeed } from "../src/feed.ts"; +import type { JulesSummary, 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)), ".."); @@ -40,6 +41,8 @@ const quotaViewPath = "workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md", ); const julesStatePath = process.env.JULES_STATE_PATH ?? join(HIDDEN, "jules-review-state.json"); +const orchestrationStatePath = + process.env.ORCHESTRATION_STATE_PATH ?? join(HIDDEN, "orchestration-state.json"); const serverUrl = process.env.SANDBOX_OPENCODE_URL ?? "http://127.0.0.1:4096"; const passwordFile = process.env.OPENCODE_SERVER_PASSWORD_FILE ?? join(HOME, "tools/secrets.d/opencode-server-password"); @@ -108,7 +111,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(); @@ -139,16 +144,38 @@ 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 summary (slice 2, #899 -> today view) ----------------- + let orchestration: FleetFeed["orchestration"]; + try { + const parsed: unknown = JSON.parse(await readFile(orchestrationStatePath, "utf8")); + if (isOrchestrationSummary(parsed)) orchestration = parsed; + } catch { + /* the orchestration job has not written one yet — the view derives */ + } + const feed: FleetFeed = { version: 1, generatedAt: now.toISOString(), quota: { pools, burn: [], choices: computeChoices(pools, now.getTime()) }, attention, + julesSummary: jules, + 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 summary embedded" : ""}`, ); } 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/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, From ab05a700c3252f401ac13313e2de6b239f153410 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:13:54 +0000 Subject: [PATCH 4/8] =?UTF-8?q?feat(aggregator):=20slice-2=20sources=20?= =?UTF-8?q?=E2=80=94=20orchestration=20+=20coverage=20on=20the=20Source=20?= =?UTF-8?q?interface?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit liveSource reads the orchestration summary from the fleet feed, stamps laptop sessions opencode-laptop, and reports per-source coverage from what its reads actually saw (feed present, laptop reachable, keeper totals) — Muse honestly not wired. Fixtures gain source stamps, a collapsed sub-session, a Jules entry, a finished probe that expires, and a fixture orchestration summary. --- pm-stack/aggregator/src/source.ts | 6 ++ pm-stack/aggregator/src/sources/fixtures.ts | 112 ++++++++++++++++++++ pm-stack/aggregator/src/sources/live.ts | 89 ++++++++++++++-- 3 files changed, 200 insertions(+), 7 deletions(-) diff --git a/pm-stack/aggregator/src/source.ts b/pm-stack/aggregator/src/source.ts index 6c200dce9c..4965d8402a 100644 --- a/pm-stack/aggregator/src/source.ts +++ b/pm-stack/aggregator/src/source.ts @@ -5,11 +5,13 @@ import type { BoardItem, Comment, GhItem, + OrchestrationSummary, Provenance, QuotaView, RefKey, RoadmapRow, SessionFeedEntry, + SourceCoverage, } from "./model.ts"; export interface Source { @@ -25,5 +27,9 @@ export interface Source { quota(): Promise; /** Raw session feed for the "needs you" view (#852), pre-classification. */ attention(): Promise; + /** The #899 orchestration summary when one exists (slice 2). */ + 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 c2b2a00269..c85c7f47e5 100644 --- a/pm-stack/aggregator/src/sources/fixtures.ts +++ b/pm-stack/aggregator/src/sources/fixtures.ts @@ -11,11 +11,13 @@ import { type Comment, type GhItem, type Link, + type OrchestrationSummary, type Provenance, type QuotaView, type RefKey, type RoadmapRow, type SessionFeedEntry, + type SourceCoverage, refsInText, refUrl, } from "../model.ts"; @@ -440,6 +442,7 @@ export const FIXTURE_QUOTA: QuotaView = { 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", @@ -450,8 +453,25 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ 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: "2026-10-25T02:40:00Z", + 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", @@ -465,6 +485,7 @@ 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", @@ -478,6 +499,7 @@ 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", @@ -491,6 +513,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ }, { 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", @@ -503,8 +526,69 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ 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: "2026-10-25T12:44:14Z", + lastActivityAt: "2026-10-25T02:50:00Z", + 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: "2026-10-24T20:00:00Z", + messageCount: 2, + messageDelta: 0, + activeToolCalls: 0, + }, ]; +// The orchestration summary (#899) as the collector would embed it. +export const FIXTURE_ORCHESTRATION: OrchestrationSummary = { + generatedAt: "2026-10-25T02:55:00Z", + objectives: [ + { + title: "Ship aggregator slice 2 (mobile, tiers, today view)", + horizon: "today", + status: "in progress", + ref: `${CODE}#898`, + }, + { title: "Decide the dezren39/nix GitHub App route", horizon: "today", status: "awaiting Drew" }, + { title: "Rotate the laptop Meta secret at the source", horizon: "3d", ref: `${CODE}#861` }, + ], + momentum: [ + { + project: CODE, + state: "moving", + accomplished: ["PR #892 — aggregator slice 1 merged"], + }, + { + project: NIX, + state: "blocked", + blockedBy: "GitHub App cannot reach a personal repo until Drew picks a route", + }, + ], + escalations: [ + { + sessionId: "ses_h_connect", + reason: "Only Drew can pick which repo installs the developing.today app first.", + at: "2026-10-25T02:55:00Z", + }, + ], +}; + export function fixtureSource(): Source { const items = new Map(FIXTURE_ITEMS.map((i) => [i.ref, i])); const provenance: Provenance = { @@ -526,6 +610,34 @@ export function fixtureSource(): Source { }, quota: async () => FIXTURE_QUOTA, attention: async () => FIXTURE_ATTENTION, + orchestration: async () => FIXTURE_ORCHESTRATION, + 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/live.ts b/pm-stack/aggregator/src/sources/live.ts index 2f6a6d977f..1e83f8674c 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, loadFeed } from "../feed.ts"; +import { feedAgeText, 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 OrchestrationSummary, type Provenance, type QuotaView, type RefKey, type RoadmapRow, type SessionFeedEntry, + type SourceCoverage, refsInText, refUrl, } from "../model.ts"; @@ -362,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). @@ -373,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; @@ -443,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; @@ -458,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)})`); @@ -467,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 */ } @@ -481,6 +501,61 @@ export function liveSource(cfg: Config): Source { provenance.attention = "fixtures (no live attention source reachable)"; return fix.attention(); }, + async orchestration(): Promise { + const feed = await getFeed(); + if (feed?.orchestration) { + provenance.orchestration = `live (orchestration summary · ${feedAgeText(feed.orchestration.generatedAt)} · written ${feed.orchestration.generatedAt})`; + return feed.orchestration; + } + provenance.orchestration = feed + ? "none yet — the orchestration job (#899) has not written a summary; 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, }; } From 55937e65abed961a6334c503ce294a50a8c3a2d9 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:17:04 +0000 Subject: [PATCH 5/8] =?UTF-8?q?feat(aggregator):=20slice-2=20views=20?= =?UTF-8?q?=E2=80=94=20mobile=20pass,=20tiered=20needs-you,=20roadmap=20ho?= =?UTF-8?q?rizons,=20today=20view?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mobile-first CSS (single-column stacking, scrollable tables/nav, touch chips). Needs-you is now card-based and tiered: NEEDS DREW first with a per-item 'Why you' reason, NEEDS ORCHESTRATOR with the fleet's next step, then all sessions with source labels, plain- language states, sub-sessions collapsed under parents, and the session-coverage note (Muse honestly not wired). Roadmap gains a horizon switcher (quarter/month/week/next-3-days/today) over the same rows. New /today view: top objectives + per-project momentum from the #899 orchestration summary when present, derived and labelled until then. /api/attention.json keeps its array shape, tier-annotated; new /api/today.json and /api/coverage.json. Footer carries the canonical amd-6.raptor-pumpkinseed.ts.net URL — never the raw tailnet IP. --- pm-stack/aggregator/src/render.ts | 282 ++++++++++++++++---- pm-stack/aggregator/src/server.ts | 59 +++- pm-stack/aggregator/src/sources/fixtures.ts | 30 ++- pm-stack/aggregator/test/boot.test.ts | 26 ++ pm-stack/aggregator/test/opencode.test.ts | 24 ++ pm-stack/aggregator/test/render.test.ts | 19 +- pm-stack/aggregator/test/slice2.test.ts | 246 +++++++++++++++++ 7 files changed, 612 insertions(+), 74 deletions(-) create mode 100644 pm-stack/aggregator/test/slice2.test.ts diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 61c3480287..e3a5c0ed7d 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -2,23 +2,33 @@ // 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, + SESSION_SOURCE_LABELS, + refUrl, } from "./model.ts"; export function esc(s: unknown): string { @@ -44,13 +54,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 +71,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 +134,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 +209,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 +312,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 +353,120 @@ 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}
    `; +} + +export function renderAttention(view: AttentionView, coverage: SourceCoverage[], provenance: Provenance): string { + const children = sessionChildren(view.all); + const roots = sessionRoots(view.all); + const chips = ``; + const drewCards = view.drew.length + ? view.drew.map((e) => sessionCard(e, children)).join("") + : `

    Nothing needs you right now.

    `; + const orchCards = view.orchestrator.length + ? view.orchestrator.map((e) => sessionCard(e, children)).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 (${view.drew.length})

    ${drewCards} +

    Needs orchestrator (${view.orchestrator.length})

    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[] = []; + if (attention.drew.length) { + alerts.push( + ``, + ); + } + if (walled.length) { + alerts.push( + ``, + ); + } + const provenanceLine = today.fromOrchestrator + ? `

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

    ` + : ``; + 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} +${coverageHtml(coverage)}`, + provenance, + "/today", + ); +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index fd3e3cd362..ce08980d3d 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -1,8 +1,15 @@ // 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 +47,28 @@ 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 +79,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 +96,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 +112,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/health") { return json({ status: "ok", source: prov() }); diff --git a/pm-stack/aggregator/src/sources/fixtures.ts b/pm-stack/aggregator/src/sources/fixtures.ts index c85c7f47e5..6890bdd03f 100644 --- a/pm-stack/aggregator/src/sources/fixtures.ts +++ b/pm-stack/aggregator/src/sources/fixtures.ts @@ -438,7 +438,11 @@ 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", @@ -448,7 +452,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ 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, @@ -464,7 +468,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ directory: "/home/user/work/id-train/pm-aggregator-ui", model: "deepseek-v4-flash", provider: "opencode-go", - lastActivityAt: "2026-10-25T02:40:00Z", + lastActivityAt: ago(0.5), messageCount: 6, messageDelta: 0, activeToolCalls: 0, @@ -477,7 +481,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ 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, @@ -491,7 +495,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ 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, @@ -505,11 +509,11 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ 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", @@ -519,7 +523,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ 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, @@ -532,8 +536,8 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ source: "jules", title: "Fix #811: id phase-9: a joiner's resize (up to 500x200) can permanently…", directory: "developing-today/code", - createdAt: "2026-10-25T12:44:14Z", - lastActivityAt: "2026-10-25T02:50:00Z", + createdAt: ago(5), + lastActivityAt: ago(0.2), messageCount: 0, activeToolCalls: 0, awaitingQuestion: "Does this look good, and should I proceed?", @@ -548,7 +552,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ directory: "/home/hatch/tmp/gemini-probe", model: "gemini-3.8-flash", provider: "google", - lastActivityAt: "2026-10-24T20:00:00Z", + lastActivityAt: ago(30), messageCount: 2, messageDelta: 0, activeToolCalls: 0, @@ -557,7 +561,7 @@ export const FIXTURE_ATTENTION: SessionFeedEntry[] = [ // The orchestration summary (#899) as the collector would embed it. export const FIXTURE_ORCHESTRATION: OrchestrationSummary = { - generatedAt: "2026-10-25T02:55:00Z", + generatedAt: ago(0.1), objectives: [ { title: "Ship aggregator slice 2 (mobile, tiers, today view)", @@ -584,7 +588,7 @@ export const FIXTURE_ORCHESTRATION: OrchestrationSummary = { { sessionId: "ses_h_connect", reason: "Only Drew can pick which repo installs the developing.today app first.", - at: "2026-10-25T02:55:00Z", + at: ago(0.1), }, ], }; diff --git a/pm-stack/aggregator/test/boot.test.ts b/pm-stack/aggregator/test/boot.test.ts index 29f2309e54..d2727594f7 100644 --- a/pm-stack/aggregator/test/boot.test.ts +++ b/pm-stack/aggregator/test/boot.test.ts @@ -63,6 +63,32 @@ 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); + expect(todayJson.fromOrchestrator).toBe(true); // fixture summary exists + 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..2ffb0fe514 --- /dev/null +++ b/pm-stack/aggregator/test/slice2.test.ts @@ -0,0 +1,246 @@ +import { describe, expect, test } from "bun:test"; +import { + buildAttention, + chicagoYmd, + deriveToday, + monthTimeline, + partitionFresh, + roadmapDayGrain, + sessionChildren, + sessionRoots, +} from "../src/derive.ts"; +import { + type OrchestrationSummary, + type RoadmapRow, + type SessionFeedEntry, +} from "../src/model.ts"; +import { renderAttention, renderRoadmap, renderToday } from "../src/render.ts"; +import { + FIXTURE_ATTENTION, + FIXTURE_BOARD, + FIXTURE_ITEMS, + FIXTURE_ORCHESTRATION, + 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(); + +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("an orchestration escalation overrides the local rules, reason verbatim", () => { + const summary: OrchestrationSummary = { + generatedAt: iso(NOW), + objectives: [], + momentum: [], + escalations: [{ sessionId: "s", reason: "Only Drew can do this thing.", at: iso(NOW) }], + }; + const view = buildAttention([entry({ lastTurnError: "plain error" })], summary, NOW); + expect(view.drew).toHaveLength(1); + expect(view.drew[0].drewReason).toBe("Only Drew can do this thing."); + }); + + 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, FIXTURE_ORCHESTRATION); + 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 fixture escalation 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 summary when present", () => { + const today = deriveToday(FIXTURE_BOARD, FIXTURE_ROADMAP, items, FIXTURE_ORCHESTRATION); + expect(today.fromOrchestrator).toBe(true); + expect(today.objectives[0].chip).toContain("orchestrator"); + expect(today.momentum.some((m) => m.state === "blocked")).toBe(true); + }); + + 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 written its goal-measurement summary 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(), await src.orchestration()); + 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 + }); +}); From d30f7078d9a59dc2105cf952a6cebc10cbc645da Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:18:45 +0000 Subject: [PATCH 6/8] docs(aggregator): slice-2 README + stack hostname; Jules questions are the keeper's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pm-stack README tailnet references now use amd-6.raptor-pumpkinseed.ts.net. Aggregator README documents the views, tiers, expiry, sources and the #899 feed contract. One behavior refinement from the live collector run: a Jules AWAITING_USER_FEEDBACK question matches the decision heuristic, but the keeper already answers those — Jules questions tier to the orchestrator unless #899 escalates them. --- pm-stack/README.md | 6 +-- pm-stack/aggregator/README.md | 52 ++++++++++++++++++++++--- pm-stack/aggregator/src/derive.ts | 5 ++- pm-stack/aggregator/test/slice2.test.ts | 16 ++++++++ 4 files changed, 70 insertions(+), 9 deletions(-) diff --git a/pm-stack/README.md b/pm-stack/README.md index 6a6824388b..4df5ff5220 100644 --- a/pm-stack/README.md +++ b/pm-stack/README.md @@ -20,9 +20,9 @@ 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/` | +| 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..9135a0029a 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -9,16 +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 +## 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 summary (#899) when it 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 (theme × quarter lane); each row drills down to its linked issues/PRs with live state. | `/api/roadmap.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` | -| `/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. | — | +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: an orchestration escalation (#899, 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 +148,18 @@ 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 summary** (slice 2, contract on #899) — when the + orchestration job writes + `~/workspace/goals/keep-the-four-repos-healthy/hidden_files/orchestration-state.json` + on the sandbox, the collector embeds it as `feed.orchestration` + (override the path with `ORCHESTRATION_STATE_PATH`); the today view + renders it and its escalations override the tier rules. `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 +237,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 +249,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/src/derive.ts b/pm-stack/aggregator/src/derive.ts index dd4c7e478e..676871058f 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -311,7 +311,10 @@ export function tierEntry(e: AttentionEntry, summary?: OrchestrationSummary | nu }; } // Routine tool permissions are the fleet's to review, not Drew's. - } else if (DECISION_Q.test(q)) { + } 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}` }; } } diff --git a/pm-stack/aggregator/test/slice2.test.ts b/pm-stack/aggregator/test/slice2.test.ts index 2ffb0fe514..49cecf8c56 100644 --- a/pm-stack/aggregator/test/slice2.test.ts +++ b/pm-stack/aggregator/test/slice2.test.ts @@ -100,6 +100,22 @@ describe("tiering (#898 §2)", () => { expect(view.drew[0].drewReason).toBe("Only Drew can do this thing."); }); + 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); From b88e22ecbdd81fc1daa6cb8e531793cf1ca8bda4 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:29:42 +0000 Subject: [PATCH 7/8] chore: retrigger CI (nix-ci did not fire on PR open) From 626a597c2e89ba0381133c9ea53fbe6b7b9de6b5 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sun, 25 Oct 2026 17:36:30 +0000 Subject: [PATCH 8/8] style(aggregator): treefmt formatting (biome + prettier) for slice-2 files --- pm-stack/README.md | 6 +-- pm-stack/aggregator/README.md | 16 +++---- .../aggregator/scripts/collect-fleet-feed.ts | 3 +- pm-stack/aggregator/src/derive.ts | 45 ++++++++++++------- pm-stack/aggregator/src/server.ts | 15 +------ pm-stack/aggregator/test/slice2.test.ts | 21 ++++++--- 6 files changed, 56 insertions(+), 50 deletions(-) diff --git a/pm-stack/README.md b/pm-stack/README.md index 4df5ff5220..209492ec79 100644 --- a/pm-stack/README.md +++ b/pm-stack/README.md @@ -17,9 +17,9 @@ 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/` | +| 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/` | diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index 9135a0029a..3cc2d5ce02 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -11,14 +11,14 @@ Design record (source of truth): ## 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 summary (#899) when it 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. | — | +| 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 summary (#899) when it 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 diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index ff436da51c..f2b7a45405 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -41,8 +41,7 @@ const quotaViewPath = "workspace/goals/stewardship-commission-recurring-review-and-dispatch/hidden_files/visibility/quota-view.md", ); const julesStatePath = process.env.JULES_STATE_PATH ?? join(HIDDEN, "jules-review-state.json"); -const orchestrationStatePath = - process.env.ORCHESTRATION_STATE_PATH ?? join(HIDDEN, "orchestration-state.json"); +const orchestrationStatePath = process.env.ORCHESTRATION_STATE_PATH ?? join(HIDDEN, "orchestration-state.json"); const serverUrl = process.env.SANDBOX_OPENCODE_URL ?? "http://127.0.0.1:4096"; const passwordFile = process.env.OPENCODE_SERVER_PASSWORD_FILE ?? join(HOME, "tools/secrets.d/opencode-server-password"); diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index 676871058f..8270bc5cdd 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -211,13 +211,7 @@ export function attentionSorted(feed: SessionFeedEntry[], now = Date.now()): Att // ORCHESTRATOR tiering, session hierarchy, roadmap grains, today view. // --------------------------------------------------------------------------- -import type { - AttentionTier, - BoardItem, - OrchestrationSummary, - SessionSource, - TieredEntry, -} from "./model.ts"; +import type { AttentionTier, BoardItem, OrchestrationSummary, SessionSource, TieredEntry } from "./model.ts"; export function sourceOf(e: SessionFeedEntry): SessionSource { if (e.source) return e.source; @@ -270,8 +264,7 @@ export function partitionFresh( 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 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; @@ -404,8 +397,18 @@ export function weekStartYmd(ymd: string): string { } const MONTH_NAMES = [ - "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December", + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", ]; const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; @@ -467,7 +470,11 @@ export function roadmapDayGrain(rows: RoadmapRow[], grain: "week" | "3d" | "toda } } return { - lanes: days.map((d) => ({ key: d, label: d === today ? `${ymdLabel(d)} · today` : ymdLabel(d), rows: lanes.get(d) ?? [] })), + lanes: days.map((d) => ({ + key: d, + label: d === today ? `${ymdLabel(d)} · today` : ymdLabel(d), + rows: lanes.get(d) ?? [], + })), outside, coarse, }; @@ -572,10 +579,16 @@ export function deriveToday( (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)) { + 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)) { + 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}` }); } @@ -598,9 +611,7 @@ export function deriveToday( .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 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({ diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index ce08980d3d..f80b4f8608 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -2,14 +2,7 @@ // server-rendered HTML; /api/*.json serve the same data machine-first. import { loadConfig } from "./config.ts"; import { allRefs, buildAttention, deriveToday, type RoadmapGrain } from "./derive.ts"; -import { - renderAttention, - renderBoard, - renderItem, - renderQuota, - renderRoadmap, - renderToday, -} from "./render.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"; @@ -48,11 +41,7 @@ async function roadmapContext() { } async function attentionContext() { - const [feed, summary, coverage] = await Promise.all([ - source.attention(), - source.orchestration(), - source.coverage(), - ]); + const [feed, summary, coverage] = await Promise.all([source.attention(), source.orchestration(), source.coverage()]); return { view: buildAttention(feed, summary), coverage }; } diff --git a/pm-stack/aggregator/test/slice2.test.ts b/pm-stack/aggregator/test/slice2.test.ts index 49cecf8c56..7ff1895485 100644 --- a/pm-stack/aggregator/test/slice2.test.ts +++ b/pm-stack/aggregator/test/slice2.test.ts @@ -9,11 +9,7 @@ import { sessionChildren, sessionRoots, } from "../src/derive.ts"; -import { - type OrchestrationSummary, - type RoadmapRow, - type SessionFeedEntry, -} from "../src/model.ts"; +import { type OrchestrationSummary, type RoadmapRow, type SessionFeedEntry } from "../src/model.ts"; import { renderAttention, renderRoadmap, renderToday } from "../src/render.ts"; import { FIXTURE_ATTENTION, @@ -33,7 +29,13 @@ describe("freshness expiry (#898 §2/§5)", () => { 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: "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 }, ]; @@ -153,7 +155,12 @@ describe("jules mapping (#898 §5)", () => { 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" }, + "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.",