diff --git a/docs/architecture/flows.md b/docs/architecture/flows.md index cc23302e27..9ee70b8176 100644 --- a/docs/architecture/flows.md +++ b/docs/architecture/flows.md @@ -749,16 +749,31 @@ the route it took, red only where it stopped. from the graph ("Asks you every time"; "Asks you if it edits CI" when a person is asked only on a side route and that person's step says what makes a run ask with `asks_if="it edits CI"`, words that finish "Asks you if …", set on the gate - or on the segment node that holds it, as change's `decide` does; "Sometimes asks + or on a segment node that holds it, the nearest one first, as change's `decide` + and Union's Land `card` do; "Sometimes asks you" when it says nothing, never the route's label, which names the route; "No - approval"), and its stages. The confirm after it says the same: a question every + approval"), and its stages; a lone flow has no row, and its label and approval + sit beside Ship. The confirm after it says the same: a question every run, "Only if it edits CI" (else "On some runs"), or none. The stages are the journey's: the stations a passing run takes, never one only a failure reaches (a later deploy after a failed one), and a station marked `fold=true` is bookkeeping, drawn as part of the stage before it (change's Verdicts reads in CI + Review, its Merged in Merge); it runs like any other station. A stage reads Person only when a person is asked on its passing - route, never for a card a segment reaches on a side route. It draws the picked one and + route, never for a card a segment reaches on a side route. A segment stage + with more than one step, or a route off them, shows its inside, read from the + graph (`insideOf` in `lib/ship/segmentInside.ts`): under its name a quiet line of + its passing steps ("PR · CI + Review · Merge"), and a press on it opens them + in place down a spine that ends at the segment's end ("Merged"). Each route + off a step hangs under that step, labelled by its edge's label, through the + steps it runs to where it goes: back to a step ("↩ Merge"), back to the + session (an end the composing flow sends to a `backend=subject` station), or + a stop. A route walks on by its edges' conditions alone, the passing one + first, then a step's default; an edge whose condition compares two words the + parser wrote in (a segment param) is never taken. A route through a person's + step is dashed and carries its "Asks you if …" words. On a run each step and + route takes its state (the route that sent the work back, the card that + waits). A single stage that sends work back draws a hook under itself. It draws the picked one and opens the shared confirm review: steps, agent sessions that start, questions for you, who does each step, the ways it can end, how to stop. Confirming asks the session to run its own change through it. On a phone it opens as a diff --git a/packages/mobile/components/session/FlowCard.tsx b/packages/mobile/components/session/FlowCard.tsx index 26472a81e4..fba23e33f0 100644 --- a/packages/mobile/components/session/FlowCard.tsx +++ b/packages/mobile/components/session/FlowCard.tsx @@ -19,7 +19,7 @@ import { type AppFlow } from '@codecast/web/lib/line/flowPool'; import { flowDiagram, routeTail, runReached, stepStates, type DiagramStep, type SideRoute, type StepState } from '@codecast/web/lib/line/flowDiagram'; import { flowRunState, type FlowRunTone } from '@codecast/web/lib/line/flowFence'; import { takesSessionChange } from '@codecast/shared/contracts/flowPool'; -import { gateWaitWords, holdWords, journeyOf, sentBackWords, stopWords, waitWords, WHO_WORDS, type JourneyNow, type JourneyStage, type JourneyWait, type StageState } from '@codecast/web/lib/ship/journey'; +import { gateWaitWords, holdWords, insideWords, journeyOf, sentBackWords, stopWords, waitWords, WHO_WORDS, type JourneyNow, type JourneyStage, type JourneyWait, type StageState } from '@codecast/web/lib/ship/journey'; import type { FlowEdit } from '@codecast/shared/contracts/flowEdit'; import { asGitDiff, editDrawing, editLines, editRun, liveDeploy, type EditMark } from '@codecast/web/lib/line/flowEditCard'; import { CastDiff } from '@/components/CastDiff'; @@ -83,6 +83,8 @@ function ShipBody({ flow, run }: { flow: AppFlow; run: RunRow }) { {s.label} {whoWords(s)} + {/* A segment's inside, in a few words: the steps a passing run takes through it. */} + {s.inside ? {insideWords(s.inside)} : null} {/* A fan-out's branches run side by side: each with its own state. */} {s.branches?.map((b) => ( diff --git a/packages/shared/contracts/flowPool.test.ts b/packages/shared/contracts/flowPool.test.ts index 17eef01d72..be5714f057 100644 --- a/packages/shared/contracts/flowPool.test.ts +++ b/packages/shared/contracts/flowPool.test.ts @@ -72,6 +72,21 @@ test("the main path runs through a station inserted after a segment, not its way ]); }); +test("a station only a failure reaches is off the main path, though its way on is an end", () => { + const n = (id: string, type: string) => ({ id, label: id, shape: "box", type }); + const nodes = [n("start", "start"), n("deploy", "command"), n("redeploy", "command"), n("exit", "exit"), n("never", "exit")] as unknown as Parameters[0]; + const edges = [ + { from: "start", to: "deploy" }, + { from: "deploy", to: "exit", condition: "outcome = success" }, + { from: "deploy", to: "redeploy", condition: "outcome = failure" }, + { from: "redeploy", to: "exit", condition: "outcome = success" }, + { from: "redeploy", to: "never", condition: "outcome = failure" }, + ]; + const folded = foldFlow(nodes, edges); + expect(folded.path).toEqual(["deploy"]); + expect(folded.stations.find((s) => s.id === "redeploy")!.main).toBe(false); +}); + test("a variant's edits read as one line each", () => { const label = (id: string) => ({ check: "Check", review: "Review", decide: "Decide", lint: "Lint", e2e: "E2E" })[id] ?? id; expect([ diff --git a/packages/shared/contracts/flowPool.ts b/packages/shared/contracts/flowPool.ts index a2f72c19f2..88d2bd2903 100644 --- a/packages/shared/contracts/flowPool.ts +++ b/packages/shared/contracts/flowPool.ts @@ -160,14 +160,14 @@ export function foldFlow(nodes: ReadonlyArray, edges: ReadonlyArray< if (t === n.id) top.set(t, n); else if (!n.segment_exit && n.type !== "exit") steps.set(t, (steps.get(t) ?? 0) + 1); } - const outOf = new Map>(); + const outOf = new Map>(); for (const e of edges) { const from = segmentTopOf(e.from); const to = segmentTopOf(e.to); if (from === to) continue; const list = outOf.get(from) ?? []; const when = edgeWhen(e); - if (!list.some((x) => x.to === to && x.when === when)) list.push({ to, when, score: passScore(e) }); + if (!list.some((x) => x.to === to && x.when === when)) list.push({ to, when, score: passScore(e), success: /\boutcome\s*=\s*success\b/.test(e.condition ?? "") }); outOf.set(from, list); } const start = [...top.values()].find((n) => n.type === "start"); @@ -186,7 +186,14 @@ export function foldFlow(nodes: ReadonlyArray, edges: ReadonlyArray< const main = new Set(); const path: string[] = []; // The subject's own stations (backend=subject: the session the change came from fixes what a stage found) are a way back, never the way on. - const rank = (x: { to: string; score: number }) => x.score - (top.get(x.to)?.type === "exit" ? 10 : 0) - (top.get(x.to)?.backend === "subject" ? 20 : 0); + // An end comes after any station, unless its edge is the station's only `outcome = success`: a station only another + // outcome reaches never outranks where a success goes. + const exit = (id: string) => top.get(id)?.type === "exit"; + const best = (list: ReadonlyArray<{ to: string; score: number; success: boolean }>) => { + const ends = !list.some((x) => x.success && !exit(x.to)); + const rank = (x: (typeof list)[number]) => x.score - (exit(x.to) && !(ends && x.success) ? 10 : 0) - (top.get(x.to)?.backend === "subject" ? 20 : 0); + return [...list].sort((a, b) => rank(b) - rank(a))[0]?.to; + }; for (let at = start?.id; at && !main.has(at); ) { main.add(at); path.push(at); @@ -198,13 +205,13 @@ export function foldFlow(nodes: ReadonlyArray, edges: ReadonlyArray< if (top.get(b)?.type === "parallel_fanin") { join ??= b; break; } main.add(b); path.push(b); - b = [...(outOf.get(b) ?? [])].filter((x) => !main.has(x.to)).sort((x, y) => rank(y) - rank(x))[0]?.to; + b = best((outOf.get(b) ?? []).filter((x) => !main.has(x.to))); } } at = join; continue; } - at = [...(outOf.get(at) ?? [])].filter((x) => !main.has(x.to)).sort((a, b) => rank(b) - rank(a))[0]?.to; + at = best((outOf.get(at) ?? []).filter((x) => !main.has(x.to))); } const label = (id: string) => top.get(id)?.label ?? id; const stations: FlowStation[] = []; diff --git a/packages/web/components/line/widgets/RunThroughFlow.tsx b/packages/web/components/line/widgets/RunThroughFlow.tsx index 0d7a04ef7f..06577f384f 100644 --- a/packages/web/components/line/widgets/RunThroughFlow.tsx +++ b/packages/web/components/line/widgets/RunThroughFlow.tsx @@ -203,6 +203,12 @@ export function ShipAgainButton({ flow, conversationId, sessionTitle, primary }: ); } +/** Whether a flow asks the person before the change lands, as a chip. */ +function Asks({ flow }: { flow: AppFlow }) { + const approval = approvalOf(flow); + return {approvalWords(approval)}; +} + function PoolPicker({ conversationId, session, onRun }: { conversationId: string; session: string; onRun: (flow: AppFlow) => void }) { // The session's workspace, not the active one: the pool `cast flow run` reads where the session runs. const workspace = useInboxStore((s) => sessionWorkspaceOf(s as any, conversationId)); @@ -229,24 +235,23 @@ function PoolPicker({ conversationId, session, onRun }: { conversationId: string {pool.length > 1 ? ( // A native radio group: one tab stop, arrow keys move the pick, Enter ships the picked flow.
- {pool.map((f) => { const approval = approvalOf(f); return ( + {pool.map((f) => ( - ); })} + ))}
) : null}
- {pool.length > 1 ? null : <>{flow.label}{flow === fallback ? Default : null}} + {/* A lone flow has no list row, so its name and whether it asks the person sit here. */} + {pool.length > 1 ? null : <>{flow.label}{flow === fallback ? Default : null}}
diff --git a/packages/web/components/ship/Journey.stateWords.test.tsx b/packages/web/components/ship/Journey.stateWords.test.tsx index abaca41d61..e42d1d595e 100644 --- a/packages/web/components/ship/Journey.stateWords.test.tsx +++ b/packages/web/components/ship/Journey.stateWords.test.tsx @@ -30,3 +30,21 @@ describe("states that read without color", () => { expect(text(stopped)).toContain("CI + Review✕ (stopped), stopped"); }); }); + +const { journeyStages } = await import("../../lib/ship/journey"); +const { appPool, flowBySlug } = await import("../../lib/line/flowPool"); +const { LAND_REPO_FLOW } = await import("../../lib/ship/journeyFixtures"); + +describe("a segment stage", () => { + const stages = journeyStages(flowBySlug(appPool([], [LAND_REPO_FLOW]), "change")!).map((s) => ({ ...s, state: "idle", round: null })) as any; + test("hints at its inside under its name, a press away from opening it", () => { + const html = renderToStaticMarkup( {}} insideId="in1" />); + expect(html).toContain('aria-expanded="false" aria-controls="in1"'); + expect(text(html)).toContain("PR · CI + Review · Merge"); + }); + test("alone and sending work back, it draws a hook under itself, not a bracket of no width", () => { + expect(renderToStaticMarkup()).toContain("data-single"); + const two = [stage("pr", "PR", "idle", { loops: [{ id: "fix", label: "Fix", max: 3 }] }), stage("merge", "Merge", "idle", { loops: [{ id: "fix", label: "Fix", max: 3 }] })]; + expect(renderToStaticMarkup()).not.toContain("data-single"); + }); +}); diff --git a/packages/web/components/ship/Journey.tsx b/packages/web/components/ship/Journey.tsx index 61dec7e427..2e408e9e14 100644 --- a/packages/web/components/ship/Journey.tsx +++ b/packages/web/components/ship/Journey.tsx @@ -5,11 +5,11 @@ // right there: an answer at Decide, the session's fix when a stage sent work // back, the deploy when it has landed. The Ship panel previews a flow with it // and the run's card in the thread draws the run with it. -import { memo, useMemo, useState } from "react"; +import { memo, useId, useMemo, useState } from "react"; import Link from "next/link"; import { useInboxStore } from "../../store/inboxStore"; -import { ArrowRight, Check, CornerDownLeft, Loader2, X } from "lucide-react"; -import { WHO_WORDS, gateWaitWords, holdWords, sentBackWords, stopWords, targetsFromLine, waitWords, type Journey as JourneyModel, type JourneyStage, type JourneyNow, type JourneyWait, type TargetState } from "../../lib/ship/journey"; +import { ArrowRight, Check, ChevronDown, CornerDownLeft, Loader2, X } from "lucide-react"; +import { WHO_WORDS, approvalWords, gateWaitWords, holdWords, insideWords, sentBackWords, stopWords, targetsFromLine, waitWords, type InsideRoute, type Journey as JourneyModel, type JourneyStage, type JourneyNow, type JourneyWait, type TargetState } from "../../lib/ship/journey"; import { ageShort } from "../../lib/lineFlow"; import { RunGate } from "../WorkflowContextPanel"; import { useDeployTargets } from "../../hooks/useSyncDeployTargets"; @@ -18,7 +18,8 @@ import { deploysFocusHref, deploysHref, runFocus, type DeployFocus } from "../.. import { useDeployPress } from "../../hooks/useDeployPress"; import "./ship.css"; -export const JourneyTrack = memo(function JourneyTrack({ stages, compact = false, open, onOpen }: { stages: JourneyStage[]; compact?: boolean; open?: string | null; onOpen?: (id: string | null) => void }) { +/** `insideId`: the element an open segment's inside is drawn in, which its stage's toggle controls. */ +export const JourneyTrack = memo(function JourneyTrack({ stages, compact = false, open, onOpen, insideId }: { stages: JourneyStage[]; compact?: boolean; open?: string | null; onOpen?: (id: string | null) => void; insideId?: string }) { // A finished journey says only what happened: no one acts any more, and nothing goes back. const finished = stages.length > 0 && stages.every((s) => s.state === "done" || s.state === "skipped") && stages.some((s) => s.state === "done"); // The stages whose findings come back to the session, as one return line under them. @@ -31,8 +32,8 @@ export const JourneyTrack = memo(function JourneyTrack({ stages, compact = false const next = stages[i + 1]; return (
  • - {onOpen && s.steps?.length ? ( - ) : } @@ -41,7 +42,7 @@ export const JourneyTrack = memo(function JourneyTrack({ stages, compact = false })} {looping.length && !compact ? ( -
    stages[i].label).join(", ")}`} data-journey-return> findings come back to this session @@ -63,6 +64,8 @@ function StageFace({ s, finished = false }: { s: JourneyStage; finished?: boolea ) : {s.label}} + {/* A segment hints at its inside, which a press on it opens in place. */} + {s.inside ? {insideWords(s.inside)} : null} {finished ? (s.round ? `round ${s.round}` : "") : s.state === "back" ? "This session" : s.role === "live" || s.state === "skipped" ? "" : WHO_WORDS[s.who]} {!finished && s.round ? · round {s.round} : null} @@ -84,6 +87,51 @@ function StateWords({ state }: { state: JourneyStage["state"] }) { return STATE_WORDS[state] ? , {STATE_WORDS[state]} : null; } +/** + * A segment opened in place: its passing steps down a spine, each route off a step a branch under it that says where it + * goes back to, and the segment's end last, so nothing reads as after it. A route a person answers on is dashed and says + * what makes a run ask: it asks only when a run turns there. + */ +function SegmentInside({ stage, id }: { stage: JourneyStage; id?: string }) { + const { path, routes, end } = stage.inside!; + return ( +
      + {path.map((p) => { + const off = routes.filter((r) => r.from === p.id); + return ( +
    1. + + + {p.branches ? p.branches.map((b, i) => {i ? beside : null}{b.label}) : p.label} + {WHO_WORDS[p.who]} + + {off.length ?
        {off.map((r, i) => )}
      : null} +
    2. + ); + })} + {end ?
    3. {end}
    4. : null} +
    + ); +} + +function Route({ r }: { r: InsideRoute }) { + return ( +
  • + {r.label ? {r.label} : null} + {r.steps.map((s, i) => ( + + {i || r.label ? → : null} + {s.label} + + ))} + + {r.to.kind === "stop" ? <>stops : <>back to {r.to.kind === "session" ? "this session" : r.to.label}} + + {r.asks ? {approvalWords({ kind: "if", when: r.asks.when })} : null} +
  • + ); +} + /** What one stage did on the run: each of its steps with its words, rounds and the session that did it. */ function StageDetail({ stage, now_ms }: { stage: JourneyStage; now_ms: number }) { return ( @@ -251,13 +299,15 @@ export function JourneyNowBar({ now, run, now_ms, children, again }: { now: Jour /** `targets`, when the caller knows them from the landed commit's deploy reach, are where the change is: never guessed from the session's commits. */ export function JourneyView({ journey, run, now_ms, compact, actions, again, targets }: { journey: JourneyModel; run?: any; now_ms: number; compact?: boolean; actions?: React.ReactNode; again?: (primary: boolean) => React.ReactNode; targets?: ReadonlyArray }) { const [open, setOpen] = useState(null); + const insideId = useId(); const opened = open ? journey.stages.find((s) => s.id === open) ?? null : null; const landed = journey.now.kind === "landed" || journey.now.kind === "deploying" || journey.now.kind === "live"; const team = typeof run?.workspace === "string" && run.workspace.startsWith("team:") ? run.workspace.slice(5) : null; return (
    - - {opened ? : null} + + {opened?.inside ? : null} + {opened?.steps?.length ? : null} {run ? {actions} : null} {run && landed && team && run.spawner_conversation_id ? : null}
    diff --git a/packages/web/components/ship/ship.css b/packages/web/components/ship/ship.css index 1b7a2b0aab..005eb2098b 100644 --- a/packages/web/components/ship/ship.css +++ b/packages/web/components/ship/ship.css @@ -22,6 +22,8 @@ .sj-return { grid-row: 2; display: flex; flex-direction: column; align-items: center; gap: 3px; } .sj-return-line { position: relative; align-self: stretch; height: 8px; border: 1.5px solid color-mix(in srgb, var(--sj-session) 45%, transparent); border-top: 0; border-radius: 0 0 8px 8px; margin: -4px calc(50% / var(--n, 1)) 0; } .sj-return-words { display: inline-flex; align-items: center; gap: 4px; font-size: var(--fs-meta); color: color-mix(in srgb, var(--sj-session) 85%, var(--sol-text-dim)); } +/* One stage that sends work back: a hook under it, out and back into the same stage. */ +.sj-return[data-single] .sj-return-line { align-self: center; width: 64px; height: 12px; margin: -2px 0 0; border-radius: 0 0 12px 12px; } .sj-return[data-active] .sj-return-line { border-color: var(--sj-session); } .sj-return[data-active] .sj-return-words { color: var(--sj-session); font-weight: 600; } .sj-stage { position: relative; display: flex; flex-direction: column; align-items: center; gap: 3px; min-width: 0; text-align: center; } @@ -156,6 +158,53 @@ .sj-detail-mark[data-status="running"] { background: var(--sol-blue); animation: sj-pulse 1.6s ease-in-out infinite; } .sj-detail-session { color: var(--sol-blue); text-decoration: none; } .sj-detail-session:hover { text-decoration: underline; } + +/* A segment's inside, hinted under its stage and opened in place: its passing steps down a spine, each route off a step a + branch under it, the segment's end last. A route a person answers on is dashed in the asker's blue. */ +.sj-hint { display: inline-flex; align-items: center; gap: 2px; max-width: 100%; font-size: var(--fs-meta); line-height: 1.2; color: var(--sol-text-dim); } +.sj-hint > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.sj-hint-caret { width: 11px; height: 11px; flex: none; transition: transform .2s; } +.sj-stage-btn[aria-expanded="true"] .sj-hint-caret { transform: rotate(180deg); } +.sj-in { list-style: none; margin: 0; padding: 12px 14px 12px 16px; border-top: 1px solid var(--sj-rule-2); background: var(--sj-card); font-size: 12px; } +.sj-in-step { position: relative; padding: 0 0 12px 26px; --sj-who-c: var(--sj-auto); } +.sj-in-step[data-who="agent"] { --sj-who-c: var(--sj-agent); } +.sj-in-step::before { content: ""; position: absolute; left: 7px; top: 18px; bottom: 0; width: 2px; border-radius: 2px; background: var(--sj-rule); } +.sj-in-end { padding-bottom: 0; } +.sj-in-end::before { display: none; } +.sj-in-node { position: absolute; left: 0; top: 1px; width: 16px; height: 16px; border-radius: 999px; display: grid; place-items: center; border: 1.5px solid color-mix(in srgb, var(--sj-who-c) 45%, var(--sj-rule)); background: var(--sj-card); color: var(--sol-text-dim); } +.sj-in-node svg { width: 9px; height: 9px; } +.sj-in-node .sj-pulse, .sj-in-node .sj-wait { width: 6px; height: 6px; } +.sj-in-end .sj-in-node { left: 3px; top: 4px; width: 10px; height: 10px; border-radius: 2px; transform: rotate(45deg); border-color: var(--sj-rule); } +.sj-in-step[data-state="done"] .sj-in-node { background: var(--sj-ok); border-color: var(--sj-ok); color: #fff; } +.sj-in-step[data-state="active"] .sj-in-node { border-color: var(--sj-who-c); box-shadow: 0 0 0 3px color-mix(in srgb, var(--sj-who-c) 16%, transparent); } +.sj-in-step[data-state="routed"] .sj-in-node { border-color: var(--sol-text-dim); color: var(--sol-text-muted); } +.sj-in-step[data-state="stopped"] .sj-in-node { background: var(--sj-bad); border-color: var(--sj-bad); color: #fff; } +.sj-in-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; min-height: 18px; } +.sj-in-head b { font-size: 12.5px; font-weight: 600; } +.sj-in-beside { font-style: normal; font-weight: 400; color: var(--sol-text-dim); } +.sj-in-who { font-size: var(--fs-meta); color: var(--sj-who-c); } +.sj-in-routes { list-style: none; margin: 6px 0 0; padding: 0; display: flex; flex-direction: column; gap: 5px; } +/* Each route leaves the spine on an elbow and reads left to right: when, the steps it runs, where it goes back to. */ +.sj-in-route { position: relative; display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 6px; padding-left: 14px; line-height: 1.45; color: var(--sol-text-muted); } +.sj-in-route::before { content: ""; position: absolute; left: -18px; top: -5px; width: 26px; height: 14px; border: solid var(--sj-rule); border-width: 0 0 1.5px 1.5px; border-bottom-left-radius: 9px; } +.sj-in-when { font-style: italic; color: var(--sol-text-dim); } +/* An arrow keeps to the step it leads to, so a wrapped route never starts a line with one, and stays outside a pill. */ +.sj-in-hops { display: inline-flex; align-items: baseline; gap: 6px; } +.sj-in-arrow { font-style: normal; color: var(--sol-text-dim); } +.sj-in-hop { color: var(--sol-text); font-weight: 500; } +.sj-in-to { display: inline-flex; align-items: center; gap: 3px; font-size: var(--fs-meta); color: var(--sol-text-dim); } +.sj-in-route[data-to="session"] .sj-in-to { color: color-mix(in srgb, var(--sj-session) 85%, var(--sol-text-dim)); } +/* A person's step only a turn reaches: dashed, as the route that leads to it, with what makes a run ask under it. */ +.sj-in-route[data-asks]::before { border-style: dashed; border-color: color-mix(in srgb, var(--sj-you) 55%, transparent); } +.sj-in-hop:is([data-who="person"], [data-who="you"]) { padding: 0 7px; border: 1px dashed color-mix(in srgb, var(--sj-you) 60%, transparent); border-radius: 999px; color: var(--sj-you); background: color-mix(in srgb, var(--sj-you) 7%, transparent); } +.sj-in-if { flex-basis: 100%; font-size: var(--fs-meta); color: var(--sj-you); } +/* On a run: the route it is on now, the one that sent the work back, and the card waiting on an answer. */ +.sj-in-route[data-state="active"] .sj-in-hop[data-state="active"] { color: var(--sol-blue); } +.sj-in-route[data-state="back"], .sj-in-route[data-state="back"] .sj-in-hop { color: var(--sj-session); } +.sj-in-route[data-state="back"]::before { border-color: var(--sj-session); } +.sj-in-route[data-state="back"] .sj-in-to { color: var(--sj-session); font-weight: 600; } +.sj-in-hop[data-state="waiting"] { border-style: solid; border-color: var(--sj-wait); background: color-mix(in srgb, var(--sj-wait) 16%, var(--sj-card)); color: var(--sol-text); } +.sj-in-route[data-state="waiting"]::before { border-color: var(--sj-wait); } /* A Ship press the session answered without a run: its answer, quoted. */ .shp-declined { padding: 9px 14px 10px; border-bottom: 1px solid var(--sj-rule-2); background: var(--sj-sunk); } .shp-declined header { display: flex; align-items: baseline; gap: 8px; min-width: 0; } @@ -166,6 +215,9 @@ button.shp-link { background: none; border: 0; padding: 0; cursor: pointer; font .shp-session { font-size: 13px; color: var(--sol-text); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .sj-target-item { display: inline-flex; align-items: center; gap: 4px; } .shp-asks { display: inline-block; margin-right: 10px; padding: 0 7px; border-radius: 999px; font-size: var(--fs-meta); font-weight: 600; color: var(--sol-text-muted); background: color-mix(in srgb, var(--sol-text-dim) 12%, transparent); } +.shp-flowname .shp-asks { margin: 0 0 0 8px; } +/* In a flow's row, whether it asks reads in full on a line of its own under the name and path. */ +.shp-flow > .shp-asks { grid-column: 2 / -1; justify-self: start; margin: -4px 0 0; padding: 1px 8px; border-radius: 8px; line-height: 1.4; } .shp-asks[data-asks] { color: var(--sol-blue); background: color-mix(in srgb, var(--sol-blue) 12%, transparent); } .shp-foot .sj-btn[data-primary] { background: var(--sol-blue); border-color: var(--sol-blue); color: #fff; } .shp-foot .sj-btn[data-primary]:hover { filter: brightness(1.08); background: var(--sol-blue); } diff --git a/packages/web/lib/line/shippedFlows.generated.ts b/packages/web/lib/line/shippedFlows.generated.ts index 87da0e8f75..177fbb1ed7 100644 --- a/packages/web/lib/line/shippedFlows.generated.ts +++ b/packages/web/lib/line/shippedFlows.generated.ts @@ -8,7 +8,7 @@ export const SHIPPED_FLOWS: ShippedFlow[] = [ {"slug":"check","kind":"segment","label":"Check","description":"The project's check command on the change","takes":["branch"],"extends":null,"stations":[{"id":"verify","label":"Verify","kind":"script","next":[{"to":"Passed","toId":"passed","when":"outcome = success"},{"to":"Checks failed","toId":"failed","when":"outcome = failure and verify.exit_code != 2"},{"to":"Not checked here","toId":"unjudged","when":"outcome = failure and verify.exit_code = 2"}],"main":true}],"ends":["Passed","Checks failed","Not checked here"],"uses":[],"name":"check","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"verify","label":"Verify","shape":"parallelogram","type":"command","timeout":3600},{"id":"passed","label":"Passed","shape":"Msquare","type":"exit"},{"id":"failed","label":"Checks failed","shape":"Msquare","type":"exit","stop":"The project's check failed on the change: $verify.summary"},{"id":"unjudged","label":"Not checked here","shape":"Msquare","type":"exit","stop":"This machine could not run the project's check, so the change is not judged yet: $verify.summary. Fix the machine, or run the flow again on one that can.","machine":true}],"edges":[{"from":"start","to":"verify"},{"from":"verify","to":"passed","condition":"outcome = success"},{"from":"verify","to":"failed","condition":"outcome = failure and verify.exit_code != 2"},{"from":"verify","to":"unjudged","condition":"outcome = failure and verify.exit_code = 2"}]}, {"slug":"review","kind":"segment","label":"Review","description":"An independent session reads the diff against the intent","takes":["task","branch"],"extends":null,"stations":[{"id":"review","label":"Review","kind":"agent","next":[{"to":"Approved","toId":"approved","when":"review_verdict = approve"},{"to":"Changes asked","toId":"changes","when":"review_verdict = changes"},{"to":"Rejected","toId":"rejected","when":"review_verdict = reject"}],"main":true}],"ends":["Approved","Changes asked","Rejected"],"uses":[],"name":"review","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"review","label":"Review","shape":"box","type":"agent","backend":"session","agent":"claude"},{"id":"approved","label":"Approved","shape":"Msquare","type":"exit"},{"id":"changes","label":"Changes asked","shape":"Msquare","type":"exit","stop":"The reviewer asked for changes. $review_note"},{"id":"rejected","label":"Rejected","shape":"Msquare","type":"exit","stop":"The reviewer rejected the change. $review_note"}],"edges":[{"from":"start","to":"review"},{"from":"review","to":"approved","condition":"review_verdict = approve"},{"from":"review","to":"changes","condition":"review_verdict = changes"},{"from":"review","to":"rejected","condition":"review_verdict = reject"}]}, {"slug":"judge","kind":"segment","label":"Judge","description":"A model scores the change's risk from its diff and the repository's guidelines, blind to who made it","takes":["branch"],"extends":null,"stations":[{"id":"guidelines","label":"Guidelines","kind":"script","next":[{"to":"Diff","toId":"diff","when":"outcome = success"},{"to":"Unscored","toId":"unscored","when":null}],"main":true},{"id":"diff","label":"Diff","kind":"script","next":[{"to":"Judge","toId":"judge","when":"outcome = success"},{"to":"Unscored","toId":"unscored","when":null}],"main":true},{"id":"judge","label":"Judge","kind":"call","next":[{"to":"High risk","toId":"high","when":"outcome = success and judge.json.risk >= 50"},{"to":"Low risk","toId":"low","when":"outcome = success and judge.json.risk < 50"},{"to":"Unscored","toId":"unscored","when":null}],"main":true}],"ends":["Unscored","High risk","Low risk"],"uses":[],"name":"judge","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"guidelines","label":"Guidelines","shape":"parallelogram","type":"command","timeout":120},{"id":"diff","label":"Diff","shape":"parallelogram","type":"command","timeout":120},{"id":"judge","label":"Judge","shape":"note","type":"call"},{"id":"low","label":"Low risk","shape":"Msquare","type":"exit"},{"id":"high","label":"High risk","shape":"Msquare","type":"exit"},{"id":"unscored","label":"Unscored","shape":"Msquare","type":"exit"}],"edges":[{"from":"start","to":"guidelines"},{"from":"guidelines","to":"diff","condition":"outcome = success"},{"from":"guidelines","to":"unscored"},{"from":"diff","to":"judge","condition":"outcome = success"},{"from":"diff","to":"unscored"},{"from":"judge","to":"high","condition":"outcome = success and judge.json.risk >= 50"},{"from":"judge","to":"low","condition":"outcome = success and judge.json.risk < 50"},{"from":"judge","to":"unscored"}]}, - {"slug":"intent","kind":"segment","label":"Intent","description":"Whether the person who started the run already said to ship this change, in their own words, checked against the record","takes":["task","branch"],"extends":null,"stations":[{"id":"asker","label":"Asker","kind":"script","next":[{"to":"Change","toId":"change","when":"outcome = success"},{"to":"Read failed","toId":"failed","when":null}],"main":true},{"id":"change","label":"Change","kind":"script","next":[{"to":"Read","toId":"read","when":"outcome = success"},{"to":"Read failed","toId":"failed","when":null}],"main":true},{"id":"failed","label":"Read failed","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":false},{"id":"read","label":"Read","kind":"call","next":[{"to":"Verify","toId":"clear","when":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.session and read.json.quote and read.json.line > 0"},{"to":"Verify card","toId":"clear_card","when":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.card and read.json.quote"},{"to":"Not said","toId":"declined","when":"outcome = success and read.json.why and (read.json.ship != true or read.json.in_scope != true)"},{"to":"No citation","toId":"unreadable","when":"outcome = success"},{"to":"Read failed","toId":"failed","when":null}],"main":true},{"id":"clear","label":"Verify","kind":"script","next":[{"to":"Verified","toId":"cleared","when":"outcome = success"},{"to":"Refused","toId":"refused","when":null}],"main":true},{"id":"clear_card","label":"Verify card","kind":"script","next":[{"to":"Verified","toId":"cleared","when":"outcome = success"},{"to":"Refused","toId":"refused","when":null}],"main":false},{"id":"declined","label":"Not said","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":false},{"id":"unreadable","label":"No citation","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":false},{"id":"refused","label":"Refused","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":true}],"ends":["Ask","Verified"],"uses":[],"name":"intent","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"asker","label":"Asker","shape":"parallelogram","type":"command","timeout":120},{"id":"change","label":"Change","shape":"parallelogram","type":"command","timeout":120},{"id":"read","label":"Read","shape":"note","type":"call"},{"id":"clear","label":"Verify","shape":"parallelogram","type":"command","timeout":120},{"id":"clear_card","label":"Verify card","shape":"parallelogram","type":"command","timeout":120},{"id":"declined","label":"Not said","shape":"parallelogram","type":"command","timeout":60},{"id":"unreadable","label":"No citation","shape":"parallelogram","type":"command","timeout":60},{"id":"refused","label":"Refused","shape":"parallelogram","type":"command","timeout":60},{"id":"failed","label":"Read failed","shape":"parallelogram","type":"command","timeout":60},{"id":"cleared","label":"Verified","shape":"Msquare","type":"exit"},{"id":"ask","label":"Ask","shape":"Msquare","type":"exit"}],"edges":[{"from":"start","to":"asker"},{"from":"asker","to":"change","condition":"outcome = success"},{"from":"asker","to":"failed"},{"from":"change","to":"read","condition":"outcome = success"},{"from":"change","to":"failed"},{"from":"read","to":"clear","condition":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.session and read.json.quote and read.json.line > 0"},{"from":"read","to":"clear_card","condition":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.card and read.json.quote"},{"from":"read","to":"declined","condition":"outcome = success and read.json.why and (read.json.ship != true or read.json.in_scope != true)"},{"from":"read","to":"unreadable","condition":"outcome = success"},{"from":"read","to":"failed"},{"from":"clear","to":"cleared","condition":"outcome = success"},{"from":"clear","to":"refused"},{"from":"clear_card","to":"cleared","condition":"outcome = success"},{"from":"clear_card","to":"refused"},{"from":"declined","to":"ask"},{"from":"unreadable","to":"ask"},{"from":"refused","to":"ask"},{"from":"failed","to":"ask"}]}, + {"slug":"intent","kind":"segment","label":"Intent","description":"Whether the person who started the run already said to ship this change, in their own words, checked against the record","takes":["task","branch"],"extends":null,"stations":[{"id":"asker","label":"Asker","kind":"script","next":[{"to":"Change","toId":"change","when":"outcome = success"},{"to":"Read failed","toId":"failed","when":null}],"main":true},{"id":"change","label":"Change","kind":"script","next":[{"to":"Read","toId":"read","when":"outcome = success"},{"to":"Read failed","toId":"failed","when":null}],"main":true},{"id":"failed","label":"Read failed","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":false},{"id":"read","label":"Read","kind":"call","next":[{"to":"Verify","toId":"clear","when":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.session and read.json.quote and read.json.line > 0"},{"to":"Verify card","toId":"clear_card","when":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.card and read.json.quote"},{"to":"Not said","toId":"declined","when":"outcome = success and read.json.why and (read.json.ship != true or read.json.in_scope != true)"},{"to":"No citation","toId":"unreadable","when":"outcome = success"},{"to":"Read failed","toId":"failed","when":null}],"main":true},{"id":"clear","label":"Verify","kind":"script","next":[{"to":"Verified","toId":"cleared","when":"outcome = success"},{"to":"Refused","toId":"refused","when":null}],"main":true},{"id":"clear_card","label":"Verify card","kind":"script","next":[{"to":"Verified","toId":"cleared","when":"outcome = success"},{"to":"Refused","toId":"refused","when":null}],"main":false},{"id":"declined","label":"Not said","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":false},{"id":"unreadable","label":"No citation","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":false},{"id":"refused","label":"Refused","kind":"script","next":[{"to":"Ask","toId":"ask","when":null}],"main":false}],"ends":["Ask","Verified"],"uses":[],"name":"intent","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"asker","label":"Asker","shape":"parallelogram","type":"command","timeout":120},{"id":"change","label":"Change","shape":"parallelogram","type":"command","timeout":120},{"id":"read","label":"Read","shape":"note","type":"call"},{"id":"clear","label":"Verify","shape":"parallelogram","type":"command","timeout":120},{"id":"clear_card","label":"Verify card","shape":"parallelogram","type":"command","timeout":120},{"id":"declined","label":"Not said","shape":"parallelogram","type":"command","timeout":60},{"id":"unreadable","label":"No citation","shape":"parallelogram","type":"command","timeout":60},{"id":"refused","label":"Refused","shape":"parallelogram","type":"command","timeout":60},{"id":"failed","label":"Read failed","shape":"parallelogram","type":"command","timeout":60},{"id":"cleared","label":"Verified","shape":"Msquare","type":"exit"},{"id":"ask","label":"Ask","shape":"Msquare","type":"exit"}],"edges":[{"from":"start","to":"asker"},{"from":"asker","to":"change","condition":"outcome = success"},{"from":"asker","to":"failed"},{"from":"change","to":"read","condition":"outcome = success"},{"from":"change","to":"failed"},{"from":"read","to":"clear","condition":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.session and read.json.quote and read.json.line > 0"},{"from":"read","to":"clear_card","condition":"outcome = success and read.json.ship = true and read.json.in_scope = true and read.json.card and read.json.quote"},{"from":"read","to":"declined","condition":"outcome = success and read.json.why and (read.json.ship != true or read.json.in_scope != true)"},{"from":"read","to":"unreadable","condition":"outcome = success"},{"from":"read","to":"failed"},{"from":"clear","to":"cleared","condition":"outcome = success"},{"from":"clear","to":"refused"},{"from":"clear_card","to":"cleared","condition":"outcome = success"},{"from":"clear_card","to":"refused"},{"from":"declined","to":"ask"},{"from":"unreadable","to":"ask"},{"from":"refused","to":"ask"},{"from":"failed","to":"ask"}]}, {"slug":"eval","kind":"segment","label":"Eval","description":"The project's evals on the base and on the change","takes":["branch"],"extends":null,"stations":[{"id":"eval","label":"Eval","kind":"script","next":[{"to":"Passed","toId":"passed","when":"outcome = success"},{"to":"Eval failed","toId":"worse","when":"outcome = failure and eval.exit_code = 1"},{"to":"Unscored","toId":"unscored","when":"outcome = failure and eval.exit_code != 1"}],"main":true}],"ends":["Passed","Eval failed","Unscored"],"uses":[],"name":"eval","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"eval","label":"Eval","shape":"parallelogram","type":"command","timeout":10800},{"id":"passed","label":"Passed","shape":"Msquare","type":"exit"},{"id":"worse","label":"Eval failed","shape":"Msquare","type":"exit","stop":"The evals scored the change worse than the base. $eval.output"},{"id":"unscored","label":"Unscored","shape":"Msquare","type":"exit","stop":"The evals could not score the change. $eval.output"}],"edges":[{"from":"start","to":"eval"},{"from":"eval","to":"passed","condition":"outcome = success"},{"from":"eval","to":"worse","condition":"outcome = failure and eval.exit_code = 1"},{"from":"eval","to":"unscored","condition":"outcome = failure and eval.exit_code != 1"}]}, {"slug":"decide","kind":"segment","label":"Decide","description":"The person who answers for the change says ship, revise or drop","takes":["task"],"extends":null,"stations":[{"id":"decide","label":"Decide","kind":"person","next":[{"to":"Ship","toId":"ship","when":"Ship"},{"to":"Revise","toId":"revise","when":"Revise"},{"to":"Dropped","toId":"dropped","when":"Drop"}],"main":true}],"ends":["Ship","Revise","Dropped"],"uses":[],"name":"decide","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"decide","label":"Decide","shape":"hexagon","type":"human"},{"id":"ship","label":"Ship","shape":"Msquare","type":"exit"},{"id":"revise","label":"Revise","shape":"Msquare","type":"exit","stop":"Sent back for revision. $human_message"},{"id":"dropped","label":"Dropped","shape":"Msquare","type":"exit","stop":"Dropped at the gate. $human_message"}],"edges":[{"from":"start","to":"decide"},{"from":"decide","to":"ship","label":"[S] Ship :: Lands it on the main branch"},{"from":"decide","to":"revise","label":"[R] Revise :: Your note goes to the session that made it; the change comes back through review"},{"from":"decide","to":"dropped","label":"[D] Drop :: Closes it unlanded; the session hears your reason"}]}, {"slug":"ship","kind":"segment","label":"Land","description":"Rebase on the default branch, check, and land the change","takes":["task","branch"],"extends":null,"stations":[{"id":"rebase","label":"Rebase","kind":"script","next":[{"to":"Land","toId":"ship","when":"outcome = success and rebase.json.landed != true"},{"to":"Already landed","toId":"landed","when":"outcome = success and rebase.json.landed = true"},{"to":"Conflict","toId":"conflict","when":"outcome = failure and rebase.exit_code = 1"},{"to":"Land","toId":"ship","when":"outcome = failure and rebase.exit_code != 1"}],"main":true},{"id":"ship","label":"Land","kind":"script","next":[{"to":"Shipped","toId":"shipped","when":"outcome = success"},{"to":"Rebase","toId":"rebase","when":"default branch moved"},{"to":"Not shipped","toId":"unshipped","when":"outcome = failure and ship.exit_code != 3"}],"main":true}],"ends":["Already landed","Conflict","Shipped","Not shipped"],"uses":[],"name":"ship","nodes":[{"id":"start","label":"start","shape":"Mdiamond","type":"start"},{"id":"rebase","label":"Rebase","shape":"parallelogram","type":"command","max_visits":3,"timeout":3600},{"id":"ship","label":"Land","shape":"parallelogram","type":"command","timeout":4500},{"id":"shipped","label":"Shipped","shape":"Msquare","type":"exit"},{"id":"landed","label":"Already landed","shape":"Msquare","type":"exit"},{"id":"conflict","label":"Conflict","shape":"Msquare","type":"exit","stop":"The change does not rebase cleanly or fails the check on the default branch. $rebase.output"},{"id":"unshipped","label":"Not shipped","shape":"Msquare","type":"exit","stop":"The change was not shipped. $ship.output"}],"edges":[{"from":"start","to":"rebase"},{"from":"rebase","to":"ship","condition":"outcome = success and rebase.json.landed != true"},{"from":"rebase","to":"landed","condition":"outcome = success and rebase.json.landed = true"},{"from":"rebase","to":"conflict","condition":"outcome = failure and rebase.exit_code = 1"},{"from":"rebase","to":"ship","condition":"outcome = failure and rebase.exit_code != 1"},{"from":"ship","to":"shipped","condition":"outcome = success"},{"from":"ship","to":"rebase","label":"default branch moved","condition":"outcome = failure and ship.exit_code = 3"},{"from":"ship","to":"unshipped","condition":"outcome = failure and ship.exit_code != 3"}]}, diff --git a/packages/web/lib/renderGallery.ts b/packages/web/lib/renderGallery.ts index b7051fc69e..9657fae74b 100644 --- a/packages/web/lib/renderGallery.ts +++ b/packages/web/lib/renderGallery.ts @@ -703,6 +703,8 @@ export function renderGalleryMessages(now: number): Row[] { asst(`Landed, waiting on a deploy:\n\n\`\`\`${FLOW_FENCE_LANG}\n{"run":"${GALLERY_FLOW.shipDeploy}"}\n\`\`\``); asst(`Live everywhere it ships:\n\n\`\`\`${FLOW_FENCE_LANG}\n{"run":"${GALLERY_FLOW.shipLive}"}\n\`\`\``); asst(`A finished run of a library flow:\n\n\`\`\`${FLOW_FENCE_LANG}\n{"run":"${GALLERY_FLOW.libraryRun}"}\n\`\`\``); + asst(`A flow that is one segment, its findings sent back to this session (press Land to see inside it):\n\n\`\`\`${FLOW_FENCE_LANG}\n{"run":"${GALLERY_FLOW.shipLandBack}"}\n\`\`\``); + asst(`The same flow at the person's card inside Land:\n\n\`\`\`${FLOW_FENCE_LANG}\n{"run":"${GALLERY_FLOW.shipLandCard}"}\n\`\`\``); section("Pipeline"); sh(EDIT_ADD.command, EDIT_ADD.output); diff --git a/packages/web/lib/renderGalleryFlows.ts b/packages/web/lib/renderGalleryFlows.ts index 53d251aafc..03b2a7f608 100644 --- a/packages/web/lib/renderGalleryFlows.ts +++ b/packages/web/lib/renderGalleryFlows.ts @@ -4,7 +4,7 @@ // Pure and free of the `@/` alias: the phone's bundle and tests import it through the gallery. import { readEdit } from "./line/flowEditFence"; import { EDIT_SKIP } from "./renderGalleryPipeline.generated"; -import { BRANCHING_FLOW, FANOUT_FLOW } from "./ship/journeyFixtures"; +import { BRANCHING_FLOW, FANOUT_FLOW, LAND_FLOW } from "./ship/journeyFixtures"; // The flow object (ct-69934): their runs, graph and session-flow row are store records the gallery's loader seeds // (renderGalleryRecords). @@ -32,8 +32,12 @@ export const GALLERY_FLOW = { // Landed and held on main's red CI; a change that edits CI, at the person's card off the main path. shipHeld: "galleryshiprunheldmain01", shipCiCard: "galleryshipruncicard0001", + // A flow that is one segment, Land: its findings sent back to the session, and a change at the person's card inside it. + shipLandBack: "galleryshiprunlandback01", + shipLandCard: "galleryshiprunlandcard01", branchingGraph: "galleryflowbranching0001", fanoutGraph: "galleryflowfanout0000001", + landGraph: "galleryflowland000000001", // The pipeline's inline objects (pipeline.md PL5, PL6): the change run that carried the skip edit out, and the repo's pipeline. editLive: "galleryeditrunlive000001", pipeline: "gallerypipeline000000001", @@ -88,6 +92,8 @@ export function shipRuns(now: number, viewerId: string, workspace: string, conve const failed = (id: string) => ({ ...status(id, "completed"), status: "failed" }); const fan = { ...base, workflow_id: GALLERY_FLOW.fanoutGraph, workflow_slug: FANOUT_FLOW.slug, workflow_name: FANOUT_FLOW.name }; const branching = { ...base, workflow_id: GALLERY_FLOW.branchingGraph, workflow_slug: BRANCHING_FLOW.slug, workflow_name: BRANCHING_FLOW.name }; + const land = { ...base, workflow_id: GALLERY_FLOW.landGraph, workflow_slug: LAND_FLOW.slug, workflow_name: LAND_FLOW.name }; + const landRound = [...through("land__pr", "land__checks"), said("land__ci", "Waiting on CI for #12 at abc1234: 14 of 14 jobs done, 11m"), ...through("land__review", "land__read")]; const merge = (at: number) => ({ sha: "4a6e413b2c", branch: "codecast/change-ct-4110", into: "main", at }); // The round: PR, then CI and Review side by side; CI's last progress line stays on its node, Review reports nothing. const round = [...through("pr", "checks"), said("ci", "Waiting on CI for #12 at abc1234: a second look before calling it green, 9m"), status("review", "completed"), status("joined", "completed")]; @@ -130,6 +136,13 @@ export function shipRuns(now: number, viewerId: string, workspace: string, conve // The change run that carried the skip edit out (it ran the graph the edit built), live in refs.liveDeploy. { ...base, workflow_slug: "change", workflow_name: "change", _id: GALLERY_FLOW.editLive, graph_hash: readEdit(EDIT_SKIP_FENCE)!.graph_hash, task_short_id: "ct-4111", task_title: "Skip Decide on this repo's changes", status: "completed", current_node_id: "exit", merge: merge(now - 700_000), node_statuses: [...through("pr", "lint"), ...merged.slice(1), said("deploy__wait", `Live: 4a6e413b2c on web ${refs.liveDeploy}.`), status("deploy__live", "completed")] }, + // Land's Read found something: its Brief went back to the session through the segment's Changes asked. + { ...land, _id: GALLERY_FLOW.shipLandBack, status: "running", current_node_id: "fix", + waiting_on_session: { node_id: "fix", conversation_id: conversationId, since: now - 180_000, note: "CI red on #12: 1 failure in test-web (inboxDivider.test.ts: the count reads 0 with sessions below it)." }, + node_statuses: [...landRound, ...through("land__brief", "land__changes"), { ...status("fix", "running"), visits: 1 }] }, + // Merge stopped on exit 6, the change edits what judges it: the card inside Land waits on the viewer. + { ...land, _id: GALLERY_FLOW.shipLandCard, status: "paused", current_node_id: "land__card__decide", gate_node_id: "land__card__decide", gate_prompt: "Ship ct-4110? It edits CI, so CI can't vouch for it.", gate_decision_id: refs.decision, gate_decision_short_id: refs.decisionShort, + node_statuses: [...landRound, failed("land__merge"), ...through("land__why_card", "land__card"), { ...status("land__card__decide", "running"), started_at: now - 40_000 }] }, // Merge refused: the runner reports the exit it stopped at. { ...fan, _id: GALLERY_FLOW.shipRefused, status: "failed", current_node_id: "unshipped", fail_reason: "Stopped: The merge guard refused: the branch would undo changes main made to packages/web/lib/inboxDivider.ts since 4a6e413.", @@ -138,6 +151,6 @@ export function shipRuns(now: number, viewerId: string, workspace: string, conve } /** The pushed graphs the branching and fan-out run cards draw from. */ -export const shipGraphs = (now: number, viewerId: string, workspace: string) => [BRANCHING_FLOW, FANOUT_FLOW].map((f) => ({ - ...f, _id: f === BRANCHING_FLOW ? GALLERY_FLOW.branchingGraph : GALLERY_FLOW.fanoutGraph, user_id: viewerId, workspace, created_at: now, updated_at: now, +export const shipGraphs = (now: number, viewerId: string, workspace: string) => ([[BRANCHING_FLOW, GALLERY_FLOW.branchingGraph], [FANOUT_FLOW, GALLERY_FLOW.fanoutGraph], [LAND_FLOW, GALLERY_FLOW.landGraph]] as const).map(([f, _id]) => ({ + ...f, _id, user_id: viewerId, workspace, created_at: now, updated_at: now, })); diff --git a/packages/web/lib/ship/__tests__/journey.test.ts b/packages/web/lib/ship/__tests__/journey.test.ts index 10672b169d..232eccc4b6 100644 --- a/packages/web/lib/ship/__tests__/journey.test.ts +++ b/packages/web/lib/ship/__tests__/journey.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; -import { approvalOf, approvalWords, canAnswer, deployHold, journeyOf, journeyStages, journeyWords, landedSha, readableWhy, sentBackWords, targetsFromLine, verdictsOf, waitWords } from "../journey"; -import { BRANCHING_FLOW, FANOUT_FLOW } from "../journeyFixtures"; -import { pushedFlow } from "../../line/flowPool"; +import { approvalOf, approvalWords, canAnswer, deployHold, insideWords, journeyOf, journeyStages, journeyWords, landedSha, readableWhy, sentBackWords, targetsFromLine, verdictsOf, waitWords } from "../journey"; +import { BRANCHING_FLOW, FANOUT_FLOW, LAND_ASKS, LAND_FLOW, LAND_REPO_FLOW } from "../journeyFixtures"; +import { appPool, flowBySlug, pushedFlow } from "../../line/flowPool"; import { SHIPPED_FLOWS } from "../../line/shippedFlows.generated"; import { GALLERY_FLOW, renderGalleryRecords } from "../../renderGallery"; // The library change flow, parsed with its segments expanded (bun packages/cli/scripts/gen-change-graph-fixture.ts). @@ -446,3 +446,87 @@ describe("approvalOf", () => { expect(approvalWords(approvalOf(g))).toBe("Asks you every time"); }); }); + +// Union's change: one segment, Land, as Union's checkout reports it (the card's gate holds land.cast's asks_if). +describe("a segment's inside", () => { + // As the Ship picker reads it in Union's checkout: the repository's own flow, folded into the pool. + const land = flowBySlug(appPool([], [LAND_REPO_FLOW]), "change")!; + const ASKS = LAND_ASKS; + const stage = () => journeyStages(land)[0]; + test("the stage holds its passing path, read from the graph: PR, CI beside Review, Merge, then the segment's end", () => { + const s = stage(); + expect(journeyStages(land).map((x) => [x.label, x.who])).toEqual([["Land", "agent"]]); + expect(s.inside!.path.map((p) => [p.id, p.label, p.branches?.map((b) => b.label) ?? null])).toEqual([ + ["land__pr", "PR", null], ["land__checks", "CI + Review", ["CI", "Review"]], ["land__merge", "Merge", null], + ]); + expect(insideWords(s.inside!)).toBe("PR · CI + Review · Merge"); + expect(s.inside!.end).toBe("Merged"); + }); + test("each side route leaves the step it turns off, by its edge's label, and says where it goes back to", () => { + const routes = stage().inside!.routes.map((r) => [r.from, r.label, r.steps.map((x) => x.label).join(" → "), r.to.kind === "step" ? r.to.label : r.to.kind]); + expect(routes).toEqual([ + ["land__checks", "findings", "Brief", "session"], + ["land__checks", "main is red", "Wait for green main → CI again, main moved", "Merge"], + ["land__merge", "main moved", "CI again, main moved", "Merge"], + ["land__merge", "conflict", "Does not fit main", "session"], + ["land__merge", "head moved", "", "PR"], + ["land__merge", "edits what judges it", "Why a person → Decide → Person said Ship", "Merge"], + ]); + // A route whose condition the parser decided false (the review left on) is no route. + expect(routes.some(([, label]) => label === "review off")).toBe(false); + }); + test("the person's card is a route of its own that asks only then, in its card's words; the chip says so and the stage is no person's", () => { + const card = stage().inside!.routes.find((r) => r.asks)!; + expect(card.steps.map((x) => [x.label, x.who])).toEqual([["Why a person", "auto"], ["Decide", "person"], ["Person said Ship", "auto"]]); + expect(card.asks).toEqual({ when: ASKS }); + expect(stage().inside!.routes.filter((r) => r.asks)).toHaveLength(1); + expect(approvalOf(land)).toEqual({ kind: "if", when: ASKS }); + expect(approvalWords(approvalOf(land))).toBe(`Asks you if ${ASKS}`); + }); + test("asks_if is read from the gate, else the segment holding it, out to the flow's own segment node", () => { + const at = (id: string | null) => ({ ...land, nodes: land.nodes.map(({ asks_if: _a, ...n }) => (n.id === id ? { ...n, asks_if: "it is Tuesday" } : n)) }); + expect(approvalOf(at("land__card"))).toEqual({ kind: "if", when: "it is Tuesday" }); + expect(approvalOf(at("land"))).toEqual({ kind: "if", when: "it is Tuesday" }); + expect(approvalOf(at(null))).toEqual({ kind: "if", when: null }); + // A pushed row stores no asks_if, and its source (change.cast) does not name the card: it can only say "sometimes". + expect(approvalWords(approvalOf(pushedFlow({ _id: "wf_land", ...LAND_FLOW })))).toBe("Sometimes asks you"); + }); + test("who sent it back: Land's own findings are not the card's, though both sit in Land; a Revise at the card is the person's", () => { + let t = 1000; + const at = (id: string, status = "completed") => st(id, status, (t += 10)); + const upTo = [at("land"), at("land__pr"), at("land__checks"), at("land__ci"), at("land__review"), at("land__read")]; + const back = (node: string, steps: any[]) => journeyOf(land, run({ current_node_id: node, waiting_on_session: { node_id: node, since: t, note: "" }, node_statuses: [...steps, at(node, "running")] })).now; + expect(back("fix", [...upTo, at("land__brief"), at("land__changes", "failed")])).toMatchObject({ kind: "session", by: null }); + expect(back("revise", [...upTo, at("land__merge", "failed"), at("land__why_card"), at("land__card"), at("land__card__decide"), at("land__card__revise", "failed"), at("land__revise", "failed")])).toMatchObject({ kind: "session", by: "the person" }); + }); + test("round 2 back at PR: nothing inside reads as last round's", () => { + let t = 1000; + const at = (id: string, status = "completed", visits = 1) => st(id, status, (t += 10), { visits }); + const round1 = [at("land"), at("land__pr"), at("land__checks"), at("land__ci"), at("land__review"), at("land__read"), at("land__merge", "failed"), at("land__retest"), at("land__brief"), at("land__changes", "failed"), at("fix")]; + const j = journeyOf(land, run({ current_node_id: "land__pr", node_statuses: [...round1, at("land__pr", "running", 2)] }), [], { id: ME, decision: null }); + expect([j.stages[0].state, j.stages[0].round]).toEqual(["active", 2]); + expect(j.stages[0].inside!.path.map((p) => p.state)).toEqual(["active", "idle", "idle"]); + expect(j.stages[0].inside!.routes.every((r) => r.state === "idle" && r.steps.every((s) => s.state === "idle"))).toBe(true); + }); + test("a segment whose inside is one step, nothing off it, draws none", () => { + expect(journeyStages(branching).some((s) => s.inside)).toBe(false); + expect(journeyStages(change).some((s) => s.inside)).toBe(false); + }); + test("on a run: the route that sent the work back reads back; the card a person must answer waits, theirs to answer", () => { + const records = renderGalleryRecords(1_790_000_000_000, ME, "team:t1"); + const read = (id: string, decision: unknown = null) => { + const r: any = records.workflowRuns.find((x: any) => x._id === id)!; + return journeyOf(land, r, [], { id: ME, decision: decision as any }); + }; + const back = read(GALLERY_FLOW.shipLandBack); + expect(back.stages[0].state).toBe("back"); + expect(back.stages[0].inside!.path.map((p) => p.state)).toEqual(["done", "done", "idle"]); + expect(back.stages[0].inside!.routes.map((r) => r.state)).toEqual(["back", "idle", "idle", "idle", "idle", "idle"]); + const atCard = read(GALLERY_FLOW.shipLandCard, card()); + expect(journeyWords(atCard).words).toBe("Your call"); + expect(atCard.stages[0].inside!.path.map((p) => p.state)).toEqual(["done", "done", "routed"]); + const route = atCard.stages[0].inside!.routes.find((r) => r.asks)!; + expect(route.state).toBe("waiting"); + expect(route.steps.map((x) => [x.label, x.state, x.who])).toEqual([["Why a person", "done", "auto"], ["Decide", "waiting", "you"], ["Person said Ship", "idle", "auto"]]); + }); +}); diff --git a/packages/web/lib/ship/journey.ts b/packages/web/lib/ship/journey.ts index c59675baed..dcb8aae313 100644 --- a/packages/web/lib/ship/journey.ts +++ b/packages/web/lib/ship/journey.ts @@ -10,6 +10,9 @@ // merged sha on the run. Pure, with relative imports only: the web's Ship panel // and run card, the inbox card and the phone's run card all read a run here. import { foldFlow, passScore, segmentTopOf, SEGMENT_SEP, type FlowEdgeIn, type FlowNodeIn } from "@codecast/shared/contracts/flowPool"; +import { asksIfOf, insideOf, insideOnRun, type RouteBase, type StageInside } from "./segmentInside"; + +export { insideWords, type InsideRoute, type StageInside } from "./segmentInside"; /** `you`: an open card on the stage the viewer may answer; `person`: a person answers there, the viewer or not. */ export type StageWho = "session" | "agent" | "you" | "person" | "auto"; @@ -38,6 +41,8 @@ export type JourneyStage = { steps?: StageStep[]; /** A fan-out's branches, side by side, each with its own state. */ branches?: JourneyStage[]; + /** A segment's own steps, when it has more than one or routes off them. */ + inside?: StageInside; }; export type StageStep = { id: string; label: string; status: string; visits: number | null; said: string | null; session: { id: string; title: string | null } | null; at: number | null }; @@ -145,7 +150,8 @@ export const gateOpen = (run: Pick & { members: string[]; kind: string; branches?: Base[]; /** Bookkeeping steps the stage holds after its own work (its verdicts, the sha it merged). */ tail?: string[] }; +/** `tail`: bookkeeping steps the stage holds after its own work (its verdicts, the sha it merged). */ +type Base = Omit & { members: string[]; kind: string; branches?: Base[]; tail?: string[]; inside?: { path: Base[]; routes: RouteBase[]; end: string | null } }; const isSubject = (n: FlowNodeIn | undefined) => n?.backend === "subject"; const inGroup = (stageId: string, nodeId: string) => nodeId === stageId || nodeId.startsWith(`${stageId}${SEGMENT_SEP}`); @@ -191,8 +197,9 @@ function passingSteps(graph: Graph, id: string): FlowNodeIn[] { return walked; } -/** The flow's stages on its main path, in the order a passing run reaches them, then Deploy and Live. */ -function planOf(graph: Graph, withTargets = false): Base[] { +/** The flow's stages on its main path, in the order a passing run reaches them, then Deploy and Live. `nested`: a + * segment's own steps, whose segments read as one step each. */ +function planOf(graph: Graph, withTargets = false, nested = false): Base[] { const folded = foldFlow(graph.nodes, graph.edges); const byId = new Map(graph.nodes.map((n) => [n.id, n])); const station = new Map(folded.stations.map((s) => [s.id, s])); @@ -229,7 +236,9 @@ function planOf(graph: Graph, withTargets = false): Base[] { const stageOf = (members: string[], label: string): Base => { const node = byId.get(members[0]); const deploy = members.length === 1 && isDeployStage(node); + const inside = !nested && members.length === 1 ? insideOf(graph, members[0], INSIDE_READERS) : undefined; return { + ...(inside ? { inside } : {}), id: members[0], label, role: deploy ? "deploy" : "step", @@ -289,7 +298,15 @@ function planOf(graph: Graph, withTargets = false): Base[] { ]; } -const strip = ({ members: _m, kind: _k, tail: _t, branches, ...s }: Base): Omit => ({ ...s, ...(branches ? { branches: branches.map((b) => ({ ...strip(b), state: "idle" as const, round: null })) } : {}) }); +const idleStage = (b: Base): JourneyStage => ({ ...strip(b), state: "idle", round: null }); +/** What a segment's inside reads of the journey: its own stages, whose segments read as one step each, and who acts. */ +const INSIDE_READERS = { plan: (g: Graph) => planOf(g, false, true), who: whoOf, passing: passingSteps }; + +const strip = ({ members: _m, kind: _k, tail: _t, branches, inside, ...s }: Base): Omit => ({ + ...s, + ...(branches ? { branches: branches.map(idleStage) } : {}), + ...(inside ? { inside: { ...inside, path: inside.path.map(idleStage), routes: inside.routes.map((r) => ({ ...r, state: "idle" as const, steps: r.steps.map((st) => ({ ...st, state: "idle" as const })) })) } } : {}), +}); /** The flow's stages on its main path, in execution order, then its Deploy and Live. */ export function journeyStages(graph: Graph): Omit[] { @@ -402,8 +419,16 @@ export function journeyOf(graph: Graph, run: JourneyRun | null | undefined, targ const route = graph.edges.find((e) => e.to === first && e.label && stageOf(e.from))?.label; return route ? route.charAt(0).toUpperCase() + route.slice(1) : byId.get(first)?.label ?? null; }; - // A step inside a person's card (a gate's own segment): what it sends back, the person sent back. - const byPerson = (nodeId: string | undefined) => !!nodeId && graph.nodes.some((n) => n.type === "human" && (n.id === nodeId || segmentTopOf(n.id) === segmentTopOf(nodeId))); + // Whether a person sent the work back to the session at `nodeId`: the last step the run took before it, past the ends it + // went out through (a step whose every way on leaves the segment it sits in), is a person's. A segment's own Brief + // inside the same segment as a card is not the card's. + const parentOf = (id: string) => (id.includes(SEGMENT_SEP) ? id.slice(0, id.lastIndexOf(SEGMENT_SEP)) : ""); + const endStep = (id: string) => { const out = graph.edges.filter((e) => e.from === id); return out.length > 0 && out.every((e) => parentOf(e.to) !== parentOf(id)); }; + const byPerson = (nodeId: string | null) => { + const since = statusOf(nodeId)?.started_at ?? Infinity; + const before = statuses.filter((n) => (n.started_at ?? 0) <= since && !isSubject(byId.get(n.node_id)) && !endStep(n.node_id)); + return byId.get(newest(before)?.node_id ?? "")?.type === "human"; + }; const backStage = live ? (backFrom(waitingOn?.node_id ?? null) ?? backFrom(at))?.id ?? null : null; const atBase = stageFor(at); const atStage = live ? atBase?.id ?? null : null; @@ -453,7 +478,7 @@ export function journeyOf(graph: Graph, run: JourneyRun | null | undefined, targ const isEntry = (id: string) => graph.nodes.some((x) => x.id.startsWith(`${id}${SEGMENT_SEP}`)); const isEnd = (id: string) => { const n = byId.get(id); return !!n && (n.type === "exit" || !!n.segment_exit); }; const stepsOf = (b: Base): StageStep[] => statuses - .filter((n) => (inStage(b, n.node_id) && !(b.members.includes(n.node_id) && isEntry(n.node_id)) && !isEnd(n.node_id)) || b.loops.some((l) => l.id === n.node_id)) + .filter((n) => (inStage(b, n.node_id) && !isEntry(n.node_id) && !isEnd(n.node_id)) || b.loops.some((l) => l.id === n.node_id)) .map((n) => ({ id: n.node_id, label: labelOf(n.node_id), status: n.status, visits: n.visits ?? null, said: n.result_preview?.trim() || n.activity || null, session: n.session ? { id: String(n.session._id), title: n.session.title ?? null } : null, at: n.started_at ?? null })); // What a stage's steps did last (one entry per node: its latest visit); a segment's entry only routes into its steps. const latestOf = (b: Base) => newest(statuses.filter((n) => inStage(b, n.node_id) && !(b.members.includes(n.node_id) && isEntry(n.node_id)))); @@ -488,12 +513,17 @@ export function journeyOf(graph: Graph, run: JourneyRun | null | undefined, targ if (said === "missing") return "routed"; return passed && last ? "done" : passed ? "skipped" : "idle"; }; + // A segment's inside on the run (segmentInside.ts insideOnRun). A stage after where the run stands holds nothing of this round. + const insideOn = (b: Base, index: number): StageInside => insideOnRun(b.inside!, { + statuses, here: gateNode ?? (live ? at : null), gate: !!gateNode, paused: run.status === "paused", live, + later: !passed && current >= 0 && index > current, back: b.id === backStage, gateWho: gateMine ? "you" : "person", + }, idleStage); const stageOn = (b: Base, index: number): JourneyStage => { const mine = statuses.filter((n) => inStage(b, n.node_id)); const rounds = Math.max(0, ...mine.map((n) => n.visits ?? 1)); // An open card says who may answer it: the viewer, or someone else. const who: StageWho = b.id === gateStage ? (gateMine ? "you" : "person") : b.who; - const base = { ...strip(b), ...(b.id === gateStage && gateOff ? { label: gateOff } : {}), who, steps: stepsOf(b), round: rounds > 1 ? rounds : null }; + const base = { ...strip(b), ...(b.id === gateStage && gateOff ? { label: gateOff } : {}), who, steps: stepsOf(b), round: rounds > 1 ? rounds : null, ...(b.inside ? { inside: insideOn(b, index) } : {}) }; if (b.role === "live") return { ...base, state: allLive ? "done" : passed ? "skipped" : "idle" }; if (b.role === "deploy") { const state: StageState = allLive ? "done" @@ -545,7 +575,7 @@ export function journeyOf(graph: Graph, run: JourneyRun | null | undefined, targ else if (live && backStage) { const loop = plan.find((s) => s.id === backStage)!.loops.find((l) => l.id === segmentTopOf(waitingOn?.node_id ?? at ?? "")); const node = statusOf(waitingOn?.node_id ?? at); - now = { kind: "session", stage: stageLabel(backStage)!, note: readableWhy(waitingOn?.note) ?? "", since: waitingOn?.since ?? node?.started_at ?? null, round: node?.visits ?? null, max: loop?.max ?? null, by: byPerson(routedFrom(waitingOn?.node_id ?? at ?? "", new Set())?.node_id) ? "the person" : null }; + now = { kind: "session", stage: stageLabel(backStage)!, note: readableWhy(waitingOn?.note) ?? "", since: waitingOn?.since ?? node?.started_at ?? null, round: node?.visits ?? null, max: loop?.max ?? null, by: byPerson(waitingOn?.node_id ?? at) ? "the person" : null }; } else if (open) { // The card's own step names the bar when it sits off every stage (a card a script asked for); on a stage, the stage. const onStage = gateNode ? stageOf(gateNode) : null; @@ -699,7 +729,7 @@ export type Approval = { kind: "always" } | { kind: "if"; when: string | null } * Who says yes before the change lands, read from the graph. A person's stage on the passing path before the one that * lands it asks on every run. Otherwise a person's step (a segment's own included) that a run can reach before the * change lands, at the runner's landing step or else an exit that is no stop, asks only when a run turns off toward it - * from a step that still lands without it: `when` is that step's `asks_if` (on it or on the segment that holds it), + * from a step that still lands without it: `when` is that step's `asks_if` (on it, else on each segment holding it, outermost last), * never a route's label, which names the route and is not written to finish a sentence. Anything else asks nobody. */ export function approvalOf(graph: Graph): Approval { @@ -729,11 +759,7 @@ export function approvalOf(graph: Graph): Approval { const passing = reach(lands, true, h); const towards = reach([h], true); const turn = graph.edges.find((e) => passing.has(e.from) && fromStart.has(e.from) && !passing.has(e.to) && towards.has(e.to)); - if (turn) { - const step = graph.nodes.find((n) => n.id === h); - const top = graph.nodes.find((n) => n.id === segmentTopOf(h)); - return { kind: "if", when: step?.asks_if ?? top?.asks_if ?? null }; - } + if (turn) return { kind: "if", when: asksIfOf(graph, h) }; } return { kind: "never" }; } diff --git a/packages/web/lib/ship/journeyFixtures.ts b/packages/web/lib/ship/journeyFixtures.ts index a2c90e1ba8..d7f31290ec 100644 --- a/packages/web/lib/ship/journeyFixtures.ts +++ b/packages/web/lib/ship/journeyFixtures.ts @@ -1,4 +1,4 @@ -// Two change flows as their pushed workflows rows (nodes, edges, and the source +// Three change flows as their pushed workflows rows (nodes, edges, and the source // pushedFlow reads backends, visit limits, stops and graph attributes from), for // the journey presenter's tests and the render gallery's run cards: // @@ -9,6 +9,14 @@ // non-zero to ask a person (the ask route) or clears the change to Land with // no card (the cleared route), Decide, Land (whose refusal goes through a // script off the main path before it stops), Deploy. +// - LAND_FLOW: Union's change (outreach/line/change.cast and land.cast, Nov 23): +// one segment, Land (PR, CI beside Review joined at Read, Merge), whose side +// routes send findings back to the session, run CI again when main moved, +// wait for a green main, or ask a person's card on Merge's exit 6. As a +// pushed row it has no `asks_if`: land.cast writes it on the card, and a row +// stores neither land.cast's source nor that attribute. LAND_REPO_FLOW is +// the same graph as Union's checkout reports it (repoFlows, parsed), which +// the Ship picker reads there: the card's gate carries it. // // Hand-written, so a flow rewritten in the library does not move what they show. // Pure and free of the `@/` alias: the phone's bundle imports the gallery. @@ -207,3 +215,131 @@ export const BRANCHING_FLOW: FixtureFlowRow = { { from: "revise", to: "check" }, ], }; + +// Land's stations as the parser names them inside the flow that uses it (land__), its card's decide segment +// one level further in (land__card__). +const inLand = (id: string, label: string, type: string, extra: Partial = {}) => node(`land__${id}`, label, type, extra); +// Land's stops, each routed by the composing flow to the session's fix for it, or to its own stop. +const LAND_STOPS: Array<[string, string]> = [ + ["changes", "Changes asked"], ["conflict", "Conflict"], ["revise", "Revise"], ["dropped", "Dropped"], ["unpushed", "No pull request"], + ["unread", "CI unread"], ["unreviewed", "No review"], ["rejected", "Rejected"], ["unmerged", "Not merged"], ["red_main", "Not rebased"], +]; + +export const LAND_FLOW: FixtureFlowRow = { + slug: "gallery-change-land", + name: "gallery-change-land", + label: "Change", + kind: "line", + source: `digraph change { + graph [kind="line", label="Change", takes="task,branch"] + land [flow="land"] + fix [label="Fix findings", backend=subject, max_visits=3] + fix_conflict [label="Resolve conflict", backend=subject, max_visits=3] + revise [label="Revise", backend=subject, max_visits=3] + stopped [shape=Msquare, label="Not landed", stop="$stop_reason"] +}`, + nodes: [ + node("start", "start", "start"), + node("fix", "Fix findings", "agent"), + node("fix_conflict", "Resolve conflict", "agent"), + node("revise", "Revise", "agent"), + node("exit", "Merged", "exit"), + node("stopped", "Not landed", "exit"), + inLand("pr", "PR", "command", { timeout: 600 }), + inLand("checks", "CI and review", "parallel_fanout"), + inLand("ci", "CI", "command", { timeout: 3_600 }), + inLand("review", "Review", "agent", { timeout: 5_400 }), + inLand("read", "Read", "parallel_fanin"), + inLand("ci_alone", "CI", "command", { timeout: 3_600 }), + inLand("brief", "Brief", "command", { timeout: 300 }), + inLand("merge", "Merge", "command", { timeout: 1_800 }), + inLand("retest", "CI again, main moved", "command", { timeout: 3_600 }), + inLand("wait_main", "Wait for green main", "command", { timeout: 90_000 }), + inLand("why_card", "Why a person", "command", { timeout: 120 }), + inLand("approved", "Person said Ship", "command", { timeout: 60 }), + inLand("landed", "Merged", "command"), + inLand("conflicted", "Does not fit main", "command", { timeout: 60 }), + ...LAND_STOPS.map(([id, label]) => inLand(id, label, "command")), + inLand("card__decide", "Decide", "human"), + inLand("card__ship", "Ship", "command"), + inLand("card__revise", "Revise", "command"), + inLand("card__dropped", "Dropped", "command"), + inLand("card", "Decide", "conditional"), + node("land", "Land", "conditional"), + ], + edges: [ + { from: "start", to: "land" }, + { from: "fix", to: "land" }, + { from: "fix_conflict", to: "land" }, + { from: "revise", to: "land" }, + { from: "land__landed", to: "exit", condition: "outcome = success" }, + ...LAND_STOPS.flatMap(([id]) => [ + { from: `land__${id}`, to: "fix", label: "changes asked", condition: `outcome = failure and land__${id}.json.exit = changes` }, + { from: `land__${id}`, to: "fix_conflict", label: "conflict", condition: `outcome = failure and land__${id}.json.exit = conflict` }, + { from: `land__${id}`, to: "revise", label: "revise", condition: `outcome = failure and land__${id}.json.exit = revise` }, + { from: `land__${id}`, to: "stopped", condition: "outcome = failure" }, + ]), + { from: "land", to: "land__pr" }, + { from: "land__pr", to: "land__checks", condition: `outcome = success and "on" != "off"` }, + { from: "land__pr", to: "land__ci_alone", label: "review off", condition: `outcome = success and "on" = "off"` }, + { from: "land__pr", to: "land__unpushed" }, + { from: "land__checks", to: "land__ci" }, + { from: "land__checks", to: "land__review" }, + { from: "land__ci", to: "land__read" }, + { from: "land__review", to: "land__read" }, + { from: "land__read", to: "land__unread", label: "CI unread", condition: "land__ci.json.error" }, + { from: "land__read", to: "land__unreviewed", label: "no verdict", condition: "land__review.json.verdict != ship and land__review.json.verdict != changes and land__review.json.verdict != rejected" }, + { from: "land__read", to: "land__rejected", label: "rejected", condition: "land__review.json.verdict = rejected" }, + { from: "land__read", to: "land__brief", label: "findings", condition: "land__review.json.verdict = changes or (land__ci.json.green != true and land__ci.json.blocked_by_main != true)" }, + { from: "land__read", to: "land__wait_main", label: "main is red", condition: "land__ci.json.blocked_by_main = true" }, + { from: "land__read", to: "land__merge", label: "green, approved", condition: "land__ci.json.green = true" }, + { from: "land__read", to: "land__unreviewed" }, + { from: "land__ci_alone", to: "land__unread", label: "CI unread", condition: "land__ci_alone.json.error" }, + { from: "land__ci_alone", to: "land__wait_main", label: "main is red", condition: "land__ci_alone.json.blocked_by_main = true" }, + { from: "land__ci_alone", to: "land__merge", label: "green", condition: "land__ci_alone.json.green = true" }, + { from: "land__ci_alone", to: "land__brief" }, + { from: "land__brief", to: "land__merge", label: "nothing to fix", condition: "land__brief.exit_code = 10" }, + { from: "land__brief", to: "land__changes" }, + { from: "land__why_card", to: "land__card" }, + { from: "land__approved", to: "land__merge" }, + { from: "land__merge", to: "land__landed", condition: "outcome = success" }, + { from: "land__merge", to: "land__retest", label: "main moved", condition: "land__merge.exit_code = 3" }, + { from: "land__merge", to: "land__conflicted", label: "conflict", condition: "land__merge.exit_code = 4" }, + { from: "land__merge", to: "land__pr", label: "head moved", condition: "land__merge.exit_code = 5" }, + { from: "land__merge", to: "land__why_card", label: "edits what judges it", condition: "land__merge.exit_code = 6" }, + { from: "land__merge", to: "land__unmerged" }, + { from: "land__retest", to: "land__unread", label: "CI unread", condition: "land__retest.json.error" }, + { from: "land__retest", to: "land__wait_main", label: "main is red", condition: "land__retest.json.blocked_by_main = true" }, + { from: "land__retest", to: "land__merge", label: "green", condition: "land__retest.json.green = true" }, + { from: "land__retest", to: "land__brief" }, + { from: "land__wait_main", to: "land__retest", condition: "outcome = success" }, + { from: "land__wait_main", to: "land__conflicted", label: "conflict", condition: "land__wait_main.exit_code = 4" }, + { from: "land__conflicted", to: "land__conflict" }, + { from: "land__wait_main", to: "land__red_main" }, + { from: "land__card__ship", to: "land__approved" }, + { from: "land__card__revise", to: "land__revise", label: "revise", condition: "outcome = failure and land__card__revise.json.exit = revise" }, + { from: "land__card__revise", to: "land__dropped", label: "dropped", condition: "outcome = failure and land__card__revise.json.exit = dropped" }, + { from: "land__card__dropped", to: "land__revise", label: "revise", condition: "outcome = failure and land__card__dropped.json.exit = revise" }, + { from: "land__card__dropped", to: "land__dropped", label: "dropped", condition: "outcome = failure and land__card__dropped.json.exit = dropped" }, + { from: "land__card", to: "land__card__decide" }, + { from: "land__card__decide", to: "land__card__ship", label: "[S] Ship :: Lands it on the main branch" }, + { from: "land__card__decide", to: "land__card__revise", label: "[R] Revise :: Your note goes to the session that made it; the change comes back through review" }, + { from: "land__card__decide", to: "land__card__dropped", label: "[D] Drop :: Closes it unlanded; the session hears your reason" }, + ], +}; + +/** What makes Union's Land ask a person: the `asks_if` on its card (land.cast). */ +export const LAND_ASKS = "it edits CI or the flow, or touches consent, bulk sends or bulk changes to people's records"; + +/** LAND_FLOW as Union's checkout reports it (cli repoFlowsReport, parsed): the session's fix stations its own, Land's + * steps marked as the segment's, and the card's gate holding the `asks_if` the parser copies onto it. */ +export const LAND_REPO_FLOW = { + slug: "change", name: "change", kind: "line" as const, label: "Change", description: null, takes: ["task", "branch"], + nodes: LAND_FLOW.nodes.map((n) => ({ + ...n, + ...(["fix", "fix_conflict", "revise"].includes(n.id) ? { backend: "subject", max_visits: 3 } : {}), + ...(n.id === "land" ? { segment: "land", segment_entry: true, segment_flow: "land" } : n.id.startsWith("land__") ? { segment: "land" } : {}), + ...(n.id === "land__card__decide" ? { asks_if: LAND_ASKS } : {}), + })), + edges: LAND_FLOW.edges, +}; diff --git a/packages/web/lib/ship/segmentInside.ts b/packages/web/lib/ship/segmentInside.ts new file mode 100644 index 0000000000..b559579b03 --- /dev/null +++ b/packages/web/lib/ship/segmentInside.ts @@ -0,0 +1,173 @@ +// A segment stage's inside (docs/architecture/flows.md FL4): its own steps read as a flow of their own, the stages a +// passing run takes through them, and every route off those stages, each to where it goes back to. The journey +// (journey.ts) plans the stages and says who acts at a step; it hands those readers in, so this file holds only the +// walk. Pure, with relative imports only, as journey.ts is. +import { edgeWhen, passScore, segmentTopOf, SEGMENT_SEP, type FlowEdgeIn, type FlowNodeIn } from "@codecast/shared/contracts/flowPool"; +import type { JourneyStage, StageState, StageWho } from "./journey"; + +/** A segment stage's inside, read from its graph: the stages a passing run takes through it (a fan-out holding its + * branches), each route off them, and the end the passing path reaches. */ +export type StageInside = { path: JourneyStage[]; routes: InsideRoute[]; end: string | null }; + +/** + * A way a segment turns off its passing path: the path step it leaves (`from`), its edge's label, the steps it runs, and + * where it ends: back on the path at a step, back to the session, or stopped. `asks`: a person answers on it, `when` what + * makes a run ask (asks_if). + */ +export type InsideRoute = { + from: string; + label: string | null; + steps: Array<{ id: string; label: string; who: StageWho; state: StageState }>; + to: { kind: "step"; id: string; label: string } | { kind: "session" } | { kind: "stop" }; + asks: { when: string | null } | null; + state: StageState; +}; + +/** A route before a run: no states yet. */ +export type RouteBase = Omit & { steps: Array<{ id: string; label: string; who: StageWho }> }; + +type Graph = { nodes: ReadonlyArray; edges: ReadonlyArray }; +/** What the walk needs of a stage the journey planned. */ +type Planned = { id: string; label: string; members: string[]; tail?: string[]; branches?: Planned[] }; +/** The journey's own readers: its stages of a graph (a segment's own, whose segments read as one step each), who acts + * at a step, and the steps a passing run takes through one. */ +export type InsideReaders = { + plan: (g: Graph) => B[]; + who: (g: Graph, ids: string[]) => StageWho; + passing: (g: Graph, id: string) => FlowNodeIn[]; +}; + +/** An edge whose condition compares two words the parser already wrote in (a segment's param): never taken when false. */ +const deadEdge = (e: FlowEdgeIn) => + !/\bor\b/.test(e.condition ?? "") && [...(e.condition ?? "").matchAll(/"([^"]*)"\s*(!=|=)\s*"([^"]*)"/g)].some((m) => (m[1] === m[3]) === (m[2] === "!=")); + +/** How a side route goes on from a step: by its condition alone (every route out is labelled), the passing edge first, + * then the step's default (no condition) before one that waits on a particular exit. */ +const routeRank = (e: FlowEdgeIn) => passScore({ condition: e.condition, label: /^\[\w+\]/.test(e.label ?? "") ? e.label : undefined }) * 2 + (e.condition ? 0 : 1); + +/** What makes a run ask at a person's step: its own `asks_if`, else that of the segment holding it, out to the flow's. */ +export function asksIfOf(graph: Graph, id: string): string | null { + const parts = id.split(SEGMENT_SEP); + for (let i = parts.length; i > 0; i--) { + const said = graph.nodes.find((n) => n.id === parts.slice(0, i).join(SEGMENT_SEP))?.asks_if; + if (said) return said; + } + return null; +} + +/** A segment's entry, as the start of its steps read as a flow of their own. */ +const ENTRY = "^"; + +/** + * A segment's inside, read from the graph: its steps as a flow of their own (its entry the start, a step with no way on + * inside it an end), the stages a passing run takes through them, and every route off those stages that goes through a + * step before it comes back to one, goes back to the session (an end the composing flow sends to a `backend=subject` + * station) or stops. Undefined for a station that is no segment, or one whose inside is itself (one step, no route). + */ +export function insideOf(graph: Graph, id: string, read: InsideReaders): { path: B[]; routes: RouteBase[]; end: string | null } | undefined { + const pre = `${id}${SEGMENT_SEP}`; + const own = graph.nodes.filter((n) => n.id.startsWith(pre)); + if (!own.length) return undefined; + const sub = (x: string) => (x === id ? ENTRY : x.slice(pre.length)); + const full = (x: string) => `${pre}${x}`; + const edges = graph.edges.filter((e) => (e.from === id || e.from.startsWith(pre)) && e.to.startsWith(pre) && !deadEdge(e)).map((e) => ({ ...e, from: sub(e.from), to: sub(e.to) })); + const nodes: FlowNodeIn[] = [{ id: ENTRY, label: "start", type: "start" }, ...own.map((n) => { + const s = sub(n.id); + // Its steps stand as a flow's own: the segment they belonged to is the flow now. + return { ...n, id: s, segment: undefined, segment_flow: undefined, segment_entry: own.some((x) => x.id.startsWith(`${n.id}${SEGMENT_SEP}`)), ...(n.type === "exit" || !edges.some((e) => e.from === s) ? { type: "exit" } : {}) }; + })]; + const g: Graph = { nodes, edges }; + const path = read.plan(g); + const byId = new Map(nodes.map((n) => [n.id, n])); + const ended = (x: string) => byId.get(x)?.type === "exit"; + const stageAt = new Map(); + path.forEach((s, i) => s.members.forEach((m) => stageAt.set(m, i))); + const outOf = (x: string) => edges.filter((e) => segmentTopOf(e.from) === x && segmentTopOf(e.to) !== x).sort((a, b) => routeRank(b) - routeRank(a)); + const routes: RouteBase[] = []; + for (const e of edges) { + const from = stageAt.get(segmentTopOf(e.from)); + const first = segmentTopOf(e.to); + const back = stageAt.get(first); + // Only a turn off the path: never along it, never straight into an end. + if (from === undefined || ended(first) || (back !== undefined && back >= from)) continue; + const steps: string[] = []; + let to: InsideRoute["to"] = { kind: "stop" }; + for (let cur: string | undefined = first; cur && !steps.includes(cur); cur = outOf(cur).map((x) => segmentTopOf(x.to))[0]) { + const on = stageAt.get(cur); + if (on !== undefined) { to = { kind: "step", id: full(path[on].id), label: path[on].label }; break; } + if (ended(cur)) { + const end = full(cur); + if (graph.edges.some((x) => x.from === end && graph.nodes.find((n) => n.id === x.to)?.backend === "subject")) to = { kind: "session" }; + break; + } + steps.push(cur); + } + const label = e.label ? edgeWhen(e) : null; + const fromId = full(path[from].id); + if (routes.some((r) => r.from === fromId && r.label === label && r.steps[0]?.id === (steps[0] ? full(steps[0]) : undefined))) continue; + const person = steps.find((s) => read.who(g, [s]) === "person"); + const gate = person ? read.passing(g, person).find((n) => n.type === "human") : undefined; + routes.push({ + from: fromId, + label, + steps: steps.map((s) => ({ id: full(s), label: byId.get(s)?.label ?? s, who: read.who(g, [s]) })), + to, + asks: person ? { when: gate ? asksIfOf(graph, full(gate.id)) : null } : null, + }); + } + if (path.length < 2 && !routes.length) return undefined; + // The end the passing path reaches from its last stage. + const last = path[path.length - 1]; + const endId = edges.filter((e) => last?.members.includes(e.from) && ended(e.to)).sort((a, b) => passScore(b) - passScore(a))[0]?.to; + const lift = (b: Planned): Planned => ({ ...b, id: full(b.id), members: b.members.map(full), ...(b.tail ? { tail: b.tail.map(full) } : {}), ...(b.branches ? { branches: b.branches.map(lift) } : {}) }); + return { path: path.map((b) => lift(b) as B), routes, end: endId ? byId.get(endId)?.label ?? null : null }; +} + +/** Where a run stands, as a segment's inside reads it: its steps' visits (one per node, its latest), the step it stands + * at (`here`: the card's when a gate holds it, else the current step while live), whether that is a gate, whether the + * stage sent the work back, whether the stage is after where the run stands, and who answers the gate. */ +export type InsideRun = { + statuses: ReadonlyArray<{ node_id: string; status: string; started_at?: number }>; + here: string | null; gate: boolean; paused: boolean; live: boolean; later: boolean; back: boolean; gateWho: StageWho; +}; + +const inGroup = (id: string, nodeId: string) => nodeId === id || nodeId.startsWith(`${id}${SEGMENT_SEP}`); +const newest = (list: T[]) => list.reduce((best, n) => (!best || (n.started_at ?? 0) >= (best.started_at ?? 0) ? n : best), undefined); + +/** + * A segment's inside on a run, this round only (from the newest entry into its first step): each step as its visit this + * round left it (the card a gate holds waits, the step the run stands at is current), nothing after where the run + * stands, a route waiting or current with its step, and the route that last went back to the session, while the stage + * has sent the work back, back. + */ +export function insideOnRun(inside: { path: B[]; routes: RouteBase[]; end: string | null }, run: InsideRun, idle: (b: B) => JourneyStage): StageInside { + const since = newest(run.statuses.filter((n) => inside.path[0]?.members.some((m) => inGroup(m, n.node_id))))?.started_at ?? 0; + const round = run.statuses.filter((n) => (n.started_at ?? 0) >= since); + const on = (ids: string[]) => !!run.here && ids.some((id) => inGroup(id, run.here!)); + const cut = inside.path.findIndex((p) => on(p.members) || inside.routes.some((r) => r.from === p.id && on(r.steps.map((s) => s.id)))); + const stepState = (ids: string[], i: number): StageState => { + if (run.later || (cut >= 0 && i > cut)) return "idle"; + if (on(ids)) return run.gate || run.paused ? "waiting" : "active"; + const last = newest(round.filter((n) => ids.some((id) => inGroup(id, n.node_id)))); + if (!last) return "idle"; + if (last.status === "running" || last.status === "pending") return run.live ? "active" : "idle"; + return last.status === "failed" ? "routed" : "done"; + }; + const pathOn = (i: number) => (p: B): JourneyStage => ({ ...idle(p), state: stepState(p.members, i), ...(p.branches ? { branches: (p.branches as B[]).map(pathOn(i)) } : {}) }); + const fromAt = (r: RouteBase) => inside.path.findIndex((p) => p.id === r.from); + const visited = (r: RouteBase) => Math.max(0, ...round.filter((n) => r.steps.some((s) => inGroup(s.id, n.node_id))).map((n) => n.started_at ?? 0)); + const back = run.back ? inside.routes.filter((r) => r.to.kind === "session" && visited(r) > 0).sort((x, y) => visited(y) - visited(x))[0] : undefined; + return { + ...inside, + path: inside.path.map((p, i) => pathOn(i)(p)), + routes: inside.routes.map((r) => { + const steps = r.steps.map((s) => ({ ...s, state: stepState([s.id], fromAt(r)), who: run.gate && on([s.id]) ? run.gateWho : s.who })); + const has = (s: StageState) => steps.some((x) => x.state === s); + const state: StageState = has("waiting") ? "waiting" : has("active") ? "active" : r === back ? "back" : steps.length && steps.every((x) => x.state !== "idle") ? "done" : "idle"; + return { ...r, steps, state }; + }), + }; +} + +/** A segment's passing path in a few words: "PR · CI + Review · Merge". */ +export const insideWords = (inside: Pick) => inside.path.map((s) => (s.branches ? s.branches.map((b) => b.label).join(" + ") : s.label)).join(" · ");