From 5446d097d9ecbe852addecd45222c36509599480 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 04:46:54 +0000 Subject: [PATCH 01/19] test(goals): closure check for the Shift Manager epic (FIX-1663) Adds goals/shift-manager/a-lab-is-worked-through-one-skinned-shell: legs a, b0, b and c over DevForce and the pentest Lab, the six controls, journeys J3 and J4, every child's check (part 3) and the gap sweep (part 4), with its verdict log from a run on c29aafa4f. The run has findings, recorded in the verdict log; none is fixed here. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../goal.md | 43 + .../legs.mts | 765 ++++++++++++++++++ .../parts.mts | 422 ++++++++++ .../run.mts | 574 +++++++++++++ .../shell.mts | 456 +++++++++++ 5 files changed, 2260 insertions(+) create mode 100644 goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md create mode 100644 goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts create mode 100644 goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts create mode 100644 goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts create mode 100644 goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md new file mode 100644 index 0000000000..06a89957c8 --- /dev/null +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -0,0 +1,43 @@ +# shift-manager › a lab is worked through one skinned shell + +**Issue:** FIX-1663 (the closure of FIX-1649) + +**Outcome:** On one `main` commit with every child merged, a person works the DevForce Lab through Shift Manager in a real browser. They answer an ask from Inbox, follow the task it started to its session and trace, reach every surface the shell promises, and talk to the coder seat while its task runs. The pentest Lab opens in the same shell from its README alone, with no shell code of its own, under the org its store names. With no Shift Manager theme loaded, no reused FSD component carries a Shift Manager value, in light or dark. Someone reusing FSD UI in their own app and a sibling epic's owner each get what the epic promised them, and every child's own check passes on the same commit. + +**Input:** `goals/devforce-lab/lab/`, opened as Shift Manager's DevTeam profile (`--team devteam`) on the real harness (`DEVFORCE_LAB_HARNESS=claude-code`) for leg a, and on the lab's scripted harness for leg c. `goals/pentest-lab/lab/` through its committed `fsdev.config.mts` for leg b, a tree Shift Manager was never tested against. Kitchen-sink's tree stands in for neither. Every seat, team, channel and board name is read from the trees at run time. + +**Signal:** each failure is tagged with its leg or part. + +- **a1, the Inbox journey.** The EM seat's ask is in Inbox with its kind and workstream. The detail pane's card says what the workstream's stream card says. Approve leaves the resume stored and the ask gone from Inbox. +- **a2, the task journey.** From Tasks, then from the workstream's Board: the task's Session tab draws only items the run session holds, the inspector's trace link is the in-process devtool's `?session=`, and following it opens that session. +- **a3, reach.** Chief of Staff, the org switcher, Jump to, Inbox against the store's asks, Tasks in its three groupings, Roster for all teams and for each team row in TEAMS, PROJECTS, the Day/Night switch, the project level's four tabs, each workstream's four tabs, panel and Board against the store's rows, and the task frame's four tabs and panel slot. Every empty one names what will be there. +- **a4, the `@worker` turn** (the one step on the real model). While the coder's task runs, `@coder ` in the workstream composer is in the running task session as a person's turn before the composer reads delivered, and the next attempt answers in that session. Never retried. +- **b0, the pentest config from the README.** An isolated writer that sees only Shift Manager's README and the pentest tree (minus its config) writes a config to scratch. Every step it had to guess is a failure, and so is a semantic difference from the committed config (flows, org, seats, workstreams, the page's user and bearer), booted side by side. +- **b, the pentest Lab.** The a3 reach on the pentest tree; the composer's post is in the channel's stored transcript when it is drawn, and drawn once after a reload; `labs/shift-manager` is unchanged and names no pentest seat, team or channel. A Lab with no resolver opens under `DEFAULT_ORG_ID`, and on both Labs the switcher names the store's org. +- **c, the theme fence.** On a build with only the theme import removed, `--shift day` then `--shift night`: the computed colour, background, border and font of every message, reasoning, tool, code block and ask card, and of the devtool page the trace link opens, match no value the Shift Manager theme declares. Each part renders at least once per pass. FIX-1655's static check over `packages/**` finds none. +- **J3.** In a fresh host, `fsdev ui add tool approval` from the commit's registry gives byte-identical copies; with the docs' token block applied as written, changing `--success` repaints both. +- **J4.** Every surface in the epic's ownership table opens by its address on a fresh load and shows rows or its named empty state; none blank, none refused. +- **Part 3.** Every child's goal check with its controls, the goal labs the set touched, the design-system and registry tests, `pnpm typecheck` and `pnpm test`. +- **Part 4.** No literal colour in Shift Manager's source; the pinned routes; Shift Manager's only session writes; one ask card; the layer fence; the final visuals after the hand-back; the docs smoke. + +**Anti-game:** a hollow pass would be a shell that draws its own rows, a no-theme build that removed more than the theme, or a control that never reaches the code it names. So no assertion reads Shift Manager's own state or a child's output: rows are compared by id with the store, read through the Lab's HTTP routes with the bearer the page was handed. Every scratch patch is printed in full. Each control must fail at its own signal and leave the rest green, or the run says WRONG. + +**Model:** leg a's harness is Claude Code, through `AI_GATEWAY_API_KEY` or `ANTHROPIC_API_KEY`; only a4's answer rests on it. b0's writer is the `claude` CLI. Legs b and c and both journeys are model-free. + +**Run:** `PLAYWRIGHT_BROWSERS_PATH=/opt/pw-browsers pnpm tsx goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts`. `GOAL_PART=a,b0,b,c,controls,part2,part3,part4` (the default) picks the parts. For a rerun, `GOAL_CONTROLS` picks the controls, `GOAL_CONTROL_LEGS` the legs a control runs, and `GOAL_CHILDREN` (a regex on the label) part 3's entries. + +**Controls:** each runs legs a, b and c on its own build or server start. + +- **today's main** (the commit before Shift Manager's first merge): Shift Manager is absent, so a and b must fail; c's static half over that commit's `packages/` stays green. +- **hardcoded-accent** (scratch patch on the tool card's copy): must fail c at the tool card. +- **static-names** (FIX-1662's swap): must fail b at TEAMS, naming a pentest seat. Jump to's Workers, drawn from the same seat list, may go red with it. +- **optimistic-post** (FIX-1662's swap): must fail a4 and b's post step together. +- **worker-session** (FIX-1664's swap): must fail a2. Leg c's sweep of the run-lab's Session may go red with it, since the control points that Session elsewhere. +- **no-org** (scratch patch, the org switcher given no org): must fail b at the org step. + +## Verdict log +| Date | Commit | Model | Verdict | Notes | +|------|--------|-------|---------|-------| +| 2026-10-02 | c29aafa4f | Claude Code harness (a4), `claude` CLI (b0) | FAIL (findings) | **Legs:** a PASS (a1 the EM's ask approved from Inbox, resume stored; a4 `@coder` delivered and held when drawn, the next attempt answered in the run session; a2 18 items drawn, all stored, trace followed from Tasks and Board; a3 every surface). b PASS (3 seats in teams audit and pentest, post held when drawn and once after a reload, `labs/shift-manager` unchanged, org_pentest_lab; no-resolver Lab under `__fsd_default_org__`). c PASS (day and night: message 20, reasoning 16, tool 51, code block 32, ask 12, devtool 155 elements, 0 theme values; static fence 0 hits in 2419 files). **b0 FAIL:** the writer's config boots the same flows, org, seats, workstream and user as the committed one, but it had to guess 3 steps (which store, whether `host.mts`'s options do the inventory and devtool steps, whether a Lab needs a chief-of-staff seat). **J3, J4 PASS.** **Part 4 FAIL:** `labs/shift-manager/src/styles.css` defines the registry's default tokens as `hsl()` literals. | +| 2026-10-02 | c29aafa4f | as above | controls | today's main (d8f6a10e7) FAIL as expected, c's static half green. hardcoded-accent FAIL at c:tool only (`#e8f551` on the tool card's icon, day and night). no-org FAIL at b:org only. **WRONG:** static-names fails b:teams but also a4 (its written-in seats carry no door, so "eng.coder takes no message."); optimistic-post fails b:post but a4 stays green (it swaps the channel post, and `@worker` goes through the seat's door); worker-session stays green at a2 (DevForce's coder holds no other session on its flow, so the near-miss reads the run session). | +| 2026-10-02 | c29aafa4f | real model where each child names one | PASS (part 3) | Every child check PASS and every child control FAIL at its named signal: design-system (hardcoded-accent), it-opens-a-lab (static-names, optimistic-post, unanswerable-asks), it-shows-and-stops-a-task-run (worker-session, optimistic-interrupt, board-flow), it-takes-its-look-from-the-design-system (hardcoded-accent, switch-ignored), it-sends-a-turn-into-a-seat-session (optimistic-turn, fresh-session), it-briefs-and-talks-with-the-chief-of-staff (optimistic-reply, static-brief), it-shows-who-is-on-shift (ignore-asks, count-queued), it-hands-a-run-the-work-it-approved (drop-task), the two D1 children (no-gate, kind-ledger), devforce-lab ×3, pentest-lab ×2, multi-seat-collab. Design-system, registry and static tests, `pnpm typecheck` and `pnpm test` PASS. | diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts new file mode 100644 index 0000000000..5e2cdd0469 --- /dev/null +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts @@ -0,0 +1,765 @@ +/** + * The closure's legs: a (DevForce, a real model on a4), b (pentest, keyless, + * plus the org step), and c (no theme, light and dark). Each leg reports its + * failures by signal (`a1`, `b:teams`, `c:tool` …) so the driver can grade a + * control by which signals it reddened, and which it left green. + * + * Every row on the page is compared by id with what the running Lab's store + * returns through its shipped routes, read with this script's own requests. + * Nothing here reads Shift Manager's own state. + */ +import { execFileSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join, relative } from "node:path"; +import type { Browser, Page } from "playwright"; +import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; +import { hex, near, parseColour, readShiftManagerTheme, type Rgb } from "../../lib/colour.mts"; +import { REPO_ROOT } from "../../lib/index.mts"; +import { findThemeValues, themeValues } from "../../../labs/design-system/test/theme.ts"; +import { + SHIFT_MANAGER, + attr, + diff, + injected, + labApi, + open, + readPainted, + readStore, + readTree, + resumed, + same, + sendAndWatch, + settled, + sleep, + startShiftManager, + visible, + type LabApi, + type PageRead, + type Running, + type Sample, + type Store, + type StoredRow, + type Tree, +} from "./shell.mts"; + +/** The trees the epic pins, and the Labs each leg opens. */ +export const TREES = { + devforce: join(REPO_ROOT, "goals", "devforce-lab", "lab", "workforce"), + pentest: join(REPO_ROOT, "goals", "pentest-lab", "lab", "workforce"), + runLab: join(REPO_ROOT, "goals", "shift-manager", "it-shows-and-stops-a-task-run", "lab", "workforce"), +}; +export const PENTEST_CONFIG = join(REPO_ROOT, "goals", "pentest-lab", "lab", "fsdev.config.mts"); +const RUN_LAB_CONFIG = join(REPO_ROOT, "goals", "shift-manager", "it-shows-and-stops-a-task-run", "lab", "fsdev.config.mts"); +const ASK_LAB_CONFIG = join(SHIFT_MANAGER, "test", "fixtures", "ask-lab", "fsdev.config.mts"); + +/** The model keys a keyless leg must not carry. */ +const MODEL_KEYS = ["AI_GATEWAY_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "ANTHROPIC_API_KEY"]; +const KEYLESS = Object.fromEntries(MODEL_KEYS.map((k) => [k, ""])); + +/** Where a leg reports to. `signal` is what a control is graded against. */ +export type Report = { fail: (signal: string, why: string) => void; note: (line: string) => void }; +/** What every leg is handed. */ +export type LegCtx = { scratch: string; pages: string; browser: Browser; report: Report }; + +const token = (what: string) => `${what}-${randomBytes(4).toString("hex")}`; + +async function newPage(browser: Browser): Promise<{ page: Page; errors: string[] }> { + const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); + const errors: string[] = []; + page.on("pageerror", (e) => errors.push(e.message)); + page.setDefaultTimeout(15_000); + // tsx compiles with esbuild's keepNames, which wraps nested functions in an + // in-page function with a `__name` helper the page lacks. + await page.addInitScript("globalThis.__name = (fn) => fn;"); + return { page, errors }; +} + +const tabSelected = (page: Page, tab: string) => page.locator(`[role=tab][data-tab=${tab}][aria-selected=true]`).waitFor({ timeout: 10_000 }).then( + () => true, + () => false, +); + +/** The documents under a tree's `resources/` folders that let a browser read them. */ +function readableDocuments(root: string): string[] { + const out: string[] = []; + const walk = (dir: string) => { + for (const entry of readdirSync(dir)) { + const full = join(dir, entry); + if (statSync(full).isDirectory()) walk(full); + else if (full.endsWith(".md") && /[/\\]resources[/\\]/.test(full)) { + const front = /^---\n([\s\S]*?)\n---/.exec(readFileSync(full, "utf8"))?.[1] ?? ""; + if (/client:\s*\n\s+content:\s*\n\s+read:\s*true/.test(front)) out.push(relative(root, full)); + } + } + }; + walk(root); + return out; +} + +// ---- a3 / b's reach: every surface, by clicking from the first screen --------- + +/** + * Walk every surface ER-1 names, by clicking from the first screen, and grade + * each against the store. `reach` failures go to `signals.reach`, seat-list + * failures to `signals.teams`. Returns what the org switcher names. + */ +export async function walkSurfaces( + page: Page, + origin: string, + store: Store, + tree: Tree, + signals: { reach: string; teams: string }, + report: Report, + options: { taskLevel: boolean } = { taskLevel: true }, +): Promise<{ orgShown: string }> { + const reach = (why: string) => report.fail(signals.reach, why); + const teams = (why: string) => report.fail(signals.teams, why); + const rows = Object.values(store.rows).flat(); + + // The first screen. + await open(page, origin, "/"); + if (!(await visible(page, "cos"))) reach("the first screen is not Chief of Staff"); + if ((await page.getByTestId("nav-cos").getAttribute("aria-current")) !== "page") reach("Chief of Staff's sidebar entry is not current on the first screen"); + if (!(await visible(page, "cos-summary"))) reach("Chief of Staff draws no shift summary"); + if (!(await visible(page, "cos-panel"))) reach("Chief of Staff has no right panel"); + + // The org switcher: it names an org, and opens. + const switcher = page.getByTestId("org-switcher"); + const orgShown = ((await switcher.locator("span.truncate").first().textContent().catch(() => null)) ?? "").trim(); + await switcher.locator("button[aria-haspopup=menu]").click(); + if (!(await page.locator("[data-testid=org-switcher] [role=menu]").isVisible().catch(() => false))) reach("the org switcher does not open"); + await switcher.locator("button[aria-haspopup=menu]").click(); + + // Jump to: a workstream, a worker, a task and a declared document. + const docs = readableDocuments(tree.root); + const targets: Array<{ group: string; query: string; lands: string }> = [ + { group: "Workstreams", query: tree.channels[0]!.id, lands: `[data-testid=workstream][data-channel-id="${tree.channels[0]!.id}"]` }, + { group: "Workers", query: store.seats[0] ?? "", lands: "[data-testid=roster]" }, + ...(rows[0] === undefined ? [] : [{ group: "Tasks", query: rows[0].title.slice(0, 24), lands: `[data-testid=task-frame][data-task-id="${rows[0].id}"]` }]), + ...(docs[0] === undefined ? [] : [{ group: "Resources", query: docs[0].split(/[/\\]/).at(-1)!.replace(/\.md$/, ""), lands: "[data-testid=resource]" }]), + ]; + for (const target of targets) { + await page.getByTestId("jump-to").click(); + await page.getByTestId("jump-input").fill(target.query); + const hit = page.locator(`[data-testid=jump-dialog] section[aria-label="${target.group}"] [data-testid=jump-result]`).first(); + if (!(await hit.waitFor({ timeout: 10_000 }).then(() => true, () => false))) { + reach(`Jump to finds no ${target.group} entry for "${target.query}"`); + await page.keyboard.press("Escape"); + continue; + } + await hit.click(); + if (!(await page.locator(target.lands).first().waitFor({ timeout: 10_000 }).then(() => true, () => false))) reach(`Jump to's ${target.group} entry "${target.query}" does not open its screen`); + } + if (docs.length === 0) report.note(`${tree.root}: no browser-readable document declared, so Jump to's Resources is not walked`); + + // Inbox. + await page.getByTestId("nav-inbox").click(); + if (!(await visible(page, "inbox"))) reach("Inbox does not open"); + const listed = await attr(page, "inbox-item", "data-suspension-id"); + if (store.asks.length === 0) { + if (!(await visible(page, "inbox-empty", 3_000))) reach("no ask is pending and Inbox's empty state is not named"); + } else if (!same(listed, store.asks.map((a) => a.suspensionId))) reach(`Inbox lists ${diff(store.asks.map((a) => a.suspensionId), listed)}`); + + // Tasks, in each grouping. + await page.getByTestId("nav-tasks").click(); + if (!(await visible(page, "tasks"))) reach("Tasks does not open"); + const open_ = rows.filter((r) => r.status !== "completed" && r.status !== "cancelled").map((r) => `${r.ref}/${r.id}`); + for (const grouping of ["state", "worker", "stream"]) { + await page.locator(`[role=tab][data-grouping=${grouping}]`).click(); + if (!(await page.locator(`[role=tab][data-grouping=${grouping}][aria-selected=true]`).waitFor({ timeout: 5_000 }).then(() => true, () => false))) reach(`Tasks' ${grouping} grouping is not selected`); + if (open_.length === 0) { + if (!(await visible(page, "tasks-empty", 3_000))) reach("no open row and Tasks' empty state is not named"); + continue; + } + const shown = (await page.getByTestId("task-row").evaluateAll((els) => els.map((e) => `${e.getAttribute("data-board-ref")}/${e.getAttribute("data-task-id")}`))) as string[]; + if (!same(shown, open_)) reach(`Tasks by ${grouping}: ${diff(open_, shown)}`); + } + + // Roster, all teams. + await page.getByTestId("nav-roster").click(); + if (!(await visible(page, "roster"))) reach("Roster does not open"); + else { + await page.getByTestId("roster-worker").first().waitFor({ timeout: 10_000 }).catch(() => undefined); + const all = await attr(page, "roster-worker", "data-seat-id"); + if (!same(all, store.seats)) teams(`Roster (all) lists ${diff(store.seats, all)}`); + } + + // TEAMS: one row per team, a square per seat, and each row opens Roster for it. + const teamRows = await attr(page, "team", "data-team"); + const wantTeams = [...new Set(store.seats.map((s) => (s.includes(".") ? s.split(".")[0]! : "Staff")))]; + if (!same(teamRows, wantTeams)) teams(`TEAMS rows: ${diff(wantTeams, teamRows)}`); + const squares = await attr(page, "worker", "data-seat-id"); + if (!same(squares, store.seats)) teams(`TEAMS squares: ${diff(store.seats, squares)}`); + for (const team of teamRows) { + const want = store.seats.filter((s) => (s.includes(".") ? s.split(".")[0] : "Staff") === team); + const under = (await page.locator(`[data-testid=team][data-team="${team}"] [data-testid=worker]`).evaluateAll((els) => els.map((e) => e.getAttribute("data-seat-id") ?? ""))) as string[]; + if (!same(under, want)) teams(`team ${team}'s squares: ${diff(want, under)}`); + await page.locator(`[data-testid=team][data-team="${team}"]`).click(); + if ((await page.locator(`[data-testid=team][data-team="${team}"]`).getAttribute("aria-current")) !== "page") reach(`team ${team}'s row is not current once opened`); + const title = (await page.getByTestId("roster-title").textContent().catch(() => "")) ?? ""; + if (!title.includes(team)) reach(`Roster opened from team ${team} is titled "${title}"`); + await sleep(300); + const filtered = await attr(page, "roster-worker", "data-seat-id"); + if (!same(filtered, want)) teams(`Roster for team ${team} lists ${diff(want, filtered)}`); + } + + // PROJECTS: the workstreams. + const streams = (await page.locator("[data-testid^=nav-workstream-]").evaluateAll((els) => els.map((e) => e.getAttribute("data-testid") ?? ""))).map((t) => + t.slice("nav-workstream-".length), + ); + if (!same(streams, store.channels.map((c) => c.id))) reach(`PROJECTS lists ${diff(store.channels.map((c) => c.id), streams)}`); + + // The Day / Night switch: there, and each half marks itself when clicked. + if (!(await visible(page, "shift-switch", 3_000))) reach("the Day / Night switch is not in the sidebar"); + else { + const day = (await page.getByTestId("shift-day").getAttribute("aria-pressed")) === "true"; + const other = day ? "shift-night" : "shift-day"; + const back = day ? "shift-day" : "shift-night"; + await page.getByTestId(other).click(); + if ((await page.getByTestId(other).getAttribute("aria-pressed")) !== "true") reach(`the switch does not mark ${other} once clicked`); + await page.getByTestId(back).click(); + if ((await page.getByTestId(back).getAttribute("aria-pressed")) !== "true") reach(`the switch does not mark ${back} once clicked back`); + } + + // The project level: four tabs, each its named empty state. + await page.getByTestId("projects-heading").click(); + for (const tab of ["stream", "board", "workstreams", "brief"]) { + await page.locator(`[role=tab][data-tab=${tab}]`).click(); + if (!(await tabSelected(page, tab))) reach(`the project's ${tab} tab is not selected`); + if (!(await visible(page, `project-${tab}-empty`))) reach(`the project's ${tab} tab shows no named empty state`); + } + + // Each workstream: four tabs, the right panel, the board, and the task level from a card. + for (const channel of tree.channels) { + await page.getByTestId(`nav-workstream-${channel.id}`).click(); + await page.locator(`[data-testid=workstream][data-channel-id="${channel.id}"]`).waitFor(); + if (!(await visible(page, "workstream-panel"))) reach(`${channel.id} has no right panel`); + const members = await attr(page, "panel-member", "data-seat-id"); + if (!same(members, channel.members)) reach(`${channel.id}'s panel team: ${diff(channel.members, members)}`); + if (!(await tabSelected(page, "stream"))) reach(`${channel.id} does not open on its Stream tab`); + if (!(await visible(page, "composer", 5_000))) reach(`${channel.id}'s Stream has no composer`); + + await page.locator("[role=tab][data-tab=board]").click(); + if (!(await tabSelected(page, "board"))) reach(`${channel.id}'s Board tab is not selected`); + const here = store.rows[channel.id] ?? []; + if (channel.boardRefs.length === 0) { + if (!(await visible(page, "board-none"))) reach(`${channel.id} attaches no board and its Board tab doesn't say so`); + } else if (!(await visible(page, "board"))) { + reach(`${channel.id}'s Board tab shows no board`); + } else { + const cards = (await page.getByTestId("board-card").evaluateAll((els) => els.map((e) => `${e.getAttribute("data-board-ref")}/${e.getAttribute("data-task-id")}`))) as string[]; + const want = here.map((r) => `${r.ref}/${r.id}`); + if (!same(cards, want)) reach(`${channel.id}'s Board: ${diff(want, cards)}`); + } + await page.locator("[role=tab][data-tab=brief]").click(); + if (!(await tabSelected(page, "brief"))) reach(`${channel.id}'s Brief tab is not selected`); + if (!(await visible(page, "brief", 5_000)) && !(await visible(page, "empty-state", 1_000))) reach(`${channel.id}'s Brief shows neither a charter nor a named empty state`); + await page.locator("[role=tab][data-tab=results]").click(); + if (!(await tabSelected(page, "results"))) reach(`${channel.id}'s Results tab is not selected`); + if (!(await visible(page, "empty-state"))) reach(`${channel.id}'s Results shows no named empty state`); + + const first = here[0]; + if (first !== undefined) { + await page.locator("[role=tab][data-tab=board]").click(); + await page.locator(`[data-testid=board-card][data-task-id="${first.id}"]`).click(); + await page.locator(`[data-testid=task-frame][data-task-id="${first.id}"]`).waitFor(); + if (!(await visible(page, "task-panel-slot"))) reach(`the task frame for ${first.id} has no right panel`); + for (const tab of ["session", "diff", "checks", "brief"]) { + await page.locator(`[role=tab][data-tab=${tab}]`).click(); + if (!(await tabSelected(page, tab))) reach(`the task frame's ${tab} tab is not selected`); + if (!(await visible(page, "task-slot"))) reach(`the task frame's ${tab} tab shows nothing`); + } + } + } + if (options.taskLevel && rows.length === 0) reach("no board holds a row, so the task level was never reached"); + return { orgShown }; +} + +// ---- leg a: DevForce, a real model on a4 -------------------------------------- + +/** How long the real harness may take to start a run once the ask is approved. */ +const RUN_STARTS_MS = 4 * 60_000; +/** a4's window for the seat's answer in its running task session. Never retried (QR-9). */ +const ANSWER_MS = 10 * 60_000; +/** How long a4 lets a running task's harness confirm its session before the turn goes in. */ +const A4_SETTLE_MS = 15_000; +/** How long a2 waits for the store to hold an item the Session drew while the run streamed it. */ +const STORED_BY_MS = 5 * 60_000; + +/** The DevForce Lab served as Shift Manager's DevTeam profile. */ +async function startDevTeam(ctx: LegCtx, label: string, harness: "claude-code" | "stub", shift?: "day" | "night"): Promise { + return startShiftManager(ctx.scratch, label, { + team: "devteam", + pages: ctx.pages, + shift, + env: harness === "stub" ? { ...KEYLESS, DEVFORCE_LAB_HARNESS: "stub" } : { DEVFORCE_LAB_HARNESS: "claude-code" }, + }); +} + +/** The first row on the store that is running and linked to its run. */ +async function runningRow(api: LabApi, tree: Tree, userId: string, withinMs: number): Promise { + for (const until = Date.now() + withinMs; Date.now() < until; await sleep(500)) { + const store = await readStore(api, tree, userId); + const row = Object.values(store.rows).flat().find((r) => r.status === "in_progress" && r.run !== null); + if (row !== undefined) return row; + } + return undefined; +} + +/** The Inbox journey: select the ask, see the stream's card, approve it. Returns the ask approved. */ +async function inboxJourney(page: Page, api: LabApi, store: Store, tree: Tree, signal: string, report: Report): Promise { + const fail = (why: string) => report.fail(signal, why); + const ask = store.asks[0]; + if (ask === undefined) { + fail("no ask is pending in the store, so there is nothing to answer"); + return false; + } + const workstream = tree.channels.find((c) => c.members.includes(ask.seat))?.id; + await page.getByTestId("nav-inbox").click(); + const item = page.locator(`[data-testid=inbox-item][data-suspension-id="${ask.suspensionId}"]`); + if (!(await item.waitFor({ timeout: 15_000 }).then(() => true, () => false))) { + fail(`Inbox does not list ${ask.suspensionId}, pending in the store`); + return false; + } + const kind = (await item.getByTestId("inbox-item-kind").textContent()) ?? ""; + const shownStream = (await item.getByTestId("inbox-item-workstream").textContent()) ?? ""; + if (kind.trim() === "") fail("the ask's Inbox item names no kind"); + if (workstream !== undefined && shownStream.trim() !== workstream) fail(`the ask's Inbox item names workstream "${shownStream}", the asking seat's is ${workstream}`); + await item.click(); + const detailCard = page.locator(`[data-testid=inbox-detail] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"]`); + if (!(await detailCard.waitFor({ timeout: 10_000 }).then(() => true, () => false))) { + fail("the detail pane draws no ask card for the selected ask"); + return false; + } + const detailText = ((await detailCard.textContent()) ?? "").trim(); + if (workstream !== undefined) { + await page.getByTestId(`nav-workstream-${workstream}`).click(); + const streamCard = page.locator(`[data-testid=stream-asks] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"]`); + if (!(await streamCard.waitFor({ timeout: 10_000 }).then(() => true, () => false))) fail(`${workstream}'s stream shows no card for the ask`); + else if (((await streamCard.textContent()) ?? "").trim() !== detailText) fail("the detail pane's card and the stream's card differ"); + await page.getByTestId("nav-inbox").click(); + await item.click(); + } + await page.locator("[data-testid=inbox-detail]").getByRole("button", { name: "Approve" }).click(); + let gone = false; + let stored = false; + for (const until = Date.now() + 30_000; Date.now() < until && !(gone && stored); await sleep(250)) { + gone = (await item.count()) === 0; + stored = await resumed(api, ask.sessionId, ask.suspensionId); + } + if (!stored) fail(`after Approve the seat's session ${ask.sessionId} holds no resume for ${ask.suspensionId}`); + if (!gone) fail("after Approve the ask is still listed in Inbox"); + if (workstream !== undefined) { + await page.getByTestId(`nav-workstream-${workstream}`).click(); + await page.getByTestId("stream-asks").waitFor({ timeout: 10_000 }).catch(() => undefined); + await sleep(500); + if ((await page.locator(`[data-testid=stream-asks] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"] button:not([disabled])`).count()) > 0) { + fail(`${workstream}'s stream still offers an answer on the approved ask`); + } + } + report.note(`${signal}: ${kind.trim()} ask ${ask.suspensionId} from ${ask.seat} on ${shownStream.trim()}, approved; resume stored ${stored}, gone from Inbox ${gone}`); + return stored; +} + +/** a2's reading of a task frame: its Session draws the run session's items, by id, and its inspector links the trace. */ +async function taskJourney(page: Page, api: LabApi, row: StoredRow, devtool: string | null, signal: string, report: Report, from: string): Promise { + const fail = (why: string) => report.fail(signal, `[from ${from}] ${why}`); + await page.locator(`[data-testid=task-frame][data-task-id="${row.id}"]`).waitFor({ timeout: 15_000 }); + if (!(await tabSelected(page, "session"))) fail("the task does not open on its Session tab"); + const drawnIds = async () => (await page.locator("[data-testid=session-item]").evaluateAll((els) => els.map((e) => e.getAttribute("data-item-id") ?? ""))) as string[]; + let drawn: string[] = []; + for (const until = Date.now() + 30_000; Date.now() < until && drawn.length === 0; await sleep(500)) drawn = await drawnIds(); + let stored = new Set((await api.items(row.run!.sessionId)).map((i) => String(i.id))); + if (drawn.length === 0) fail(`the Session draws nothing while the run session ${row.run!.sessionId} holds ${stored.size} items`); + let strays = drawn.filter((id) => !stored.has(id)); + // A live run's items are drawn as they stream; the store may keep them later. + // A drawn item is a stray only if the store never comes to hold it. + const early = strays.length; + for (const until = Date.now() + STORED_BY_MS; strays.length > 0 && Date.now() < until; await sleep(2_000)) { + stored = new Set((await api.items(row.run!.sessionId)).map((i) => String(i.id))); + strays = drawn.filter((id) => !stored.has(id)); + } + if (early > 0) report.note(`${signal} [from ${from}]: ${early} drawn item(s) were not yet in the store when drawn${strays.length === 0 ? "; the store held them later" : ""}`); + if (strays.length > 0) fail(`the Session draws ${strays.length} item(s) the run session ${row.run!.sessionId} doesn't hold (${strays.slice(0, 3).join(", ")})`); + if (!(await visible(page, "task-inspector"))) { + fail("the right panel holds no task inspector"); + return; + } + const href = await page.getByTestId("inspector-trace-link").getAttribute("href").catch(() => null); + const wanted = devtool === null ? null : `${devtool}?session=${encodeURIComponent(row.run!.sessionId)}`; + if (wanted === null) fail("Shift Manager served no devtool, so there is no trace link to follow"); + else if (href !== wanted) fail(`the trace link is ${href}, wanted ${wanted}`); + else if (from === "Tasks") { + const [opened] = await Promise.all([page.context().waitForEvent("page", { timeout: 10_000 }), page.getByTestId("inspector-trace-link").click()]); + try { + const badge = opened.locator(`button[title^="Session ID: ${row.run!.sessionId}"]`); + if (!(await badge.waitFor({ timeout: 20_000 }).then(() => true, () => false))) fail(`following Open trace did not open session ${row.run!.sessionId} in the devtool`); + } finally { + await opened.close(); + } + } + report.note(`${signal} [from ${from}]: ${drawn.length} items drawn, all held by ${row.run!.sessionId} (${stored.size} stored); trace ${href === wanted ? "linked and followed" : href}`); +} + +/** + * Leg a. DevForce as the DevTeam profile on the real harness. a1 the Inbox + * journey, a4 the `@worker` turn into the running task session (the one step + * graded on the model), a2 the task journey from Tasks and from the Board, + * a3 every surface. Also b's org step on this tree: the switcher names the + * store's org. + */ +export async function legA(ctx: LegCtx): Promise { + const { report } = ctx; + const keys = MODEL_KEYS.filter((k) => (process.env[k] ?? "") !== ""); + if (keys.length === 0) { + report.fail("a4", "blocked: no model key in the environment, and a4 rests on a real model"); + return; + } + const tree = await readTree(TREES.devforce); + const served = await startDevTeam(ctx, "a-devforce", "claude-code"); + const { page, errors } = await newPage(ctx.browser); + try { + await open(page, served.origin, "/"); + const { userId, bearer } = await injected(page); + const api = labApi(served.origin, bearer); + const before = await readStore(api, tree, userId); + report.note(`a: DevForce served as --team devteam on the claude-code harness, ${keys.length} model key(s) set; org ${before.orgs.join(", ")}`); + + // a1: from the first screen, Inbox. + const approved = await inboxJourney(page, api, before, tree, "a1", report); + + // a4: the `@worker` turn, while the approved task runs. + const row = approved ? await runningRow(api, tree, userId, RUN_STARTS_MS) : undefined; + if (row === undefined) { + report.fail("a2", approved ? `no row was running with a run link within ${RUN_STARTS_MS / 60_000} min of Approve` : "no ask was approved, so no task runs"); + report.fail("a4", "no task of the coder's is running, so there is nothing to talk to"); + } else { + const channel = tree.channels.find((c) => c.boardRefs.includes(row.ref))!; + const assignee = String(row.raw.assignee ?? ""); + const seat = tree.seats.find((s) => s === assignee || s.endsWith(`.${assignee}`)) ?? assignee; + // The turn goes in mid-run: once the harness has had A4_SETTLE_MS to open and + // confirm its coding session (the door refuses a run whose session is not yet + // confirmed), and long before a real coding run ends. The run session's own + // items are counted to say whether the person could see the run working. + await sleep(A4_SETTLE_MS); + const working = (await api.items(row.run!.sessionId)).filter((i) => i.requestId === row.run!.requestId && (i.type === "tool_output" || i.type === "reasoning" || (i.type === "message" && i.role === "assistant"))).length; + const line = token("a4"); + await page.getByTestId(`nav-workstream-${channel.id}`).click(); + await page.locator("[role=tab][data-tab=stream]").click(); + await page.getByTestId("composer-input").fill(`@${seat.split(".").at(-1)} ${line}`); + const picker = page.getByTestId("composer-task-picker"); + if (await picker.isVisible().catch(() => false)) await picker.selectOption(row.id); + const sent = await sendAndWatch(page, "composer", () => api.holds(row.run!.sessionId, "user", line)); + if (sent.state !== "delivered") report.fail("a4", `the composer never read delivered: ${sent.state}${sent.error === null ? "" : `, "${sent.error}"`}`); + else if (sent.heldAtDelivered !== true) report.fail("a4", `the composer read delivered while ${seat}'s running task session ${row.run!.sessionId} held no person's turn with the token`); + // The seat answers in that session: an assistant message, after the person's turn, from the next + // attempt (the one handed the line), not the stopped attempt's work going on. + let answer: Record | undefined; + let turnAt = -1; + let nextRequest: string | undefined; + for (const until = Date.now() + ANSWER_MS; Date.now() < until && answer === undefined; await sleep(2_000)) { + const messages = await api.items(row.run!.sessionId, ["message"]); + turnAt = messages.findIndex((m) => m.role === "user" && JSON.stringify(m.content ?? m.text ?? m).includes(line)); + const linked = (await readStore(api, tree, userId)).rows[channel.id]?.find((r) => r.id === row.id)?.run; + if (linked != null && linked.requestId !== row.run!.requestId) nextRequest = linked.requestId; + if (turnAt >= 0 && nextRequest !== undefined) answer = messages.slice(turnAt + 1).find((m) => m.role === "assistant" && m.requestId === nextRequest); + if (sent.state !== "delivered") break; + } + if (turnAt < 0) report.fail("a4", `${seat}'s running task session ${row.run!.sessionId} never held a person's turn with the token`); + else if (sent.state === "delivered" && nextRequest === undefined) report.fail("a4", `no next attempt took the line within ${ANSWER_MS / 60_000} min (not retried)`); + else if (sent.state === "delivered" && answer === undefined) report.fail("a4", `the next attempt ${nextRequest} did not answer in ${row.run!.sessionId} within ${ANSWER_MS / 60_000} min of the turn (not retried)`); + const answerText = answer === undefined ? "" : JSON.stringify(answer.content ?? answer.text ?? "").slice(0, 160); + report.note(`a4: @${seat.split(".").at(-1)} ${line} sent after ${working} harness item(s) in the attempt → ${sent.state}${sent.heldAtDelivered === true ? " (held when drawn)" : ""}${sent.error === null ? "" : ` "${sent.error}"`} in ${row.run!.sessionId}; next attempt ${nextRequest ?? "none"}; answer ${answer === undefined ? "none" : `${String(answer.id)}: ${answerText}`}`); + + // a2: the task, from Tasks and again from the workstream's Board. + const current = (await readStore(api, tree, userId)).rows[channel.id]!.find((r) => r.id === row.id) ?? row; + const linked = current.run === null ? row : current; + await page.getByTestId("nav-tasks").click(); + await page.locator(`[data-testid=task-row][data-task-id="${row.id}"]`).click(); + await taskJourney(page, api, linked, served.devtool, "a2", report, "Tasks"); + await page.getByTestId(`nav-workstream-${channel.id}`).click(); + await page.locator("[role=tab][data-tab=board]").click(); + await page.locator(`[data-testid=board-card][data-task-id="${row.id}"]`).click(); + await taskJourney(page, api, linked, served.devtool, "a2", report, "Board"); + } + + // a3: every surface, against the store as it stands now. + const store = await readStore(api, tree, userId); + const { orgShown } = await walkSurfaces(page, served.origin, store, tree, { reach: "a3", teams: "a3" }, report); + if (store.orgs.length !== 1) report.fail("b:org", `[devforce] the person's sessions sit in ${store.orgs.length} orgs (${store.orgs.join(", ")})`); + else if (orgShown !== store.orgs[0]) report.fail("b:org", `[devforce] the org switcher names "${orgShown}", the store's org is ${store.orgs[0]}`); + if (errors.length > 0) report.fail("a3", `the page threw: ${errors.join(" | ")}`); + const rows = Object.values(store.rows).flat(); + report.note(`a3: ${store.seats.length} seats [${store.seats.join(", ")}], ${store.channels.length} workstream(s), ${rows.length} row(s) [${rows.map((r) => r.status).join(", ")}], ${store.asks.length} ask(s) pending; org switcher "${orgShown}"`); + } finally { + await page.close(); + await served.stop(); + } +} + +// ---- leg b: pentest, keyless, and every Lab under an org ------------------------ + +/** + * Names a pentest seat, team or channel: a full id anywhere, or a bare name + * as a whole string literal. A bare name in prose ("an audit note", "the + * findings") is English, not the tree. + */ +function pentestNames(tree: Tree): RegExp { + const esc = (w: string) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const ids = [...tree.seats, ...tree.channels.map((c) => c.id)]; + const bare = new Set(); + for (const id of ids) for (const part of id.split(".")) bare.add(part); + return new RegExp(`(? { + for (const entry of readdirSync(dir)) { + if (entry === "node_modules" || entry === "dist") continue; + const full = join(dir, entry); + if (/src[/\\]components[/\\](flow-state|ui)$/.test(full)) continue; + if (statSync(full).isDirectory()) walk(full); + else out.push(full); + } + }; + walk(SHIFT_MANAGER); + return out; +} + +/** Leg b: the same reach on the pentest tree, its post, the fence, and the org step. */ +export async function legB(ctx: LegCtx): Promise { + const { report } = ctx; + const tree = await readTree(TREES.pentest); + const served = await startShiftManager(ctx.scratch, "b-pentest", { config: PENTEST_CONFIG, pages: ctx.pages, env: KEYLESS }); + const { page, errors } = await newPage(ctx.browser); + try { + await open(page, served.origin, "/"); + const { userId, bearer } = await injected(page); + const api = labApi(served.origin, bearer); + const store = await readStore(api, tree, userId); + if (!same(store.seats, tree.seats)) report.fail("b:reach", `the store's seats are not the tree's: ${diff(tree.seats, store.seats)}`); + const { orgShown } = await walkSurfaces(page, served.origin, store, tree, { reach: "b:reach", teams: "b:teams" }, report, { + // The pentest channel attaches no board, so no task exists to reach; its Board tab names that (PLAN: b). + taskLevel: false, + }); + if (store.orgs.length !== 1) report.fail("b:org", `[pentest] the person's sessions sit in ${store.orgs.length} orgs (${store.orgs.join(", ")})`); + else if (orgShown !== store.orgs[0]) report.fail("b:org", `[pentest] the org switcher names "${orgShown}", the store's org is ${store.orgs[0]}`); + + // The post: in the stored transcript before the stream shows it. + const channel = tree.channels[0]!; + const line = token("b-post"); + await page.getByTestId(`nav-workstream-${channel.id}`).click(); + await page.locator("[role=tab][data-tab=stream]").click(); + await page.getByTestId("composer-input").fill(line); + await page.getByTestId("composer-send").click(); + const drawn = page.getByTestId("transcript-line-body").filter({ hasText: line }); + const keptNow = async () => (await api.items(channel.id, ["component"])).filter((i) => i.component === "channel-post" && i.data?.body === line).length; + let atDrawn: number | null = null; + for (const until = Date.now() + 30_000; Date.now() < until && atDrawn === null; await sleep(50)) { + if ((await drawn.count()) > 0) atDrawn = await keptNow(); + } + if (atDrawn === null) report.fail("b:post", `"${line}" was never drawn (${(await page.getByTestId("composer-status").textContent().catch(() => "")) ?? ""})`); + else if (atDrawn !== 1) report.fail("b:post", `the stream drew the post while the channel's stored transcript held ${atDrawn} copies of it`); + await open(page, served.origin, `/w/${encodeURIComponent(channel.id)}/stream`); + await page.getByTestId("transcript").waitFor().catch(() => undefined); + await sleep(1_000); + if ((await drawn.count()) !== 1) report.fail("b:post", `after a reload "${line}" is drawn ${await drawn.count()} times`); + if (errors.length > 0) report.fail("b:reach", `the page threw: ${errors.join(" | ")}`); + report.note( + `b: pentest served from its committed config, keyless; ${store.seats.length} seats [${store.seats.join(", ")}] in teams [${[...new Set(store.seats.map((s) => s.split(".")[0]))].join(", ")}], workstreams [${store.channels.map((c) => c.id).join(", ")}]; post held ${atDrawn ?? "never drawn"} when drawn; org switcher "${orgShown}", store org ${store.orgs.join(", ")}`, + ); + } finally { + await page.close(); + await served.stop(); + } + + // The fence: Shift Manager untouched, and naming nothing of the pentest tree. + try { + execFileSync("git", ["diff", "--quiet", "HEAD", "--", "labs/shift-manager"], { cwd: REPO_ROOT }); + } catch { + report.fail("b:fence", "labs/shift-manager differs from the commit"); + } + const names = pentestNames(tree); + const hits = shiftManagerFiles().flatMap((file) => { + const m = names.exec(readFileSync(file, "utf8")); + return m === null ? [] : [`${relative(REPO_ROOT, file)}: ${m[1] ?? m[2]}`]; + }); + if (hits.length > 0) report.fail("b:fence", `Shift Manager names the pentest tree: ${hits.slice(0, 5).join("; ")}`); + report.note(`b:fence: git diff of labs/shift-manager empty; no Shift Manager file (registry copies aside) names a pentest id [${[...tree.seats, ...tree.channels.map((c) => c.id)].join(", ")}] or quotes a bare name of one`); + + // Every Lab opens under an org: a Lab with no resolver opens under the dev org. + const askLab = await startShiftManager(ctx.scratch, "b-no-resolver", { config: ASK_LAB_CONFIG, pages: ctx.pages, env: KEYLESS }); + const second = await newPage(ctx.browser); + try { + await open(second.page, askLab.origin, "/"); + const { userId } = await injected(second.page); + const listing = await labApi(askLab.origin, undefined).get(`/sessions?userId=${encodeURIComponent(userId)}&limit=500`); + const orgs = [...new Set(((listing.sessions ?? []) as Array<{ orgId?: string }>).map((s) => s.orgId).filter(Boolean))]; + const shown = ((await second.page.getByTestId("org-switcher").locator("span.truncate").first().textContent().catch(() => null)) ?? "").trim(); + if (!same(orgs as string[], [DEFAULT_ORG_ID])) report.fail("b:org", `[no resolver] the Lab's sessions sit in [${orgs.join(", ")}], wanted the dev org ${DEFAULT_ORG_ID}`); + if (shown !== DEFAULT_ORG_ID) report.fail("b:org", `[no resolver] the org switcher names "${shown}", wanted ${DEFAULT_ORG_ID}`); + if ((await second.page.getByTestId("refusal").count()) + (await second.page.getByTestId("unreachable").count()) > 0) report.fail("b:org", "[no resolver] the Lab opens on a refusal, not the app"); + if (!(await visible(second.page, "cos", 5_000))) report.fail("b:org", "[no resolver] the Lab opens as an empty app, with no Chief of Staff"); + report.note(`b:org [no resolver]: ask-lab with no bearer; sessions in [${orgs.join(", ")}], switcher "${shown}"`); + } finally { + await second.page.close(); + await askLab.stop(); + } +} + +// ---- leg c: no theme, light then dark ----------------------------------------- + +const THEME = readShiftManagerTheme(); +/** The registry parts and the devtool page, by the selector that finds each on its page. */ +export const SWEPT = { + message: "[data-testid=session-item][data-item-type=message] [data-testid=message]", + reasoning: "[data-testid=session-item][data-item-type=reasoning] [data-slot=collapsible]", + tool: "[data-testid=session-item][data-item-type=tool_output] [data-slot=collapsible]", + "code block": "[data-testid=session-item][data-item-type=tool_output] [data-language]", + ask: "[data-testid=ask-card]", +} as const; +const firstFamily = (value: string) => value.split(",")[0]!.trim().replace(/^["']|["']$/g, ""); + +/** Every painted value on `read` that is a Shift Manager value (either variant) or one of its fonts. */ +function themedHits(read: PageRead): Sample[] { + const all = [...THEME.light, ...THEME.dark]; + const theme = all.map((v) => parseColour(read.probes[v] ?? v)?.rgb).filter((v): v is Rgb => v !== undefined); + const hits: Sample[] = []; + for (const s of read.colours) { + const c = parseColour(s.value); + if (c !== null && theme.some((t) => near(t, c.rgb))) hits.push({ ...s, value: hex(c.rgb) }); + } + for (const s of read.fonts) if (THEME.families.includes(firstFamily(s.value))) hits.push(s); + return hits; +} + +/** Read painted values for the parts on screen now, and add them to the pass's tally. */ +async function sweep(page: Page, parts: Record, tally: Map): Promise { + await settled(page); + const read = await page.evaluate(readPainted, { parts, probeValues: [...THEME.light, ...THEME.dark] }); + for (const [part, n] of Object.entries(read.counts)) { + const entry = tally.get(part) ?? { elements: 0, hits: [] }; + entry.elements += n; + entry.hits.push(...themedHits({ ...read, colours: read.colours.filter((s) => s.part === part), fonts: read.fonts.filter((s) => s.part === part) })); + tally.set(part, entry); + } +} + +/** Open every collapsed card in the task's Session, so the code block inside the tool card is drawn. */ +async function expandSession(page: Page): Promise { + for (const trigger of await page.locator("[data-testid=session-item] [data-slot=collapsible-trigger]").all()) { + if ((await trigger.getAttribute("data-state")) === "closed") await trigger.click().catch(() => undefined); + } + await page.locator(SWEPT["code block"]).first().waitFor({ timeout: 5_000 }).catch(() => undefined); +} + +/** + * Leg c. The no-theme build, started on `--shift day` then `--shift night`. + * Per pass: DevForce (scripted harness) for every surface a3 reaches, the ask + * card in Inbox and in the stream, a run's Session and the devtool page its + * trace link opens; and the run-lab, whose runs store the reasoning, tool and + * code block cards DevForce's scripted run never draws. Each swept part must + * render at least once per pass (QR-13) and carry no Shift Manager value. + * Then FIX-1655's static fence over `packages/`. + */ +export async function legC(ctx: LegCtx): Promise { + const { report } = ctx; + for (const shift of ["day", "night"] as const) { + const wantDark = shift === "night"; + const tally = new Map(); + // DevForce. + const tree = await readTree(TREES.devforce); + const devforce = await startDevTeam(ctx, `c-devforce-${shift}`, "stub", shift); + const { page, errors } = await newPage(ctx.browser); + try { + await open(page, devforce.origin, "/"); + const dark = await page.evaluate(() => document.documentElement.classList.contains("dark")); + if (dark !== wantDark) report.fail("c:reach", `[${shift}] --shift ${shift} started the page ${dark ? "dark" : "light"}`); + const { userId, bearer } = await injected(page); + const api = labApi(devforce.origin, bearer); + const before = await readStore(api, tree, userId); + // The ask card, in Inbox's detail pane and in the stream. + const ask = before.asks[0]; + if (ask !== undefined) { + await page.getByTestId("nav-inbox").click(); + await page.locator(`[data-testid=inbox-item][data-suspension-id="${ask.suspensionId}"]`).click(); + await page.locator("[data-testid=inbox-detail] [data-testid=ask-card]").waitFor(); + await sweep(page, { ask: `[data-testid=inbox-detail] ${SWEPT.ask}` }, tally); + const workstream = tree.channels.find((c) => c.members.includes(ask.seat))!.id; + await page.getByTestId(`nav-workstream-${workstream}`).click(); + await page.locator("[data-testid=stream-asks] [data-testid=ask-card]").waitFor().catch(() => undefined); + await sweep(page, { ask: `[data-testid=stream-asks] ${SWEPT.ask}` }, tally); + // Approve, so a run's Session and its trace page can be read. + await page.getByTestId("nav-inbox").click(); + await page.locator(`[data-testid=inbox-item][data-suspension-id="${ask.suspensionId}"]`).click(); + await page.locator("[data-testid=inbox-detail]").getByRole("button", { name: "Approve" }).click(); + const row = await runningRow(api, tree, userId, 60_000); + if (row !== undefined) { + await page.getByTestId("nav-tasks").click(); + await page.locator(`[data-testid=task-row][data-task-id="${row.id}"]`).click(); + await page.locator("[data-testid=session-item]").first().waitFor({ timeout: 30_000 }).catch(() => undefined); + await expandSession(page); + await sweep(page, SWEPT, tally); + const link = page.getByTestId("inspector-trace-link"); + if ((await link.count()) > 0) { + const [trace] = await Promise.all([page.context().waitForEvent("page", { timeout: 10_000 }), link.click()]); + await trace.addInitScript("globalThis.__name = (fn) => fn;"); + await trace.locator(`button[title^="Session ID: ${row.run!.sessionId}"]`).waitFor({ timeout: 20_000 }).catch(() => undefined); + await trace.evaluate("globalThis.__name = (fn) => fn;"); + await sweep(trace, { devtool: "body" }, tally); + await trace.close(); + } + } else report.fail("c:reach", `[${shift}] DevForce's approved row never ran on the scripted harness`); + } else report.fail("c:reach", `[${shift}] DevForce raised no ask, so the ask card could not be swept`); + // Every surface a3 reaches, now that a row exists, on this shift's look. + await walkSurfaces(page, devforce.origin, await readStore(api, tree, userId), tree, { reach: "c:reach", teams: "c:reach" }, report); + if (errors.length > 0) report.fail("c:reach", `[${shift}] the page threw: ${errors.join(" | ")}`); + } finally { + await page.close(); + await devforce.stop(); + } + // The run-lab, for the cards DevForce's scripted run never draws. + const runLab = await startShiftManager(ctx.scratch, `c-run-lab-${shift}`, { config: RUN_LAB_CONFIG, pages: ctx.pages, shift, env: KEYLESS }); + const second = await newPage(ctx.browser); + try { + const lab = await readTree(TREES.runLab); + await open(second.page, runLab.origin, "/tasks"); + const { userId, bearer } = await injected(second.page); + const row = await runningRow(labApi(runLab.origin, bearer), lab, userId, 30_000); + if (row === undefined) report.fail("c:reach", `[${shift}] the run-lab's board never held a running row`); + else { + await second.page.getByTestId("nav-tasks").click(); + await second.page.locator(`[data-testid=task-row][data-task-id="${row.id}"]`).click(); + await second.page.locator("[data-testid=session-item][data-item-type=tool_output]").first().waitFor({ timeout: 20_000 }).catch(() => undefined); + await expandSession(second.page); + await sweep(second.page, SWEPT, tally); + } + } finally { + await second.page.close(); + await runLab.stop(); + } + // Grade the pass. + const parts = [...Object.keys(SWEPT), "devtool"]; + for (const part of parts) { + const entry = tally.get(part); + if (entry === undefined || entry.elements === 0) report.fail("c:sweep", `[${shift}] ${part} never rendered in this pass (QR-13)`); + for (const hit of (entry?.hits ?? []).slice(0, 4)) report.fail(`c:${part}`, `[${shift}] ${hit.el} ${hit.prop} → ${hit.value} is a Shift Manager value`); + if ((entry?.hits.length ?? 0) > 4) report.fail(`c:${part}`, `[${shift}] … and ${entry!.hits.length - 4} more on ${part}`); + } + report.note(`c [${shift}]: ${parts.map((p) => `${p} ${tally.get(p)?.elements ?? 0}`).join(", ")} elements; ${parts.reduce((n, p) => n + (tally.get(p)?.hits.length ?? 0), 0)} Shift Manager values`); + } + report.note(`c theme values: ${THEME.light.length} light and ${THEME.dark.length} dark colours, families [${THEME.families.join(", ")}], read from labs/design-system/shift-manager.css`); + staticFence(join(REPO_ROOT, "packages"), "c:static", report); +} + +/** FIX-1655's static fence: no Shift Manager value anywhere under a `packages/` tree. */ +export function staticFence(packages: string, signal: string, report: Report): void { + const values = themeValues(readFileSync(join(REPO_ROOT, "labs", "design-system", "shift-manager.css"), "utf8")); + const { walked, hits } = findThemeValues(packages, values); + if (walked < 500) report.fail(signal, `the fence walked only ${walked} files under ${packages}`); + if (hits.length > 0) report.fail(signal, `a Shift Manager value sits under packages/: ${hits.slice(0, 5).join("; ")}`); + report.note(`${signal}: ${values.length} theme values, ${walked} files under ${relative(REPO_ROOT, packages) || packages}, ${hits.length} hit(s)`); +} diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts new file mode 100644 index 0000000000..8fe28d16c5 --- /dev/null +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts @@ -0,0 +1,422 @@ +/** + * Parts 2 and 4 of the closure: the two teams the legs don't walk (J3, J4), + * and the seam sweep. Part 3 is the child checks, run by subprocess from + * `run.mts`. + * + * J3's host scaffolding (the registry served from this checkout, a host app + * shaped the way `shadcn init` leaves one, the CLI's copies compared with + * their sources) is lifted from FIX-1655's + * `goals/design-system/skins-reused-components-from-one-token-set/run.mts`, + * which executes on import. + */ +import { execFile, execFileSync } from "node:child_process"; +import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import { createRequire } from "node:module"; +import type { AddressInfo } from "node:net"; +import { extname, join, relative } from "node:path"; +import { pathToFileURL } from "node:url"; +import { promisify } from "node:util"; +import type { Browser } from "playwright"; +import { hex, near, parseColour } from "../../lib/colour.mts"; +import { REPO_ROOT } from "../../lib/index.mts"; +import { TREES, type Report } from "./legs.mts"; +import { SHIFT_MANAGER, injected, labApi, open, readStore, readTree, sleep, startShiftManager, type Running } from "./shell.mts"; + +const execFileAsync = promisify(execFile); +const UI = join(REPO_ROOT, "packages", "ui"); + +// ---- J3: someone reusing FSD UI in their own app ------------------------------- + +/** The two status-bearing items the fresh app installs: both paint `--success`. */ +const J3_ITEMS = ["tool", "approval"]; + +function serve(root: string): Promise<{ server: Server; origin: string }> { + const types: Record = { ".json": "application/json", ".html": "text/html", ".js": "text/javascript", ".css": "text/css" }; + const server = createServer((req, res) => { + const path = decodeURIComponent(new URL(req.url ?? "/", "http://x").pathname); + const file = join(root, path === "/" ? "index.html" : path); + if (!existsSync(file) || statSync(file).isDirectory()) { + res.writeHead(404).end(); + return; + } + res.writeHead(200, { "content-type": types[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file)); + }); + return new Promise((done) => server.listen(0, "127.0.0.1", () => done({ server, origin: `http://127.0.0.1:${(server.address() as AddressInfo).port}` }))); +} + +/** Whether an installed copy is its registry source (the CLI drops leading comments on a file with no "use client"). */ +function sameAsInstalled(copy: string, source: string): boolean { + if (copy === source) return true; + return !/^["']use client["']/.test(source) && copy === source.replace(/^(?:\/\*[\s\S]*?\*\/\s*)+/, ""); +} + +/** Every registry file the installed items ship, as `target → registry source`, followed through dependencies. */ +function shippedFiles(registryDir: string, base: string): Map { + const manifest = JSON.parse(readFileSync(join(UI, "registry.json"), "utf8")) as { items: Array<{ name: string; files?: Array<{ path: string; target: string }> }> }; + const byName = new Map(manifest.items.map((i) => [i.name, i])); + const out = new Map(); + const seen = new Set(); + const visit = (name: string) => { + if (seen.has(name)) return; + seen.add(name); + const built = JSON.parse(readFileSync(join(registryDir, `${name}.json`), "utf8")) as { registryDependencies: string[] }; + for (const file of byName.get(name)?.files ?? []) out.set(file.target, file.path); + for (const dep of built.registryDependencies) if (dep.startsWith(`${base}/`)) visit(dep.slice(base.length + 1, -".json".length)); + }; + for (const item of J3_ITEMS) visit(item); + return out; +} + +/** The first `css` block under the docs' "One set of tokens" heading, as written. */ +function docsTokenBlock(): string { + const page = readFileSync(join(REPO_ROOT, "apps", "docs", "docs", "workforce", "ui.md"), "utf8"); + const section = page.slice(page.indexOf("### One set of tokens")); + const block = /```css\n([\s\S]*?)```/.exec(section)?.[1]; + if (block === undefined) throw new Error("setup: the token section of apps/docs/docs/workforce/ui.md has no css block to follow"); + return block; +} + +const J3_PAGE = `import { createRoot } from "react-dom/client"; +import { FlowProvider } from "@flow-state-dev/react"; +import { ToolShell, ToolHeader } from "@/components/flow-state/tool"; +import { Approval } from "@/components/flow-state/approval"; +import "./app/globals.css"; + +const ask = { id: "s1", type: "suspension", status: "completed", requestId: "r1", itemIndex: 0, ts: 0, + provenance: { blockName: "gen", blockInstanceId: "b1", phase: "main" }, + suspensionId: "s1", suspensionStatus: "pending", reason: "human_approval", message: "Ship it?" } as never; + +createRoot(document.getElementById("root")!).render( + +
+
+
+
+
, +); +`; + +/** + * J3. A fresh app outside Shift Manager and kitchen-sink installs two + * status-bearing components from this commit's registry with `fsdev ui add`, + * follows the token section of `apps/docs/docs/workforce/ui.md` as written, + * then changes one status token: both components follow, and the copies are + * byte-identical to the registry. + */ +export async function j3(scratch: string, browser: Browser, report: Report): Promise { + const fail = (why: string) => report.fail("J3", why); + const root = join(scratch, "j3"); + const registryDir = join(root, "r"); + const host = join(root, "host"); + const dist = join(host, "dist"); + mkdirSync(registryDir, { recursive: true }); + const { server, origin } = await serve(root); + try { + execFileSync("pnpm", ["exec", "tsx", "scripts/build-registry.ts", "--base-url", `${origin}/r`, "--out", registryDir], { cwd: UI, stdio: "ignore" }); + // The host, as `shadcn init` leaves one; it lists every package the registry's workspace has, so the CLI installs none. + const ui = JSON.parse(readFileSync(join(UI, "package.json"), "utf8")) as Record>; + const listed = { ...ui.dependencies, ...ui.devDependencies, ...ui.peerDependencies, cn: "*" }; + const deps = Object.fromEntries(Object.entries(listed).map(([name, range]) => [name, range.startsWith("workspace:") ? "*" : range])); + mkdirSync(join(host, "app"), { recursive: true }); + writeFileSync(join(host, "package.json"), JSON.stringify({ name: "j3-host", private: true, type: "module", dependencies: deps }, null, 2)); + writeFileSync(join(host, "tsconfig.json"), JSON.stringify({ compilerOptions: { baseUrl: ".", paths: { "@/*": ["./*"] } } })); + writeFileSync( + join(host, "components.json"), + JSON.stringify({ + $schema: "https://ui.shadcn.com/schema.json", + style: "new-york", + rsc: false, + tsx: true, + tailwind: { config: "", css: "app/globals.css", baseColor: "neutral", cssVariables: true }, + aliases: { components: "@/components", utils: "@/lib/utils", ui: "@/components/ui" }, + }), + ); + writeFileSync(join(host, "app/globals.css"), '@import "tailwindcss";\n'); + const install = execFileAsync("pnpm", ["fsdev", "ui", "add", ...J3_ITEMS, "--registry", `${origin}/r`, "--cwd", host], { cwd: REPO_ROOT, timeout: 180_000, maxBuffer: 64 * 1024 * 1024 }); + install.child.stdin?.end(); + const { stdout, stderr } = await install; + const asked = `${stdout}${stderr}`.match(/[^\n]*Would you like to[^\n?]*\?/g); + if (asked) return fail(`fsdev ui add stopped to ask: ${asked.join(" | ")}`); + // The upstream primitives the CLI fetched, swapped for the ones the registry's Storybook builds against (as FIX-1655's check does). + cpSync(join(UI, ".storybook/shadcn"), host, { recursive: true }); + + // The copies are byte-identical to the registry, before anything reads them. + const shipped = shippedFiles(registryDir, `${origin}/r`); + for (const [target, source] of shipped) { + const copy = join(host, target); + if (!existsSync(copy)) fail(`${target} was not installed`); + else if (!sameAsInstalled(readFileSync(copy, "utf8"), readFileSync(join(UI, source), "utf8"))) fail(`the installed ${target} differs from ${source}`); + } + + // Follow the docs: the navigator's and panels' properties pointed at the same tokens. + const block = docsTokenBlock(); + writeFileSync(join(host, "app/globals.css"), `${readFileSync(join(host, "app/globals.css"), "utf8")}\n${block}`); + const success = /:root\s*\{[^}]*?--success:\s*([^;]+);/.exec(readFileSync(join(host, "app/globals.css"), "utf8"))?.[1]?.trim(); + if (success === undefined) return fail("the installed tokens define no --success on :root to change"); + + // node_modules: the registry workspace's, linked after the CLI ran. + const from = join(UI, "node_modules"); + const to = join(host, "node_modules"); + mkdirSync(to, { recursive: true }); + for (const entry of readdirSync(from)) { + if (entry.startsWith(".")) continue; + if (entry.startsWith("@")) { + mkdirSync(join(to, entry), { recursive: true }); + for (const scoped of readdirSync(join(from, entry))) if (!existsSync(join(to, entry, scoped))) symlinkSync(join(from, entry, scoped), join(to, entry, scoped)); + } else if (!existsSync(join(to, entry))) symlinkSync(join(from, entry), join(to, entry)); + } + writeFileSync(join(host, "index.html"), '
'); + writeFileSync(join(host, "main.tsx"), J3_PAGE); + + const req = createRequire(join(UI, "package.json")); + const load = async (name: string) => (await import(pathToFileURL(req.resolve(name)).href)) as Record; + const build = async () => { + const vite = await load("vite"); + await vite.build({ + root: host, + base: "/host/dist/", + configFile: false, + logLevel: "error", + plugins: [(await load("@vitejs/plugin-react")).default(), (await load("@tailwindcss/vite")).default()], + resolve: { alias: { "@": host } }, + build: { outDir: dist, target: "es2022", emptyOutDir: true, chunkSizeWarningLimit: 100_000 }, + }); + }; + const read = async () => { + const page = await browser.newPage(); + try { + await page.goto(`${origin}/host/dist/index.html`); + await page.locator("[data-part=approval] button").first().waitFor({ timeout: 20_000 }); + return (await page.evaluate(() => ({ + tool: getComputedStyle(document.querySelector("[data-part=tool] svg.lucide-circle-check-big")!).stroke, + approval: getComputedStyle(Array.from(document.querySelectorAll("[data-part=approval] button")).find((b) => b.textContent?.includes("Approve"))!).backgroundColor, + }))) as { tool: string; approval: string }; + } finally { + await page.close(); + } + }; + await build(); + const before = await read(); + // Change one status token, in the stylesheet the docs had the app define them in. + const changed = "#1f6feb"; + const css = readFileSync(join(host, "app/globals.css"), "utf8"); + writeFileSync(join(host, "app/globals.css"), css.replace(/(:root\s*\{[^}]*?--success:\s*)([^;]+);/, `$1${changed};`)); + await build(); + const after = await read(); + const want = [1, 3, 5].map((i) => parseInt(changed.slice(i, i + 2), 16)) as [number, number, number]; + for (const part of ["tool", "approval"] as const) { + const was = parseColour(before[part]); + const now = parseColour(after[part]); + if (now === null || !near(now.rgb, want)) fail(`${part} paints ${now === null ? "nothing" : hex(now.rgb)} after --success became ${changed}`); + if (was !== null && near(was.rgb, want)) fail(`${part} already painted ${changed} before the change, so following it proves nothing`); + } + report.note( + `J3: fresh host, \`fsdev ui add ${J3_ITEMS.join(" ")}\` from this commit's registry, ${shipped.size} copies byte-identical; docs' token block applied as written; --success ${success} → ${changed}: tool ${before.tool} → ${after.tool}, approval ${before.approval} → ${after.approval}`, + ); + } catch (error) { + fail(`setup: ${String((error as Error).message ?? error).split("\n").slice(0, 6).join(" ")}`); + } finally { + server.close(); + } +} + +// ---- J4: a sibling epic's owner ------------------------------------------------- + +/** + * J4. Every surface in the epic's ownership table opens by its address on a + * fresh load, and shows store rows or a named empty state that says what + * arrives. None hidden, none blank. DevForce on the scripted harness, after + * its ask is approved so a task exists. + */ +export async function j4(scratch: string, pages: string, browser: Browser, report: Report): Promise { + const fail = (why: string) => report.fail("J4", why); + const tree = await readTree(TREES.devforce); + let served: Running | undefined; + try { + served = await startShiftManager(scratch, "j4-devforce", { + team: "devteam", + pages, + env: { DEVFORCE_LAB_HARNESS: "stub", AI_GATEWAY_API_KEY: "", OPENAI_API_KEY: "", OPENROUTER_API_KEY: "", ANTHROPIC_API_KEY: "" }, + }); + const setup = await browser.newPage(); + await open(setup, served.origin, "/inbox"); + const { userId, bearer } = await injected(setup); + const api = labApi(served.origin, bearer); + await setup.getByTestId("inbox-item").first().click(); + await setup.locator("[data-testid=inbox-detail]").getByRole("button", { name: "Approve" }).click(); + let row: { ref: string; id: string } | undefined; + for (let waited = 0; waited < 60_000 && row === undefined; waited += 500) { + row = Object.values((await readStore(api, tree, userId)).rows).flat()[0]; + if (row === undefined) await sleep(500); + } + await setup.close(); + if (row === undefined) return fail("DevForce filed no row after its ask was approved"); + const ch = tree.channels[0]!.id; + const task = `/tasks/${encodeURIComponent(row.ref)}/${encodeURIComponent(row.id)}`; + const addresses: Array<{ path: string; surface: string; owner: string }> = [ + { path: "/cos", surface: "cos", owner: "Chief of Staff (FIX-1719's seat; FIX-1722's view)" }, + { path: "/roster", surface: "roster", owner: "TEAMS, workers, shift status (Workforce; FIX-1723)" }, + { path: `/roster?team=${tree.teams[0]}`, surface: "roster", owner: "a team's workers (Workforce; FIX-1723)" }, + ...["stream", "board", "workstreams", "brief"].map((tab) => ({ path: `/p/unassigned/${tab}`, surface: `project-${tab}-empty`, owner: "projects (FIX-1650)" })), + { path: `/w/${encodeURIComponent(ch)}/stream`, surface: "workstream", owner: "a workstream (FIX-1650)" }, + ...["board", "brief", "results"].map((tab) => ({ path: `/w/${encodeURIComponent(ch)}/${tab}`, surface: "workstream", owner: `a workstream's ${tab} (FIX-1651)` })), + { path: "/inbox", surface: "inbox", owner: "Inbox (FIX-1652)" }, + { path: "/tasks", surface: "tasks", owner: "Tasks, NOW, TIME and COST (FIX-1651; session data)" }, + ...["session", "diff", "checks", "brief"].map((tab) => ({ path: `${task}/${tab}`, surface: "task-frame", owner: `a task's ${tab} (FIX-1651; FIX-1652)` })), + ]; + const named: string[] = []; + for (const address of addresses) { + const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } }); + const errors: string[] = []; + page.on("pageerror", (e) => errors.push(e.message)); + try { + await open(page, served.origin, address.path); + if (!(await page.getByTestId(address.surface).first().waitFor({ timeout: 15_000 }).then(() => true, () => false))) { + fail(`${address.path} (${address.owner}) does not open its surface on a fresh load`); + continue; + } + const centre = ((await page.getByTestId("centre").textContent().catch(() => "")) ?? "").trim(); + if (centre.length === 0) fail(`${address.path} (${address.owner}) is blank`); + // Every empty state and gap line on the screen says something. + const empties = (await page.locator("[data-testid$=-empty], [data-testid=empty-state], [data-testid$=-gap]").evaluateAll((els) => els.map((e) => (e.textContent ?? "").trim()))) as string[]; + if (empties.some((t) => t.length === 0)) fail(`${address.path} draws an empty state with no text`); + named.push(...empties); + if ((await page.getByTestId("refusal").count()) + (await page.getByTestId("unreachable").count()) > 0) fail(`${address.path} opens on a refusal`); + if (errors.length > 0) fail(`${address.path} threw: ${errors.join(" | ")}`); + } finally { + await page.close(); + } + } + report.note(`J4: ${addresses.length} addresses opened fresh on DevForce; ${named.length} named empty states and gap lines, e.g. "${named.find((t) => /FIX-|arriv|not planned|ships/i.test(t))?.slice(0, 120) ?? named[0]?.slice(0, 120)}"`); + } finally { + await served?.stop(); + } +} + +// ---- Part 4: the seams --------------------------------------------------------- + +/** Every file under `dir` matching `keep`, skipping dependencies and build output. */ +function files(dir: string, keep: (path: string) => boolean): string[] { + const out: string[] = []; + for (const entry of readdirSync(dir)) { + if (entry === "node_modules" || entry === "dist") continue; + const full = join(dir, entry); + if (statSync(full).isDirectory()) out.push(...files(full, keep)); + else if (keep(full)) out.push(full); + } + return out; +} + +const stripComments = (text: string) => text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`])\/\/[^\n]*/g, "$1").replace(/\{\/\*[\s\S]*?\*\/\}/g, ""); +const git = (...args: string[]) => execFileSync("git", args, { cwd: REPO_ROOT, encoding: "utf8", maxBuffer: 1 << 30 }); + +/** + * Part 4: only what parts 1 to 3 don't grade. `base` is the commit before the + * epic's first child merged (today's main as the epic's control). + */ +export function part4(base: string, report: Report): void { + const src = join(SHIFT_MANAGER, "src"); + // Shift Manager's own source; the registry copies under components/flow-state and components/ui are FSD's. + const own = files(src, (p) => /\.(tsx?|css)$/.test(p) && !/components[/\\](flow-state|ui)[/\\]/.test(p)); + + // Token names: no literal colour in Shift Manager's own source. + const palette = "slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose"; + const literal = new RegExp( + `#[0-9a-fA-F]{3,8}\\b|\\b(?:rgb|rgba|hsl|hsla|oklch)\\(|\\b(?:text|bg|border|ring|fill|stroke|from|to|via|outline|decoration|divide|shadow|accent|caret)-(?:(?:${palette})-\\d{2,3}|black|white)\\b|-\\[(?:#|rgb|hsl|oklch)`, + ); + const literals = own.flatMap((file) => { + const m = literal.exec(stripComments(readFileSync(file, "utf8"))); + return m === null ? [] : [`${relative(REPO_ROOT, file)}: ${m[0]}`]; + }); + if (literals.length > 0) report.fail("P4:tokens", `a literal colour in Shift Manager's source: ${literals.join("; ")}`); + report.note(`P4 token names: ${own.length} files of Shift Manager's own source, ${literals.length} literal colour(s)`); + + // The task route and the panel slot: FIX-1662's pinned shapes, as the route table parses them. + const routes = readFileSync(join(src, "lib", "routes.ts"), "utf8"); + const pinned: Array<[string, RegExp]> = [ + ["task", /if \(head === "tasks" && a !== undefined && b !== undefined\)[\s\S]*?level: "task", boardRef: a, taskId: b, tab: oneOf\(TASK_TABS/], + ["workstream", /if \(head === "w" && a !== undefined\) return \{ level: "workstream", channelId: a, tab: oneOf\(WORKSTREAM_TABS/], + ["project", /if \(head === "p" && a !== undefined\) return \{ level: "project", projectId: a, tab: oneOf\(PROJECT_TABS/], + ]; + for (const [name, re] of pinned) if (!re.test(routes)) report.fail("P4:routes", `the ${name} route is not FIX-1662's pinned shape`); + const tabs = { TASK_TABS: "session, diff, checks, brief", WORKSTREAM_TABS: "stream, board, brief, results", PROJECT_TABS: "stream, board, workstreams, brief" }; + for (const [name, want] of Object.entries(tabs)) { + const got = new RegExp(`${name} = \\[([^\\]]*)\\]`).exec(routes)?.[1]?.replace(/"/g, "").split(",").map((s) => s.trim()).join(", "); + if (got !== want) report.fail("P4:routes", `${name} is [${got}], pinned [${want}]`); + } + const heads = [...routes.matchAll(/head === "([a-z]+)"/g)].map((m) => m[1]!); + const levels = [...new Set([...routes.matchAll(/level: "([a-z]+)"/g)].map((m) => m[1]!))].sort(); + report.note(`P4 routes: task, workstream and project routes as pinned; route heads [${[...new Set(heads)].join(", ")}], levels [${levels.join(", ")}]; the task level's panel slot is graded in a3 (task-panel-slot holds the inspector)`); + + // One session write path (ER-15): every write Shift Manager makes, by call and by module. + const allowed: Record = { + "sendAction(": ["lib/send.ts", "lib/transcript.ts"], + "abortRequest(": ["lib/run.ts"], + "resumeSuspension(": ["lib/reads.ts"], + }; + const writes: string[] = []; + for (const file of own) { + const text = stripComments(readFileSync(file, "utf8")); + const rel = relative(src, file).replace(/\\/g, "/"); + for (const call of [...Object.keys(allowed), "createSession(", "appendItem(", "saveItem(", "/actions/"]) { + if (!text.includes(call)) continue; + writes.push(`${rel} ${call}`); + if (!(allowed[call] ?? []).includes(rel)) report.fail("P4:ER-15", `${rel} writes through ${call}, outside the doors ER-15 names`); + } + } + const transcriptPost = /sendAction\("post"/.test(readFileSync(join(src, "lib", "transcript.ts"), "utf8")); + if (!transcriptPost) report.fail("P4:ER-15", "lib/transcript.ts sends something other than the channel's post"); + report.note(`P4 ER-15: Shift Manager's writes are [${writes.join("; ")}]: the seat's door (send.ts), the channel's post (transcript.ts), Interrupt's abort (run.ts) and the one resume (reads.ts); Inbox's reply is graded by FIX-1690's check in part 3`); + + // One ask rendering: Inbox's detail and the stream's card draw through AskCard. + for (const surface of ["Inbox.tsx", "Stream.tsx", "ChiefOfStaff.tsx"]) { + const text = readFileSync(join(src, "surfaces", surface), "utf8"); + if (!/import \{ AskCard \} from "\.\.\/components\/AskCard"/.test(text) || !/ / relative(src, f)); + if (askRenderers.some((f) => !f.endsWith("AskCard.tsx"))) report.fail("P4:ask", `an ask is drawn outside AskCard: ${askRenderers.join(", ")}`); + report.note(`P4 one ask rendering: Inbox, Stream and Chief of Staff import AskCard; registry ask cards are drawn only in [${askRenderers.join(", ")}]; a1 compared the two cards' text on screen`); + + // Layer fence (ER-7, ER-8): the set's changes to core, engine, client and react. + const layerDiff = git("diff", `${base}..HEAD`, "--", "packages/core/src", "packages/engine/src", "packages/client/src", "packages/react/src"); + const nouns = layerDiff + .split("\n") + .filter((l) => l.startsWith("+") && !l.startsWith("+++")) + .filter((l) => /\b(?:export\s+)?(?:interface|type|class|function|const)\s+(Agent|Team|Channel|MessageBoard|Project)\b/.test(l)); + if (nouns.length > 0) report.fail("P4:fence", `an L1 noun added: ${nouns.slice(0, 3).join(" | ")}`); + const ds = JSON.parse(readFileSync(join(REPO_ROOT, "labs", "design-system", "package.json"), "utf8")) as Record | undefined>; + const dsDeps = Object.keys({ ...(ds.dependencies ?? {}), ...(ds.peerDependencies ?? {}) }); + if (dsDeps.some((d) => d.includes("workforce"))) report.fail("P4:fence", `the design-system package depends on ${dsDeps.join(", ")}`); + if (/workforce/.test(readFileSync(join(REPO_ROOT, "labs", "design-system", "shift-manager.css"), "utf8"))) report.fail("P4:fence", "the design-system stylesheet names Workforce"); + const added = git("diff", "--name-only", "--diff-filter=A", `${base}..HEAD`).split("\n").filter(Boolean); + const channelsMd = added.filter((f) => /(^|\/)CHANNELS\.md$/.test(f)); + if (channelsMd.length > 0) report.fail("P4:fence", `CHANNELS.md added: ${channelsMd.join(", ")}`); + const kindFront = git("diff", `${base}..HEAD`, "--", "*.md") + .split("\n") + .filter((l) => /^\+kind:\s/.test(l)); + if (kindFront.length > 0) report.fail("P4:fence", `\`kind:\` frontmatter added: ${kindFront.slice(0, 3).join(" | ")}`); + report.note(`P4 layer fence: ${layerDiff.split("\n").filter((l) => /^[+-][^+-]/.test(l)).length} changed lines under core/engine/client/react src since ${base.slice(0, 9)}, no Agent/Team/Channel/MessageBoard/Project noun; design-system deps [${dsDeps.join(", ")}]; no CHANNELS.md, no \`kind:\` frontmatter added`); + + // Final visuals (ER-9): the theme's final values merged after the final hand-back. + const handBack = git("log", "--diff-filter=A", "--format=%H", "HEAD", "--", "specs/epics/FIX-1649/assets/design/v2/README.md").trim().split("\n").at(-1) ?? ""; + const lastTheme = git("log", "-1", "--format=%H", "HEAD", "--", "labs/design-system/shift-manager.css").trim(); + if (handBack === "") report.fail("P4:visuals", "no final hand-back (assets/design/v2) is committed"); + else { + try { + execFileSync("git", ["merge-base", "--is-ancestor", handBack, lastTheme], { cwd: REPO_ROOT }); + } catch { + report.fail("P4:visuals", `the theme's last change ${lastTheme.slice(0, 9)} does not follow the hand-back's commit ${handBack.slice(0, 9)}`); + } + } + report.note(`P4 final visuals: hand-back v2 committed at ${handBack.slice(0, 9)}; shift-manager.css last changed at ${lastTheme.slice(0, 9)}, after it`); + + // Docs smoke (ER-14). + const labs = readFileSync(join(REPO_ROOT, "labs", "README.md"), "utf8"); + if (!/\[`shift-manager\/`\]\(shift-manager\)/.test(labs)) report.fail("P4:docs", "labs/README.md does not list Shift Manager"); + const readme = readFileSync(join(SHIFT_MANAGER, "README.md"), "utf8"); + for (const heading of ["## Run it", "## What a Lab's config provides", "## What you see", "## A task", "## Roster"]) { + if (!readme.includes(heading)) report.fail("P4:docs", `Shift Manager's README has no "${heading}"`); + } + report.note("P4 docs smoke: labs/README.md lists Shift Manager; its README says how to open a Lab and what each level shows (b0 and a3 followed it)"); +} diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts new file mode 100644 index 0000000000..7083e025cb --- /dev/null +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts @@ -0,0 +1,574 @@ +/** + * Goal check (epic closure): a Lab is reached and worked through one skinned + * shell. See goal.md for the contract; the plan it runs is FIX-1663's + * `PLAN.md`, read with the epic's 2026-10-01 amendment (design v2's + * structure: Chief of Staff, Roster, the Day / Night switch). + * + * A thin driver over one commit, in the plan's order: + * + * part 1 legs a (DevForce, real model on a4), b0 (the pentest config + * written from Shift Manager's README by an isolated writer), b + * (pentest, keyless, plus every Lab opening under an org) and c + * (no theme, `--shift day` then `--shift night`, plus the static + * fence over packages/) + * controls each on its own build or start; each must fail its own leg at + * its own signal and leave the rest green + * part 2 J3 (FSD UI reused in a fresh app) and J4 (a sibling's surfaces + * open by address) + * part 3 every child's goal check, with its controls, and the goal labs' + * checks, by subprocess; `pnpm typecheck` and `pnpm test` + * part 4 the seams + * + * Every verdict is printed as `VERDICT : …` with the commit it ran on. + * + * Run: PLAYWRIGHT_BROWSERS_PATH=/opt/pw-browsers pnpm tsx goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts + * Parts: GOAL_PART=a,b0,b,c,controls,part2,part3,part4 (default: all, in that order) + * Controls: GOAL_CONTROLS=hardcoded-accent,… (default: all of them) + * Needs: a model key (leg a, and the real-model child checks), a signed-in + * Claude Code (a4's harness, and b0's writer through the `claude` + * CLI), Chromium, and `pnpm build:assets` for the devtool pages. + */ +import { execFileSync, spawn } from "node:child_process"; +import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; +import { REPO_ROOT, goalTmpDir, runGoal } from "../../lib/index.mts"; +import { readShiftManagerTheme } from "../../lib/colour.mts"; +import { launchChromium } from "../../lib/playwright.mts"; +import { PENTEST_CONFIG, TREES, legA, legB, legC, staticFence, type LegCtx, type Report } from "./legs.mts"; +import { j3, j4, part4 } from "./parts.mts"; +import { SHIFT_MANAGER, buildPages, injected, labApi, open, readStore, readTree, startShiftManager, type Built, type Patch, type Swap } from "./shell.mts"; + +const HERE = fileURLToPath(new URL(".", import.meta.url)); +const SCRATCH = goalTmpDir("shift-manager-closure"); +const PARTS = (process.env.GOAL_PART ?? "a,b0,b,c,controls,part2,part3,part4").split(",").map((s) => s.trim()); +const git = (...args: string[]) => execFileSync("git", args, { cwd: REPO_ROOT, encoding: "utf8" }).trim(); + +const COMMIT = git("rev-parse", "HEAD"); +const DIRTY = git("status", "--porcelain", "--", ".", `:(exclude)${relative(REPO_ROOT, HERE)}`) !== ""; +const AT = `${COMMIT.slice(0, 9)}${DIRTY ? "+wip" : ""}`; + +/** The commit before FIX-1662's first merge: today's main, as the epic's control. */ +const TODAYS_MAIN = (() => { + const merge = git("log", "--first-parent", "--diff-filter=A", "--format=%H", "HEAD", "--", "labs/app-lab/package.json").split("\n").at(-1)!; + return git("rev-parse", `${merge}^1`); +})(); + +// ---- reporting ----------------------------------------------------------------- + +type Failure = { signal: string; why: string }; +/** A fresh report: failures by signal, and notes for the evidence. */ +function collector(): Report & { failures: Failure[]; notes: string[] } { + const failures: Failure[] = []; + const notes: string[] = []; + return { failures, notes, fail: (signal, why) => failures.push({ signal, why }), note: (line) => notes.push(line) }; +} + +const verdicts: Array<{ id: string; ok: boolean; line: string }> = []; +function verdict(id: string, ok: boolean, line: string, detail: string[] = []): void { + verdicts.push({ id, ok, line }); + console.log(`VERDICT ${id} @ ${AT}: ${line}`); + for (const d of detail) console.log(` ${d}`); +} + +/** Report one leg's own result: PASS, or FAIL with each failure. */ +function legVerdict(id: string, prefix: string[], report: ReturnType): void { + const mine = report.failures.filter((f) => prefix.some((p) => f.signal === p || f.signal.startsWith(`${p}:`))); + const notes = report.notes.filter((n) => prefix.some((p) => n.startsWith(`${p}:`) || n.startsWith(`${p} `))); + verdict(id, mine.length === 0, mine.length === 0 ? "PASS" : `FAIL (${mine.length})`, [...mine.map((f) => `✗ [${f.signal}] ${f.why}`), ...notes]); +} + +// ---- builds -------------------------------------------------------------------- + +const THEME_IMPORT = /^@import "@flow-state-dev\/design-system\/shift-manager\.css";\n/m; +const NO_THEME: Patch = { file: "src/styles.css", from: THEME_IMPORT, to: "", why: "the design-system import line removed (leg c)" }; +const ACCENT = readShiftManagerTheme().attentionLight; +const HARDCODED_ACCENT: Patch = { + file: "src/components/flow-state/tool.tsx", + from: /CheckCircleIcon className="size-4 text-success"/g, + to: `CheckCircleIcon className="size-4 text-[${ACCENT}]"`, + why: `control hardcoded-accent: Shift Manager's copy of the tool card paints its completed icon with Shift Manager's accent ${ACCENT} as a literal`, +}; +const NO_ORG: Patch = { + file: "src/surfaces/Sidebar.tsx", + from: "", + to: '', + why: "control no-org: Shift Manager renders with no org, the org switcher empty", +}; +const CHILD = (goal: string, file: string) => join(REPO_ROOT, "goals", "shift-manager", goal, "controls", file); +const swapOf = (target: string, goal: string, file: string): Swap => ({ target: join(SHIFT_MANAGER, "src", "lib", target), with: CHILD(goal, file) }); + +/** + * A build with a module swapped in and the theme import removed in the + * bundler, in a child process: the scratch-copy route can't take a swap (the control module + * imports the checkout's sources), and removing a stylesheet import changes + * no class name Tailwind reads off disk. + */ +async function swapBuild(name: string, swap: Swap, noTheme: boolean, staticSeats?: Array<{ id: string; kind: string }>): Promise { + if (!noTheme) return buildPages(SCRATCH, name, { swap, staticSeats }); + // In a process of its own: Tailwind's Vite plugin keeps a stylesheet's + // compiled CSS per file across builds in one process, so this build would + // otherwise ship the themed build's CSS for the same \`src/styles.css\`. + const pages = join(SCRATCH, name, "pages"); + const script = join(SCRATCH, name, "build.mts"); + mkdirSync(join(SCRATCH, name), { recursive: true }); + writeFileSync( + script, + `import { createRequire } from "node:module"; +import { readFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; +const [root, outDir, target, withFile, seats] = ${JSON.stringify([SHIFT_MANAGER, pages, swap.target, swap.with, staticSeats ?? []])}; +const THEME_IMPORT = ${THEME_IMPORT.toString()}; +const vite = await import(pathToFileURL(createRequire(root + "/package.json").resolve("vite")).href); +let swapped = 0; +let stripped = 0; +await vite.build({ + root, + configFile: root + "/vite.config.ts", + logLevel: "error", + build: { outDir, emptyOutDir: true }, + define: { __STATIC_SEATS__: JSON.stringify(seats) }, + plugins: [ + { + name: "goal-control-swap", + enforce: "pre", + async resolveId(source, importer, opts) { + if (importer === undefined || importer === withFile) return null; + const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true }); + if (resolved?.id !== target) return null; + swapped += 1; + return withFile; + }, + }, + { + name: "goal-no-theme", + enforce: "pre", + load(id) { + if (id.includes("?") || !id.endsWith("/src/styles.css")) return null; + const code = readFileSync(id, "utf8"); + const out = code.replace(THEME_IMPORT, ""); + if (out !== code) stripped += 1; + return out; + }, + }, + ], +}); +if (swapped === 0) throw new Error("the build never imported " + target); +if (stripped === 0) throw new Error("the theme import was never removed"); +`, + ); + try { + execFileSync(join(REPO_ROOT, "node_modules", ".bin", "tsx"), [script], { cwd: REPO_ROOT, encoding: "utf8", stdio: "pipe", maxBuffer: 64 * 1024 * 1024 }); + } catch (error) { + throw new Error(`setup [${name}]: ${String((error as { stderr?: string }).stderr ?? error).trim().split("\n").slice(-3).join(" ")}`); + } + const css = readdirSync(join(pages, "assets")).filter((f) => f.endsWith(".css")).map((f) => readFileSync(join(pages, "assets", f), "utf8")).join("\n"); + if (/Space Grotesk/i.test(css)) throw new Error(`setup [${name}]: the no-theme build still ships the Shift Manager theme`); + return { pages, diff: `# the design-system import line removed in the bundler (src/styles.css), plus ${relative(REPO_ROOT, swap.with)} in place of ${relative(REPO_ROOT, swap.target)}` }; +} + +// ---- b0: the pentest config, from the README alone ------------------------------- + +/** + * b0. An isolated writer (the `claude` CLI, in a scratch directory holding + * only Shift Manager's README and a copy of the pentest Lab with its config + * removed, no project instructions) writes a config and lists what it had to + * guess. The run boots Shift Manager over it once, then compares what it boots + * with what the committed config boots: flows, the org, the inventory, who + * the page reads as. A semantic difference, a failed boot, or a guessed step + * is a finding. + */ +async function b0(report: Report): Promise { + const fail = (why: string) => report.fail("b0", why); + const room = join(SCRATCH, "b0-writer"); + rmSync(room, { recursive: true, force: true }); + mkdirSync(room, { recursive: true }); + cpSync(join(SHIFT_MANAGER, "README.md"), join(room, "SHIFT-MANAGER-README.md")); + const labDir = join(REPO_ROOT, "goals", "pentest-lab", "lab"); + cpSync(labDir, join(room, "pentest-lab", "lab"), { recursive: true, filter: (src) => src !== PENTEST_CONFIG }); + const prompt = [ + "You are opening a Lab in Shift Manager for the first time. You have two things and nothing else:", + "SHIFT-MANAGER-README.md (Shift Manager's README) and the Lab's tree under pentest-lab/lab/.", + "Following the README, write the one file the README says a Lab needs so Shift Manager can open it:", + "pentest-lab/lab/fsdev.config.mts. It must default-export what the README asks for. Use the Lab's own code", + "where it helps; edit nothing else. Read only files in this directory.", + "When done, reply with one line per step the README did not tell you and you had to guess, each starting", + "'GUESSED: ', or the single line 'GUESSED: none'.", + ].join(" "); + const env = { ...process.env }; + for (const key of ["CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD", "CLAUDE_ADDITIONAL_DIRECTORIES"]) delete env[key]; + let reply = ""; + try { + reply = execFileSync("claude", ["-p", prompt, "--allowedTools", "Read,Glob,Grep,Write", "--disallowedTools", "Bash,WebFetch,WebSearch", "--max-turns", "40"], { + cwd: room, + env, + encoding: "utf8", + timeout: 15 * 60_000, + maxBuffer: 16 * 1024 * 1024, + }); + } catch (error) { + return fail(`blocked: the writer did not run (${String((error as Error).message).split("\n")[0]})`); + } + const written = join(room, "pentest-lab", "lab", "fsdev.config.mts"); + if (!existsSync(written)) return fail("the writer wrote no fsdev.config.mts"); + const guesses = reply.split("\n").filter((l) => l.startsWith("GUESSED:")).map((l) => l.slice("GUESSED:".length).trim()).filter((g) => g !== "none"); + for (const guess of guesses) fail(`the writer had to guess: ${guess}`); + const text = readFileSync(written, "utf8"); + report.note(`b0: the writer's config (${text.split("\n").length} lines), kept at ${written}:\n${text.split("\n").map((l) => ` | ${l}`).join("\n")}`); + const devteam = readFileSync(join(SHIFT_MANAGER, "teams", "devteam", "fsdev.config.mts"), "utf8"); + report.note(`b0: lines that differ from DevTeam's config:\n${lineDiff(devteam, text).map((l) => ` ${l}`).join("\n")}`); + + // Boot it once, beside the committed config so its relative imports resolve, and compare what each boots. + const beside = join(labDir, ".b0-writer.fsdev.config.mts"); + writeFileSync(beside, text); + try { + const browser = await launchChromium(); + try { + const boot = async (config: string, label: string) => { + const served = await startShiftManager(SCRATCH, label, { config, pages: PAGES!.pages, env: { AI_GATEWAY_API_KEY: "", OPENAI_API_KEY: "", OPENROUTER_API_KEY: "", ANTHROPIC_API_KEY: "" } }); + const page = await browser.newPage(); + try { + await open(page, served.origin, "/"); + const who = await injected(page); + const api = labApi(served.origin, who.bearer); + const store = await readStore(api, await readTree(TREES.pentest), who.userId); + const listed = await api.get(""); + const flows = (Array.isArray(listed) ? listed : (listed?.flows ?? [])) as Array<{ id?: string; kind?: string }>; + return { + flows: flows.map((f) => String(f.id ?? f.kind)).sort(), + orgs: store.orgs, + seats: store.seats, + channels: store.channels.map((c) => `${c.id}[${c.members.join(",")}]`), + userId: who.userId, + bearer: who.bearer !== undefined, + }; + } finally { + await page.close(); + await served.stop(); + } + }; + let theirs: Awaited>; + try { + theirs = await boot(beside, "b0-writer"); + } catch (error) { + return fail(`Shift Manager does not boot over the writer's config: ${String((error as Error).message).split("\n").slice(0, 4).join(" ")}`); + } + const ours = await boot(PENTEST_CONFIG, "b0-committed"); + for (const key of Object.keys(ours) as Array) { + const a = JSON.stringify(ours[key]); + const b = JSON.stringify(theirs[key]); + if (a !== b) fail(`the writer's config boots a different ${key}: ${b}, the committed config ${a}`); + } + report.note(`b0: booted with the README's command over the writer's copy; both configs boot ${ours.flows.length} flows, org [${ours.orgs.join(", ")}], seats [${ours.seats.join(", ")}], workstreams [${ours.channels.join(", ")}], page as ${ours.userId}${ours.bearer ? " with a bearer" : ""}`); + } finally { + await browser.close(); + } + } finally { + rmSync(beside, { force: true }); + } +} + +/** A plain line diff: lines only in `a` as `-`, only in `b` as `+`. */ +function lineDiff(a: string, b: string): string[] { + const left = new Set(a.split("\n").map((l) => l.trim()).filter(Boolean)); + const right = new Set(b.split("\n").map((l) => l.trim()).filter(Boolean)); + return [...[...left].filter((l) => !right.has(l)).map((l) => `- ${l}`), ...[...right].filter((l) => !left.has(l)).map((l) => `+ ${l}`)]; +} + +// ---- controls -------------------------------------------------------------------- + +type Control = { + name: string; + /** Builds: one for legs a and b, one (no theme) for leg c. */ + build: () => Promise<{ themed: Built; noTheme: Built }>; + /** The signals that must go red. Anything else red is a finding. */ + must: string[]; + /** Signals allowed to go red with `must` (none unless a goal names the co-failure). */ + also?: string[]; + legs: Array<"a" | "b" | "c">; +}; + +async function controls(only: string[] | null): Promise { + const devforceSeats = (await readDeclaredRoster(TREES.devforce)).workers.map((w) => ({ id: w.id, kind: String(w.declared.flow) })); + const all: Control[] = [ + { + name: "hardcoded-accent", + build: async () => ({ + themed: await buildPages(SCRATCH, "ctl-hardcoded-accent-themed", { patches: [HARDCODED_ACCENT] }), + noTheme: await buildPages(SCRATCH, "ctl-hardcoded-accent-no-theme", { patches: [NO_THEME, HARDCODED_ACCENT] }), + }), + must: ["c:tool"], + legs: ["a", "b", "c"], + }, + { + name: "static-names", + build: async () => { + const swap = swapOf("reads.ts", "it-opens-a-lab", "static-names.ts"); + return { themed: await swapBuild("ctl-static-names", swap, false, devforceSeats), noTheme: await swapBuild("ctl-static-names-no-theme", swap, true, devforceSeats) }; + }, + must: ["b:teams"], + // Jump to's Workers list is the same written-in seat list TEAMS draws. + also: ["b:reach"], + legs: ["a", "b", "c"], + }, + { + name: "optimistic-post", + build: async () => { + const swap = swapOf("transcript.ts", "it-opens-a-lab", "optimistic-post.ts"); + return { themed: await swapBuild("ctl-optimistic-post", swap, false), noTheme: await swapBuild("ctl-optimistic-post-no-theme", swap, true) }; + }, + must: ["a4", "b:post"], + legs: ["a", "b", "c"], + }, + { + name: "worker-session", + build: async () => { + const swap = swapOf("run.ts", "it-shows-and-stops-a-task-run", "worker-session.ts"); + return { themed: await swapBuild("ctl-worker-session", swap, false), noTheme: await swapBuild("ctl-worker-session-no-theme", swap, true) }; + }, + must: ["a2"], + // Leg c draws its message, reasoning, tool and code block cards through + // the run-lab's task Session, which this control points elsewhere. + also: ["c:sweep"], + legs: ["a", "b", "c"], + }, + { + name: "no-org", + build: async () => ({ + themed: await buildPages(SCRATCH, "ctl-no-org-themed", { patches: [NO_ORG] }), + noTheme: await buildPages(SCRATCH, "ctl-no-org-no-theme", { patches: [NO_THEME, NO_ORG] }), + }), + must: ["b:org"], + legs: ["a", "b", "c"], + }, + ]; + + // Today's main: Shift Manager is absent, so legs a and b can't start; c's static half stays green. + if (only === null || only.includes("todays-main")) { + const absent = ["labs/shift-manager/package.json", "labs/app-lab/package.json"].every((p) => { + try { + git("cat-file", "-e", `${TODAYS_MAIN}:${p}`); + return false; + } catch { + return true; + } + }); + const report = collector(); + const tree = join(SCRATCH, "todays-main"); + rmSync(tree, { recursive: true, force: true }); + mkdirSync(tree, { recursive: true }); + execFileSync("sh", ["-c", `git archive ${TODAYS_MAIN} packages | tar -x -C ${tree}`], { cwd: REPO_ROOT }); + staticFence(join(tree, "packages"), "c:static", report); + const staticGreen = report.failures.length === 0; + verdict( + "control today's-main", + absent && staticGreen, + absent && staticGreen ? `FAIL (expected) at ${TODAYS_MAIN.slice(0, 9)}: legs a and b, Shift Manager is absent; c's static half green` : `WRONG: Shift Manager absent ${absent}, static half green ${staticGreen}`, + [...report.failures.map((f) => `✗ [${f.signal}] ${f.why}`), ...report.notes], + ); + } + + for (const control of all) { + if (only !== null && !only.includes(control.name)) continue; + const report = collector(); + let built: { themed: Built; noTheme: Built }; + try { + built = await control.build(); + } catch (error) { + verdict(`control ${control.name}`, false, `WRONG: failed at setup: ${String((error as Error).message).split("\n")[0]}`); + continue; + } + const browser = await launchChromium(); + try { + const ctx = (pages: string): LegCtx => ({ scratch: join(SCRATCH, `ctl-${control.name}`), pages, browser, report }); + for (const leg of control.legs.filter((l) => process.env.GOAL_CONTROL_LEGS === undefined || process.env.GOAL_CONTROL_LEGS.split(",").includes(l))) { + try { + if (leg === "a") await legA(ctx(built.themed.pages)); + if (leg === "b") await legB(ctx(built.themed.pages)); + if (leg === "c") await legC(ctx(built.noTheme.pages)); + } catch (error) { + const at = String((error as Error).stack ?? "").split("\n").find((l) => l.includes(HERE)) ?? ""; + report.fail(`${leg}:setup`, `${String((error as Error).message).split("\n")[0]!}${at === "" ? "" : ` (${relative(HERE, at.trim().replace(/^at .*\(|\)$/g, "").replace(/^at /, ""))})`}`); + } + } + } finally { + await browser.close(); + } + const red = new Set(report.failures.map((f) => f.signal)); + const missing = control.must.filter((s) => !red.has(s)); + const stray = [...red].filter((s) => !control.must.includes(s) && !(control.also ?? []).includes(s)); + const ok = missing.length === 0 && stray.length === 0; + verdict( + `control ${control.name}`, + ok, + ok ? `FAIL (expected) at ${control.must.join(" + ")} only` : `WRONG: ${missing.length > 0 ? `stayed green at ${missing.join(", ")}` : ""}${missing.length > 0 && stray.length > 0 ? "; " : ""}${stray.length > 0 ? `also red at ${stray.join(", ")}` : ""}`, + [ + ...report.failures.map((f) => `✗ [${f.signal}] ${f.why}`), + ...[built.themed.diff, built.noTheme.diff].filter(Boolean).map((d) => `patch:\n${d}`), + ...report.notes.filter((n) => /^a4|^b:org|^b:/.test(n)), + ], + ); + } +} + +// ---- part 3: every child's check, by subprocess ----------------------------------- + +type Child = { id: string; run: string; control?: string; env?: Record; must?: RegExp; allowed?: RegExp }; + +const SM = (goal: string) => `goals/shift-manager/${goal}/run.mts`; +const CHILDREN: Child[] = [ + // P3.1: FIX-1655. + { id: "P3.1 design-system", run: "goals/design-system/skins-reused-components-from-one-token-set/run.mts" }, + { id: "P3.1 design-system", run: "goals/design-system/skins-reused-components-from-one-token-set/run.mts", control: "hardcoded-accent", must: /b:themed[^\n]*tool:awaiting/, allowed: /tool:awaiting|b:themed summary — 1 components: tool\.tsx/ }, + // P3.2: each child's merged goal check, with its controls. + { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab") }, + { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab"), control: "static-names", must: /\[multi-seat-collab\] TEAMS equals the store's seats/, allowed: /\[multi-seat-collab\] TEAMS equals the store's seats/ }, + { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab"), control: "optimistic-post", must: /the post is in the stored transcript/, allowed: /the post is in the stored transcript/ }, + { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab"), control: "unanswerable-asks", must: /an answer from Inbox lands in the store/, allowed: /an answer from Inbox lands in the store/ }, + { id: "P3.2 FIX-1664 it-shows-and-stops-a-task-run", run: SM("it-shows-and-stops-a-task-run") }, + { id: "P3.2 FIX-1664 it-shows-and-stops-a-task-run", run: SM("it-shows-and-stops-a-task-run"), control: "worker-session", must: /items equal the run session's/, allowed: /items equal the run session's|\blive\b/ }, + { id: "P3.2 FIX-1664 it-shows-and-stops-a-task-run", run: SM("it-shows-and-stops-a-task-run"), control: "optimistic-interrupt", must: /the request reads aborted first/, allowed: /the request reads aborted first/ }, + { id: "P3.2 FIX-1664 it-shows-and-stops-a-task-run", run: SM("it-shows-and-stops-a-task-run"), control: "board-flow", must: /items equal the run session's/, allowed: /./ }, + { id: "P3.2 FIX-1688/1689/1725 it-takes-its-look-from-the-design-system", run: SM("it-takes-its-look-from-the-design-system") }, + { id: "P3.2 FIX-1688/1689/1725 it-takes-its-look-from-the-design-system", run: SM("it-takes-its-look-from-the-design-system"), control: "hardcoded-accent", must: /\] neutral .*tool:/, allowed: /\] neutral .*tool:/ }, + { id: "P3.2 FIX-1688/1689/1725 it-takes-its-look-from-the-design-system", run: SM("it-takes-its-look-from-the-design-system"), control: "switch-ignored", must: /\] switch /, allowed: /\] switch / }, + { id: "P3.2 FIX-1690 it-sends-a-turn-into-a-seat-session", run: SM("it-sends-a-turn-into-a-seat-session") }, + { id: "P3.2 FIX-1690 it-sends-a-turn-into-a-seat-session", run: SM("it-sends-a-turn-into-a-seat-session"), control: "optimistic-turn", must: /\] delivered:/, allowed: /\] (delivered|stopped|continued|standing|heard):/ }, + { id: "P3.2 FIX-1690 it-sends-a-turn-into-a-seat-session", run: SM("it-sends-a-turn-into-a-seat-session"), control: "fresh-session", must: /\] continued:/, allowed: /\] continued:/ }, + { id: "P3.2 FIX-1722 it-briefs-and-talks-with-the-chief-of-staff", run: SM("it-briefs-and-talks-with-the-chief-of-staff") }, + { id: "P3.2 FIX-1722 it-briefs-and-talks-with-the-chief-of-staff", run: SM("it-briefs-and-talks-with-the-chief-of-staff"), control: "optimistic-reply", must: /\[desk\] talk/, allowed: /\[desk\] talk/ }, + { id: "P3.2 FIX-1722 it-briefs-and-talks-with-the-chief-of-staff", run: SM("it-briefs-and-talks-with-the-chief-of-staff"), control: "static-brief", must: /\[desk\] inline/, allowed: /\[desk\] inline/ }, + { id: "P3.2 FIX-1723 it-shows-who-is-on-shift", run: SM("it-shows-who-is-on-shift") }, + { id: "P3.2 FIX-1723 it-shows-who-is-on-shift", run: SM("it-shows-who-is-on-shift"), control: "ignore-asks", must: /\] status/, allowed: /\] (status|summary|sidebar|TEAMS)/ }, + { id: "P3.2 FIX-1723 it-shows-who-is-on-shift", run: SM("it-shows-who-is-on-shift"), control: "count-queued", must: /\] slots/, allowed: /\] (slots|holding)/ }, + { id: "P3.2 FIX-1717 it-hands-a-run-the-work-it-approved", run: SM("it-hands-a-run-the-work-it-approved") }, + { id: "P3.2 FIX-1717 it-hands-a-run-the-work-it-approved", run: SM("it-hands-a-run-the-work-it-approved"), control: "drop-task", must: /does not carry the approved/, allowed: /does not carry the (approved|posted) goal|does not carry the goal's token/ }, + // D1's children. + { id: "P3.2 FIX-1666 it-waits-for-a-person-before-it-files", run: "goals/devforce-lab/it-waits-for-a-person-before-it-files/run.mts" }, + { id: "P3.2 FIX-1666 it-waits-for-a-person-before-it-files", run: "goals/devforce-lab/it-waits-for-a-person-before-it-files/run.mts", control: "no-gate", must: /a row existed before any approval/, allowed: /./ }, + { id: "P3.2 FIX-1667 it-keeps-its-rows-on-the-channels-board", run: "goals/devforce-lab/it-keeps-its-rows-on-the-channels-board/run.mts" }, + { id: "P3.2 FIX-1667 it-keeps-its-rows-on-the-channels-board", run: "goals/devforce-lab/it-keeps-its-rows-on-the-channels-board/run.mts", control: "kind-ledger", must: /the channel's board returned no rows/, allowed: /./ }, + // P3.3: the goal labs the set touched. + { id: "P3.3 devforce-lab it-wakes-the-seat-a-file-declared", run: "goals/devforce-lab/it-wakes-the-seat-a-file-declared/run.mts" }, + { id: "P3.3 devforce-lab it-commits-from-the-seats-own-file", run: "goals/devforce-lab/it-commits-from-the-seats-own-file/run.mts" }, + { id: "P3.3 devforce-lab it-ships-an-artifact-a-person-can-open", run: "goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts" }, + { id: "P3.3 pentest-lab a-post-reaches-both-declared-seats", run: "goals/pentest-lab/a-post-reaches-both-declared-seats/run.mts" }, + { id: "P3.3 pentest-lab a-seat-answers-from-its-own-document", run: "goals/pentest-lab/a-seat-answers-from-its-own-document/run.mts" }, + { id: "P3.3 multi-seat-collab it-hands-a-row-between-two-seats-in-view", run: "goals/multi-seat-collab/it-hands-a-row-between-two-seats-in-view/run.mts" }, +]; + +/** Run one command to its end, keeping its output in a log beside the scratch builds. */ +function runLogged(label: string, cmd: string, args: string[], env: Record): Promise<{ code: number; out: string; log: string }> { + const log = join(SCRATCH, "part3", `${label.replace(/[^a-z0-9.-]+/gi, "_")}.log`); + mkdirSync(join(SCRATCH, "part3"), { recursive: true }); + return new Promise((resolve) => { + let out = ""; + const merged: Record = { ...process.env, ...env }; + for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]; + const child = spawn(cmd, args, { cwd: REPO_ROOT, env: merged as NodeJS.ProcessEnv, stdio: ["ignore", "pipe", "pipe"] }); + child.stdout.on("data", (d) => (out += String(d))); + child.stderr.on("data", (d) => (out += String(d))); + child.on("exit", (code) => { + writeFileSync(log, out); + resolve({ code: code ?? 1, out, log }); + }); + }); +} + +const failBullets = (out: string) => { + const at = out.lastIndexOf("FAIL —"); + return at < 0 ? [] : out.slice(at).split("\n").filter((l) => /^\s+- /.test(l)).map((l) => l.replace(/^\s+- /, "")); +}; +const verdictLine = (out: string) => out.split("\n").reverse().find((l) => /^(PASS|FAIL) —/.test(l)) ?? ""; + +async function part3(): Promise { + const tsx = join(REPO_ROOT, "node_modules", ".bin", "tsx"); + // GOAL_CHILDREN narrows part 3 to the entries whose label matches it (a rerun); unset runs them all. + const pick = process.env.GOAL_CHILDREN === undefined ? null : new RegExp(process.env.GOAL_CHILDREN); + for (const child of CHILDREN) { + const label = `${child.id}${child.control === undefined ? "" : ` GOAL_CONTROL=${child.control}`}`; + if (pick !== null && !pick.test(label)) continue; + const { code, out, log } = await runLogged(label, tsx, [child.run], { GOAL_CONTROL: child.control, ...(child.env ?? {}) }); + const bullets = failBullets(out); + if (child.control === undefined) { + verdict(label, code === 0, code === 0 ? `PASS — ${verdictLine(out).slice(7, 400)}` : `FAIL (${bullets.length})`, [...bullets.slice(0, 12).map((b) => `✗ ${b}`), `log: ${log}`]); + } else { + const hit = bullets.some((b) => child.must!.test(b)) || child.must!.test(out.slice(out.lastIndexOf("FAIL —"))); + const strays = bullets.filter((b) => !child.allowed!.test(b)); + const ok = code !== 0 && hit && strays.length === 0; + verdict(label, ok, ok ? `FAIL (expected) — ${bullets.length} bullet(s) at its named signal` : `WRONG: exit ${code}, named signal ${hit ? "red" : "green"}, ${strays.length} stray`, [ + ...bullets.slice(0, 8).map((b) => `✗ ${b}`), + ...strays.slice(0, 5).map((b) => `stray: ${b}`), + `log: ${log}`, + ]); + } + } + // P3.1's CI half, and P3.3's whole-repo checks. + for (const [label, args] of [ + ["P3.1 design-system static fence", ["--filter", "@flow-state-dev/design-system", "test"]], + ["P3.1 registry drift and palette census", ["--filter", "@flow-state-dev/ui", "exec", "vitest", "run", "test/registry-drift.test.ts", "test/palette-census.test.ts"]], + ["P3.1 Shift Manager's copies unedited", ["--filter", "@flow-state-dev/shift-manager", "exec", "vitest", "run", "test/static.test.ts"]], + ["P3.3 pnpm typecheck", ["typecheck"]], + ["P3.3 pnpm test", ["test"]], + ] as const) { + if (pick !== null && !pick.test(label)) continue; + const { code, out, log } = await runLogged(label, "pnpm", [...args], {}); + const tail = out.trim().split("\n").filter((l) => /Tests?|passed|failed|Tasks:|error/i.test(l)).slice(-3).join(" · "); + verdict(label, code === 0, code === 0 ? `PASS — ${tail.slice(0, 300)}` : `FAIL — exit ${code}: ${tail.slice(0, 300)}`, [`log: ${log}`]); + } +} + +// ---- the run --------------------------------------------------------------------- + +let PAGES: Built | undefined; + +await runGoal(async () => { + console.log(`closure run on ${COMMIT}${DIRTY ? " (with uncommitted changes outside this goal)" : ""}; today's main is ${TODAYS_MAIN}`); + const want = (part: string) => PARTS.includes(part); + if (["a", "b0", "b", "c", "part2"].some(want)) { + PAGES = await buildPages(SCRATCH, "as-written"); + } + const noTheme = want("c") ? await buildPages(SCRATCH, "no-theme", { patches: [NO_THEME] }) : undefined; + if (noTheme !== undefined) console.log(`leg c's no-theme build, the whole patch:\n${noTheme.diff}`); + + const report = collector(); + const browser = await launchChromium(); + try { + const ctx = (pages: string): LegCtx => ({ scratch: SCRATCH, pages, browser, report }); + const leg = async (id: string, prefixes: string[], run: () => Promise) => { + try { + await run(); + } catch (error) { + report.fail(`${prefixes[0]}:setup`, String((error as Error).message ?? error).split("\n").slice(0, 3).join(" ")); + } + legVerdict(id, prefixes, report); + }; + if (want("a")) await leg("leg a (a1-a4)", ["a1", "a2", "a3", "a4", "a"], () => legA(ctx(PAGES!.pages))); + if (want("b0")) await leg("b0", ["b0"], () => b0(report)); + if (want("b")) await leg("leg b", ["b"], () => legB(ctx(PAGES!.pages))); + if (want("c")) await leg("leg c", ["c"], () => legC(ctx(noTheme!.pages))); + if (want("part2")) { + await leg("J3", ["J3"], () => j3(SCRATCH, browser, report)); + await leg("J4", ["J4"], () => j4(SCRATCH, PAGES!.pages, browser, report)); + } + } finally { + await browser.close(); + } + if (want("controls")) { + const only = process.env.GOAL_CONTROLS?.split(",").map((s) => s.trim()) ?? null; + await controls(only); + } + if (want("part3")) await part3(); + if (want("part4")) { + const p4 = collector(); + part4(TODAYS_MAIN, p4); + legVerdict("part 4", ["P4"], p4); + } + + const bad = verdicts.filter((v) => !v.ok); + return { + failures: bad.map((v) => `${v.id}: ${v.line}`), + evidence: `${verdicts.length} verdicts on ${AT}, all as expected: ${verdicts.map((v) => `${v.id} ${v.line.split(" — ")[0]}`).join("; ")}`, + }; +}); diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts new file mode 100644 index 0000000000..57c2b5a82c --- /dev/null +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts @@ -0,0 +1,456 @@ +/** + * The closure check's scaffolding: building Shift Manager (as written, with a + * scratch patch, or with a control module swapped in), serving it over a Lab + * with its own start script, reading the Lab's store through its HTTP routes, + * and reading what Chromium paints. + * + * Every piece is lifted from the child checks under `goals/shift-manager/` + * (`it-opens-a-lab` for the swap build, the start script and the store reads; + * `it-takes-its-look-from-the-design-system` for the scratch-copy build and + * the colour sweep; `it-sends-a-turn-into-a-seat-session` for watching a + * composer settle). Their run files execute on import, so the helpers are + * lifted here rather than imported. The grading lives in `legs.mts`. + */ +import { execFileSync, spawn, type ChildProcess } from "node:child_process"; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import type { Page } from "playwright"; +import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; +import { REPO_ROOT, intentFreeEnv } from "../../lib/index.mts"; + +/** Shift Manager's package, in this checkout. */ +export const SHIFT_MANAGER = join(REPO_ROOT, "labs", "shift-manager"); +const TSX = join(REPO_ROOT, "node_modules", ".bin", "tsx"); + +export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const sorted = (values: Iterable) => [...values].sort(); +/** Whether two lists hold the same values, order aside. */ +export const same = (a: Iterable, b: Iterable) => JSON.stringify(sorted(a)) === JSON.stringify(sorted(b)); +/** What `got` lacks and adds against `want`. */ +export const diff = (want: Iterable, got: Iterable) => { + const w = new Set(want); + const g = new Set(got); + return `missing [${[...w].filter((x) => !g.has(x)).join(", ")}], extra [${[...g].filter((x) => !w.has(x)).join(", ")}]`; +}; + +// ---- building ---------------------------------------------------------------- + +/** One edit to a scratch copy of Shift Manager. A patch that matches nothing fails the setup. */ +export type Patch = { file: string; from: string | RegExp; to: string; why: string }; +/** A source module swapped for a control module at build time (a child check's control). */ +export type Swap = { target: string; with: string }; +/** A build: where its pages are, and the full diff of every patch applied to it. */ +export type Built = { pages: string; diff: string }; + +async function vite() { + return (await import(pathToFileURL(createRequire(join(SHIFT_MANAGER, "package.json")).resolve("vite")).href)) as { + build(config: Record): Promise; + }; +} + +/** + * Build Shift Manager's pages into `scratch/`. + * + * - With `patches`, Shift Manager is copied to scratch and patched there, + * never in the checkout (Tailwind reads class names off the files on disk, + * so a patch has to land in a copy). The diff of every patched file is + * returned in full, for the report. + * - With `swap`, the build runs from the checkout and one module is swapped + * for a control module, as the child checks' controls do. The build fails + * if the swap never fired. + * - `staticSeats` feeds the `static-names` control module its written-in list. + */ +export async function buildPages( + scratch: string, + name: string, + options: { patches?: Patch[]; swap?: Swap; staticSeats?: Array<{ id: string; kind: string }> } = {}, +): Promise { + const pages = join(scratch, name, "pages"); + const define = { __STATIC_SEATS__: JSON.stringify(options.staticSeats ?? []) }; + const patches = options.patches ?? []; + if (patches.length === 0) { + let swapped = 0; + const swap = options.swap; + await (await vite()).build({ + root: SHIFT_MANAGER, + configFile: join(SHIFT_MANAGER, "vite.config.ts"), + logLevel: "error", + build: { outDir: pages, emptyOutDir: true }, + define, + plugins: + swap === undefined + ? [] + : [ + { + name: "goal-control-swap", + enforce: "pre", + async resolveId(this: any, source: string, importer: string | undefined, opts: Record) { + if (importer === undefined || importer === swap.with) return null; + const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true }); + if (resolved?.id !== swap.target) return null; + swapped += 1; + return swap.with; + }, + }, + ], + }); + if (swap !== undefined && swapped === 0) throw new Error(`setup [${name}]: the build never imported ${swap.target}, so nothing was swapped`); + return { pages, diff: "" }; + } + + const root = join(scratch, name, "shift-manager"); + cpSync(SHIFT_MANAGER, root, { recursive: true, filter: (src) => !/[/\\](node_modules|dist)$/.test(src) }); + symlinkSync(join(SHIFT_MANAGER, "node_modules"), join(root, "node_modules")); + // The copy sits outside the workspace; its tsconfig still extends the workspace's. + const tsconfig = join(root, "tsconfig.json"); + writeFileSync(tsconfig, readFileSync(tsconfig, "utf8").replace('"../../tsconfig.base.json"', JSON.stringify(join(REPO_ROOT, "tsconfig.base.json")))); + const diffs: string[] = []; + for (const patch of patches) { + const path = join(root, patch.file); + const before = readFileSync(path, "utf8"); + const after = before.replace(patch.from, patch.to); + if (after === before) throw new Error(`setup [${name}]: ${patch.why}, but ${patch.file} has nothing to patch (looked for ${String(patch.from)})`); + writeFileSync(path, after); + diffs.push(`# ${patch.why}\n${unifiedDiff(join(SHIFT_MANAGER, patch.file), path, `labs/shift-manager/${patch.file}`)}`); + } + await (await vite()).build({ root, configFile: join(root, "vite.config.ts"), logLevel: "error", build: { outDir: pages, emptyOutDir: true }, define }); + return { pages, diff: diffs.join("\n") }; +} + +/** `diff -u` of the checkout's file against its patched copy, labelled with the repo path. */ +function unifiedDiff(original: string, patched: string, label: string): string { + try { + execFileSync("diff", ["-u", "--label", `a/${label}`, "--label", `b/${label}`, original, patched], { encoding: "utf8" }); + return ""; + } catch (error) { + return String((error as { stdout?: string }).stdout ?? ""); + } +} + +// ---- serving ----------------------------------------------------------------- + +/** A Shift Manager process serving one Lab. */ +export type Running = { origin: string; devtool: string | null; child: ChildProcess; exited: Promise; log: () => string; stop: () => Promise }; + +/** + * Shift Manager's start script over a Lab, from a fresh scratch working + * directory: `--team ` or `--config `, plus `--shift` when given. + */ +export async function startShiftManager( + scratch: string, + label: string, + options: { team?: string; config?: string; pages: string; shift?: "day" | "night"; env?: Record }, +): Promise { + mkdirSync(join(scratch, "labs"), { recursive: true }); + const workDir = mkdtempSync(join(scratch, "labs", `${label}-`)); + const lab = options.team !== undefined ? ["--team", options.team] : ["--config", options.config!]; + const args = [join(SHIFT_MANAGER, "bin", "start.mts"), ...lab, "--port", "0", "--assets", options.pages, ...(options.shift === undefined ? [] : ["--shift", options.shift])]; + let log = ""; + const child = spawn(TSX, args, { + cwd: workDir, + // GOAL_CONTROL is this script's, never the Lab's. + env: intentFreeEnv(process.env, { INIT_CWD: workDir, GOAL_CONTROL: "", SHIFT_MANAGER_SHIFT: "", ...(options.env ?? {}) }), + stdio: ["ignore", "pipe", "pipe"], + }); + child.stdout!.on("data", (d) => (log += String(d))); + child.stderr!.on("data", (d) => (log += String(d))); + let gone = false; + const exited = new Promise((resolve) => + child.on("exit", () => { + gone = true; + resolve(); + }), + ); + const stop = async () => { + if (!gone) child.kill("SIGTERM"); + await exited; + }; + for (let waited = 0; waited < 180_000; waited += 250) { + const match = /Shift Manager: (http:\/\/\S+)/.exec(log); + if (match !== null) { + const devtool = /Devtool: (http:\/\/\S+)/.exec(log); + return { origin: match[1]!, devtool: devtool?.[1] ?? null, child, exited, log: () => log, stop }; + } + if (gone) break; + await sleep(250); + } + await stop(); + throw new Error(`Shift Manager's start script never served ${label}. Log tail:\n${log.slice(-2000)}`); +} + +// ---- the store, read by this script ----------------------------------------- + +/** GET/POST against the Lab's routes, with the page's bearer when the Lab has one. */ +export function labApi(origin: string, bearer: string | undefined) { + const enc = encodeURIComponent; + const call = async (method: string, path: string, body?: unknown): Promise<{ status: number; body: any }> => { + const response = await fetch(`${origin}/api/flows${path}`, { + method, + headers: { "content-type": "application/json", ...(bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }) }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }); + const text = await response.text(); + if (text.length === 0) return { status: response.status, body: null }; + try { + return { status: response.status, body: JSON.parse(text) }; + } catch { + throw new Error(`${method} ${path}: ${response.status}, and the body is not JSON: ${text.slice(0, 200)}`); + } + }; + const get = async (path: string): Promise => { + const { status, body } = await call("GET", path); + if (status !== 200) throw new Error(`GET ${path}: ${status} ${JSON.stringify(body)}`); + return body; + }; + /** Every row of a collection, through one session, page by page. */ + const collection = async (sessionId: string, ref: string): Promise>> => { + const rows: Array> = []; + let cursor: string | undefined; + for (let page = 0; page < 100; page += 1) { + const body = await get(`/sessions/${enc(sessionId)}/resources/${enc(ref)}?limit=200${cursor === undefined ? "" : `&cursor=${enc(cursor)}`}`); + rows.push(...((body.items ?? []) as Array<{ clientData?: Record }>).map((i) => i.clientData ?? {})); + if (body.nextCursor === undefined || body.nextCursor === null || body.nextCursor === cursor) break; + cursor = body.nextCursor; + } + return rows; + }; + /** Every item of the given types in one session, oldest first (all types when none are given). */ + const items = async (sessionId: string, types: string[] = []): Promise>> => { + const out: Array> = []; + for (let offset = 0, page = 0; page < 100; page += 1) { + const filter = types.length === 0 ? "" : `&item_types=${types.join(",")}`; + const body = await get(`/sessions/${enc(sessionId)}/state?include_items=true${filter}&offset=${offset}&limit=200`); + out.push(...(body.items ?? [])); + if (body.pagination?.hasMore !== true) break; + offset = body.pagination.nextOffset ?? offset + 200; + } + return out; + }; + /** Whether the session holds a message of `role` whose content contains `needle`. */ + const holds = async (sessionId: string, role: string, needle: string): Promise => + (await items(sessionId, ["message"])).some((m) => m.role === role && JSON.stringify(m.content ?? m.text ?? m).includes(needle)); + const ownerOf = async (sessionId: string): Promise => { + const body = await get(`/sessions/${enc(sessionId)}`); + return String((body.session ?? body).flowId); + }; + const requestStatus = async (flowId: string, requestId: string): Promise => + String((await get(`/${enc(flowId)}/requests/${enc(requestId)}/status`)).status); + return { call, get, collection, items, holds, ownerOf, requestStatus }; +} +export type LabApi = ReturnType; + +/** What the tree on disk declares: an oracle Shift Manager never reads. */ +export type Tree = { + root: string; + seats: string[]; + teams: string[]; + channels: Array<{ id: string; members: string[]; boardRefs: string[] }>; +}; + +export async function readTree(root: string): Promise { + const roster = await readDeclaredRoster(root); + if (roster.problems.length > 0) throw new Error(`the tree at ${root} did not load: ${roster.problems.map((p) => p.path).join(", ")}`); + const seats = roster.workers.map((w) => w.id); + return { + root, + seats, + teams: [...new Set(seats.map((s) => (s.includes(".") ? s.split(".")[0]! : "Staff")))], + channels: roster.channels.map((c) => ({ + id: c.id, + members: Array.isArray(c.declared.members) ? (c.declared.members as string[]) : [], + boardRefs: ((c.declared.boards as string[] | undefined) ?? []).map((b) => `${c.id}.${b}`), + })), + }; +} + +/** A stored board row, as the store returns it. */ +export type StoredRow = { ref: string; id: string; status: string; title: string; run: { sessionId: string; requestId: string } | null; raw: Record }; +/** A pending ask: a suspension with no resume, on a seat's session, asking a person. */ +export type StoredAsk = { suspensionId: string; sessionId: string; seat: string }; + +/** What the store holds, read through the Lab's routes by this script. */ +export type Store = { + seats: string[]; + channels: Array<{ id: string; kind: string; members: string[] }>; + rows: Record; + asks: StoredAsk[]; + /** The organizations the person's sessions are bound to. */ + orgs: string[]; +}; + +/** Suspension reasons that are a person being asked something. */ +const PERSON_REASONS = new Set(["human_approval", "human_input"]); + +export async function readStore(api: LabApi, tree: Tree, userId: string): Promise { + // The inventory, through the first channel's session, by its published key patterns. + const host = tree.channels[0]!.id; + const manifest = await api.get(`/sessions/${encodeURIComponent(host)}/manifest`); + const refOf = (pattern: string) => + (manifest.resources as Array<{ kind: string; ref: string; pattern: string }>).find((r) => r.kind === "collection" && r.pattern === pattern)?.ref; + const seatsRef = refOf("inventory/seats/*"); + const channelsRef = refOf("inventory/channels/*"); + const seats = seatsRef === undefined ? [] : (await api.collection(host, seatsRef)).map((r) => String(r.id)); + const channels = + channelsRef === undefined + ? [] + : (await api.collection(host, channelsRef)).map((r) => ({ id: String(r.id), kind: String(r.kind), members: Array.isArray(r.members) ? (r.members as string[]) : [] })); + + const rows: Store["rows"] = {}; + for (const channel of tree.channels) { + rows[channel.id] = []; + for (const ref of channel.boardRefs) { + for (const row of await api.collection(channel.id, ref)) { + rows[channel.id]!.push({ + ref, + id: String(row.id), + status: String(row.status), + title: String(row.title ?? row.goal ?? row.id), + run: row.run == null ? null : { sessionId: String(row.run.sessionId), requestId: String(row.run.requestId) }, + raw: row, + }); + } + } + } + + const listing = await api.get(`/sessions?userId=${encodeURIComponent(userId)}&include=dispatch-runs&limit=500`); + const sessions = (listing.sessions ?? []) as Array>; + const orgs = [...new Set(sessions.map((s) => s.orgId).filter((o): o is string => typeof o === "string" && o.length > 0))]; + const seatSet = new Set(seats); + const asks: StoredAsk[] = []; + for (const session of sessions) { + if (!seatSet.has(String(session.flowId))) continue; + const found = await api.items(String(session.id), ["suspension", "suspension_resume"]); + const resumed = new Set(found.filter((i) => i.type === "suspension_resume").map((i) => String(i.suspensionId))); + for (const item of found) { + if (item.type === "suspension" && PERSON_REASONS.has(String(item.reason)) && !resumed.has(String(item.suspensionId))) { + asks.push({ suspensionId: String(item.suspensionId), sessionId: String(session.id), seat: String(session.flowId) }); + } + } + } + return { seats, channels, rows, asks, orgs }; +} + +/** Whether a session holds a resume for `suspensionId`. */ +export async function resumed(api: LabApi, sessionId: string, suspensionId: string): Promise { + return (await api.items(sessionId, ["suspension_resume"])).some((i) => String(i.suspensionId) === suspensionId); +} + +// ---- the page ---------------------------------------------------------------- + +/** The user and bearer the page was handed, read off the page itself. */ +export async function injected(page: Page): Promise<{ userId: string; bearer: string | undefined }> { + const config = (await page.evaluate(() => (window as any).__FSD_DEVTOOL_CONFIG__ ?? null)) as { userId?: string; bearerToken?: string } | null; + if (config?.userId === undefined) throw new Error("the page was handed no userId"); + return { userId: config.userId, bearer: config.bearerToken }; +} + +/** Load a path and wait for the shell and its first read. */ +export async function open(page: Page, origin: string, path: string): Promise { + await page.goto(`${origin}${path}`); + await page.getByTestId("shell").waitFor({ timeout: 30_000 }); + await page.waitForFunction(() => !document.querySelector("[data-testid=nav-tasks-count]")?.textContent?.includes("…"), undefined, { timeout: 30_000 }); +} + +export async function visible(page: Page, testId: string, timeout = 10_000): Promise { + try { + await page.getByTestId(testId).first().waitFor({ timeout }); + return true; + } catch { + return false; + } +} + +/** One attribute of every element with a test id. */ +export const attr = async (page: Page, testId: string, name: string) => + (await page.getByTestId(testId).evaluateAll((els, n) => els.map((e) => e.getAttribute(n) ?? ""), name)) as string[]; + +/** + * Click Send on a composer, then watch its status until it settles. The moment + * it first reads *delivered*, `heldNow` reads the store: the line must already + * be there. + */ +export async function sendAndWatch( + page: Page, + composer: string, + heldNow: () => Promise, + withinMs = 120_000, +): Promise<{ state: string; heldAtDelivered: boolean | null; error: string | null }> { + await page.getByTestId(`${composer}-send`).click(); + for (const until = Date.now() + withinMs; Date.now() < until; await sleep(50)) { + const state = (await page.getByTestId(`${composer}-status`).getAttribute("data-state")) ?? ""; + if (state === "delivered") return { state, heldAtDelivered: await heldNow(), error: null }; + const error = await page.getByTestId(`${composer}-error`).textContent({ timeout: 50 }).catch(() => null); + if (error !== null) return { state: state || "error", heldAtDelivered: null, error }; + } + return { state: "sending", heldAtDelivered: null, error: `nothing settled within ${withinMs / 1000}s` }; +} + +// ---- reading what is painted --------------------------------------------------- + +/** One painted value on one element. */ +export type Sample = { part: string; el: string; prop: string; value: string }; +export type PageRead = { counts: Record; colours: Sample[]; fonts: Sample[]; probes: Record }; + +/** + * Runs in the page: every painted colour and font inside each part's + * selector, plus how the page computes each probe value. A colour set by an + * inline literal (syntax highlighting) is content, not skin, and is skipped. + * Lifted from `it-takes-its-look-from-the-design-system`. + */ +export function readPainted(args: { parts: Record; probeValues: string[] }): PageRead { + const colours: Sample[] = []; + const fonts: Sample[] = []; + const counts: Record = {}; + const describe = (el: Element) => + `${el.tagName.toLowerCase()}${el.getAttribute("class") ? "." + el.getAttribute("class")!.trim().split(/\s+/).slice(0, 3).join(".") : ""}`; + const sample = (part: string, el: Element) => { + const cs = getComputedStyle(el); + const rect = el.getBoundingClientRect(); + if (cs.display === "none" || cs.visibility !== "visible" || rect.width === 0 || rect.height === 0) return false; + const push = (prop: string, value: string) => colours.push({ part, el: describe(el), prop, value }); + const inlineLiteral = /(^|;)\s*(color|background(-color)?)\s*:\s*(#|rgb)/i.test(el.getAttribute("style") ?? ""); + const hasText = Array.from(el.childNodes).some((n) => n.nodeType === 3 && n.textContent!.trim().length > 0); + if (!inlineLiteral) { + if (hasText) push("color", cs.color); + push("background-color", cs.backgroundColor); + } + if (el.tagName.toLowerCase() === "svg") { + if (cs.stroke !== "none") push("stroke", cs.stroke); + if (cs.fill !== "none") push("fill", cs.fill); + } + for (const side of ["top", "right", "bottom", "left"]) { + const style = cs.getPropertyValue(`border-${side}-style`); + if (parseFloat(cs.getPropertyValue(`border-${side}-width`)) > 0 && style !== "none" && style !== "hidden") { + push(`border-${side}-color`, cs.getPropertyValue(`border-${side}-color`)); + } + } + if (cs.outlineStyle !== "none" && parseFloat(cs.outlineWidth) > 0) push("outline-color", cs.outlineColor); + if (hasText) fonts.push({ part, el: describe(el), prop: "font-family", value: cs.fontFamily }); + return true; + }; + for (const [part, selector] of Object.entries(args.parts)) { + counts[part] = 0; + for (const root of Array.from(document.querySelectorAll(selector))) { + for (const el of [root, ...Array.from(root.querySelectorAll("*"))]) if (sample(part, el)) counts[part] += 1; + } + } + const probe = document.createElement("span"); + document.body.appendChild(probe); + const probes: Record = {}; + for (const value of args.probeValues) { + probe.style.color = ""; + probe.style.color = value; + probes[value] = getComputedStyle(probe).color; + } + probe.remove(); + return { counts, colours, fonts, probes }; +} + +/** Wait until no finite animation or transition is running, so computed colours are settled. */ +export async function settled(page: Page): Promise { + await page.waitForFunction(() => document.getAnimations().every((a) => a.playState !== "running" || a.effect?.getTiming().iterations === Infinity), undefined, { + timeout: 10_000, + }); +} From 3aca2f290a80af4fd65f95b1b7405a2aaa389198 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 05:52:22 +0000 Subject: [PATCH 02/19] goals(FIX-1663): optimistic-post swaps the @worker send too The control removes the send on both trees (PLAN Controls), which since FIX-1690 means send.ts as well as transcript.ts; a swap may now name several target files. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../run.mts | 12 +++++++----- .../shell.mts | 9 ++++++--- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts index 7083e025cb..0b66910811 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts @@ -97,7 +97,7 @@ const NO_ORG: Patch = { why: "control no-org: Shift Manager renders with no org, the org switcher empty", }; const CHILD = (goal: string, file: string) => join(REPO_ROOT, "goals", "shift-manager", goal, "controls", file); -const swapOf = (target: string, goal: string, file: string): Swap => ({ target: join(SHIFT_MANAGER, "src", "lib", target), with: CHILD(goal, file) }); +const swapOf = (target: string | string[], goal: string, file: string): Swap => ({ target: [target].flat().map((t) => join(SHIFT_MANAGER, "src", "lib", t)), with: CHILD(goal, file) }); /** * A build with a module swapped in and the theme import removed in the @@ -122,6 +122,7 @@ const [root, outDir, target, withFile, seats] = ${JSON.stringify([SHIFT_MANAGER, const THEME_IMPORT = ${THEME_IMPORT.toString()}; const vite = await import(pathToFileURL(createRequire(root + "/package.json").resolve("vite")).href); let swapped = 0; +const hit = new Set(); let stripped = 0; await vite.build({ root, @@ -136,7 +137,8 @@ await vite.build({ async resolveId(source, importer, opts) { if (importer === undefined || importer === withFile) return null; const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true }); - if (resolved?.id !== target) return null; + if (resolved?.id === undefined || ![target].flat().includes(resolved.id)) return null; + hit.add(resolved.id); swapped += 1; return withFile; }, @@ -154,7 +156,7 @@ await vite.build({ }, ], }); -if (swapped === 0) throw new Error("the build never imported " + target); +if (swapped === 0 || [target].flat().some((t) => !hit.has(t))) throw new Error("the build never imported " + [target].flat().filter((t) => !hit.has(t)).join(", ")); if (stripped === 0) throw new Error("the theme import was never removed"); `, ); @@ -165,7 +167,7 @@ if (stripped === 0) throw new Error("the theme import was never removed"); } const css = readdirSync(join(pages, "assets")).filter((f) => f.endsWith(".css")).map((f) => readFileSync(join(pages, "assets", f), "utf8")).join("\n"); if (/Space Grotesk/i.test(css)) throw new Error(`setup [${name}]: the no-theme build still ships the Shift Manager theme`); - return { pages, diff: `# the design-system import line removed in the bundler (src/styles.css), plus ${relative(REPO_ROOT, swap.with)} in place of ${relative(REPO_ROOT, swap.target)}` }; + return { pages, diff: `# the design-system import line removed in the bundler (src/styles.css), plus ${relative(REPO_ROOT, swap.with)} in place of ${[swap.target].flat().map((t) => relative(REPO_ROOT, t)).join(" and ")}` }; } // ---- b0: the pentest config, from the README alone ------------------------------- @@ -315,7 +317,7 @@ async function controls(only: string[] | null): Promise { { name: "optimistic-post", build: async () => { - const swap = swapOf("transcript.ts", "it-opens-a-lab", "optimistic-post.ts"); + const swap = swapOf(["transcript.ts", "send.ts"], "it-opens-a-lab", "optimistic-post.ts"); return { themed: await swapBuild("ctl-optimistic-post", swap, false), noTheme: await swapBuild("ctl-optimistic-post-no-theme", swap, true) }; }, must: ["a4", "b:post"], diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts index 57c2b5a82c..cfe30e0a33 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts @@ -40,7 +40,7 @@ export const diff = (want: Iterable, got: Iterable) => { /** One edit to a scratch copy of Shift Manager. A patch that matches nothing fails the setup. */ export type Patch = { file: string; from: string | RegExp; to: string; why: string }; /** A source module swapped for a control module at build time (a child check's control). */ -export type Swap = { target: string; with: string }; +export type Swap = { target: string | string[]; with: string }; /** A build: where its pages are, and the full diff of every patch applied to it. */ export type Built = { pages: string; diff: string }; @@ -72,6 +72,7 @@ export async function buildPages( const patches = options.patches ?? []; if (patches.length === 0) { let swapped = 0; + const hit = new Set(); const swap = options.swap; await (await vite()).build({ root: SHIFT_MANAGER, @@ -89,14 +90,16 @@ export async function buildPages( async resolveId(this: any, source: string, importer: string | undefined, opts: Record) { if (importer === undefined || importer === swap.with) return null; const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true }); - if (resolved?.id !== swap.target) return null; + if (resolved?.id === undefined || ![swap.target].flat().includes(resolved.id)) return null; + hit.add(resolved.id); swapped += 1; return swap.with; }, }, ], }); - if (swap !== undefined && swapped === 0) throw new Error(`setup [${name}]: the build never imported ${swap.target}, so nothing was swapped`); + const missed = swap === undefined ? [] : [swap.target].flat().filter((t) => !hit.has(t)); + if (swapped === 0 && swap !== undefined || missed.length > 0) throw new Error(`setup [${name}]: the build never imported ${missed.join(", ")}, so nothing was swapped`); return { pages, diff: "" }; } From cb49d3e0de99ab6460e95e8f0aea4a43cdc55eb0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 13:09:54 +0000 Subject: [PATCH 03/19] test(goals): verdict log for the FIX-1663 re-run on main 48c31cfa6 The earlier findings are fixed: b0, part 4 and all six controls now hold. One new finding is recorded: a4 refused 15 s into a run whose harness had not yet confirmed its session, and a2 drew nothing live from the running task's Session. Nothing is fixed here. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../a-lab-is-worked-through-one-skinned-shell/goal.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md index 06a89957c8..a47a4e79b3 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -41,3 +41,6 @@ | 2026-10-02 | c29aafa4f | Claude Code harness (a4), `claude` CLI (b0) | FAIL (findings) | **Legs:** a PASS (a1 the EM's ask approved from Inbox, resume stored; a4 `@coder` delivered and held when drawn, the next attempt answered in the run session; a2 18 items drawn, all stored, trace followed from Tasks and Board; a3 every surface). b PASS (3 seats in teams audit and pentest, post held when drawn and once after a reload, `labs/shift-manager` unchanged, org_pentest_lab; no-resolver Lab under `__fsd_default_org__`). c PASS (day and night: message 20, reasoning 16, tool 51, code block 32, ask 12, devtool 155 elements, 0 theme values; static fence 0 hits in 2419 files). **b0 FAIL:** the writer's config boots the same flows, org, seats, workstream and user as the committed one, but it had to guess 3 steps (which store, whether `host.mts`'s options do the inventory and devtool steps, whether a Lab needs a chief-of-staff seat). **J3, J4 PASS.** **Part 4 FAIL:** `labs/shift-manager/src/styles.css` defines the registry's default tokens as `hsl()` literals. | | 2026-10-02 | c29aafa4f | as above | controls | today's main (d8f6a10e7) FAIL as expected, c's static half green. hardcoded-accent FAIL at c:tool only (`#e8f551` on the tool card's icon, day and night). no-org FAIL at b:org only. **WRONG:** static-names fails b:teams but also a4 (its written-in seats carry no door, so "eng.coder takes no message."); optimistic-post fails b:post but a4 stays green (it swaps the channel post, and `@worker` goes through the seat's door); worker-session stays green at a2 (DevForce's coder holds no other session on its flow, so the near-miss reads the run session). | | 2026-10-02 | c29aafa4f | real model where each child names one | PASS (part 3) | Every child check PASS and every child control FAIL at its named signal: design-system (hardcoded-accent), it-opens-a-lab (static-names, optimistic-post, unanswerable-asks), it-shows-and-stops-a-task-run (worker-session, optimistic-interrupt, board-flow), it-takes-its-look-from-the-design-system (hardcoded-accent, switch-ignored), it-sends-a-turn-into-a-seat-session (optimistic-turn, fresh-session), it-briefs-and-talks-with-the-chief-of-staff (optimistic-reply, static-brief), it-shows-who-is-on-shift (ignore-asks, count-queued), it-hands-a-run-the-work-it-approved (drop-task), the two D1 children (no-gate, kind-ledger), devforce-lab ×3, pentest-lab ×2, multi-seat-collab. Design-system, registry and static tests, `pnpm typecheck` and `pnpm test` PASS. | +| 2026-10-02 | 9bbc77b04 (main 48c31cfa6, with the earlier findings fixed) | Claude Code harness (a4), `claude` CLI (b0) | FAIL (finding) | **a FAIL:** a1 and a3 pass. a4 was refused 15 s into the run with "This run's harness can't continue with a message.", because the door refuses a run whose harness hasn't confirmed its session yet. a2 then opened the still-running task: from Tasks the Session drew nothing in 30 s while the run session held 2 items; from Board it drew 1 item, which the store held later. In the five control runs of leg a on the same commit, a4 was delivered and answered in four. **b0 PASS** (no guesses; same flows, org, seats, workstream and user as the committed config). **b, c, J3, J4 and part 4 PASS** (c: 0 Shift Manager values day and night, static fence 0 hits). | +| 2026-10-02 | 9bbc77b04 | as above | controls | All six FAIL at their own signal only: today's main (a and b; c's static half green), hardcoded-accent (c:tool), static-names (b:teams), optimistic-post (a4 + b:post), worker-session (a2), no-org (b:org). | +| 2026-10-02 | 9bbc77b04 | real model where each child names one | PASS (part 3) | 39 verdicts, all as expected: every child check passes, every child control fails at its named signal, and the design-system, registry and static tests, `pnpm typecheck` and `pnpm test` pass. | From e5ccf686576218b1f507e92543a6b25695b60da1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 18:55:29 +0000 Subject: [PATCH 04/19] fix(goals): Part 3 children get the launch NODE_ENV, not vite.build()'s (FIX-1663) An in-process vite.build() sets NODE_ENV=production and leaves it set, so P3.1's vitest child resolved node: built-ins to Vite's browser stub and failed with 'fileURLToPath is not a function' whenever pages were built first. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../a-lab-is-worked-through-one-skinned-shell/run.mts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts index 0b66910811..5f186061af 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts @@ -460,13 +460,17 @@ const CHILDREN: Child[] = [ { id: "P3.3 multi-seat-collab it-hands-a-row-between-two-seats-in-view", run: "goals/multi-seat-collab/it-hands-a-row-between-two-seats-in-view/run.mts" }, ]; +/** NODE_ENV as launched. An in-process vite.build() sets it to "production" and never restores it, + * which would make Part 3's vitest children stub out node: built-ins. */ +const LAUNCH_NODE_ENV = process.env.NODE_ENV; + /** Run one command to its end, keeping its output in a log beside the scratch builds. */ function runLogged(label: string, cmd: string, args: string[], env: Record): Promise<{ code: number; out: string; log: string }> { const log = join(SCRATCH, "part3", `${label.replace(/[^a-z0-9.-]+/gi, "_")}.log`); mkdirSync(join(SCRATCH, "part3"), { recursive: true }); return new Promise((resolve) => { let out = ""; - const merged: Record = { ...process.env, ...env }; + const merged: Record = { ...process.env, NODE_ENV: LAUNCH_NODE_ENV, ...env }; for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]; const child = spawn(cmd, args, { cwd: REPO_ROOT, env: merged as NodeJS.ProcessEnv, stdio: ["ignore", "pipe", "pipe"] }); child.stdout.on("data", (d) => (out += String(d))); From 3537738a7273e9188b0aec55c9579e836f41be12 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 00:53:22 +0000 Subject: [PATCH 05/19] goals(FIX-1663): closure leg d runs FIX-1737's v2 look with its controls; each DevTeam start on a fresh store Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../goal.md | 5 ++- .../run.mts | 42 +++++++++++++++++-- .../shell.mts | 3 +- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md index a47a4e79b3..9c394ecd39 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -15,6 +15,7 @@ - **b0, the pentest config from the README.** An isolated writer that sees only Shift Manager's README and the pentest tree (minus its config) writes a config to scratch. Every step it had to guess is a failure, and so is a semantic difference from the committed config (flows, org, seats, workstreams, the page's user and bearer), booted side by side. - **b, the pentest Lab.** The a3 reach on the pentest tree; the composer's post is in the channel's stored transcript when it is drawn, and drawn once after a reload; `labs/shift-manager` is unchanged and names no pentest seat, team or channel. A Lab with no resolver opens under `DEFAULT_ORG_ID`, and on both Labs the switcher names the store's org. - **c, the theme fence.** On a build with only the theme import removed, `--shift day` then `--shift night`: the computed colour, background, border and font of every message, reasoning, tool, code block and ask card, and of the devtool page the trace link opens, match no value the Shift Manager theme declares. Each part renders at least once per pass. FIX-1655's static check over `packages/**` finds none. +- **d, the v2 look (FIX-1737).** `goals/shift-manager/it-draws-v2s-look` passes on the same commit, by subprocess. Its controls `drift`, `unclassified` and `missing` each fail at exactly the legs its goal.md names (drift at surface and type, the other two at totality) and nowhere else. It builds its own copy and runs DevTeam on a fresh store of its own. - **J3.** In a fresh host, `fsdev ui add tool approval` from the commit's registry gives byte-identical copies; with the docs' token block applied as written, changing `--success` repaints both. - **J4.** Every surface in the epic's ownership table opens by its address on a fresh load and shows rows or its named empty state; none blank, none refused. - **Part 3.** Every child's goal check with its controls, the goal labs the set touched, the design-system and registry tests, `pnpm typecheck` and `pnpm test`. @@ -24,9 +25,9 @@ **Model:** leg a's harness is Claude Code, through `AI_GATEWAY_API_KEY` or `ANTHROPIC_API_KEY`; only a4's answer rests on it. b0's writer is the `claude` CLI. Legs b and c and both journeys are model-free. -**Run:** `PLAYWRIGHT_BROWSERS_PATH=/opt/pw-browsers pnpm tsx goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts`. `GOAL_PART=a,b0,b,c,controls,part2,part3,part4` (the default) picks the parts. For a rerun, `GOAL_CONTROLS` picks the controls, `GOAL_CONTROL_LEGS` the legs a control runs, and `GOAL_CHILDREN` (a regex on the label) part 3's entries. +**Run:** `PLAYWRIGHT_BROWSERS_PATH=/opt/pw-browsers pnpm tsx goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts`. `GOAL_PART=a,b0,b,c,d,controls,part2,part3,part4` (the default) picks the parts. For a rerun, `GOAL_CONTROLS` picks the controls, `GOAL_CONTROL_LEGS` the legs a control runs, and `GOAL_CHILDREN` (a regex on the label) part 3's entries. -**Controls:** each runs legs a, b and c on its own build or server start. +**Controls:** each runs legs a, b and c on its own build or server start. Leg d's controls are the look check's own, run inside leg d. Every server start that opens DevTeam gets a fresh store in its own scratch directory, never the checkout's `labs/shift-manager/.fsdev/devteam.sqlite`. - **today's main** (the commit before Shift Manager's first merge): Shift Manager is absent, so a and b must fail; c's static half over that commit's `packages/` stays green. - **hardcoded-accent** (scratch patch on the tool card's copy): must fail c at the tool card. diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts index 5f186061af..328bab57ee 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts @@ -8,9 +8,10 @@ * * part 1 legs a (DevForce, real model on a4), b0 (the pentest config * written from Shift Manager's README by an isolated writer), b - * (pentest, keyless, plus every Lab opening under an org) and c + * (pentest, keyless, plus every Lab opening under an org), c * (no theme, `--shift day` then `--shift night`, plus the static - * fence over packages/) + * fence over packages/) and d (FIX-1737's v2 look, its goal check + * and its controls, by subprocess) * controls each on its own build or start; each must fail its own leg at * its own signal and leave the rest green * part 2 J3 (FSD UI reused in a fresh app) and J4 (a sibling's surfaces @@ -22,7 +23,7 @@ * Every verdict is printed as `VERDICT : …` with the commit it ran on. * * Run: PLAYWRIGHT_BROWSERS_PATH=/opt/pw-browsers pnpm tsx goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts - * Parts: GOAL_PART=a,b0,b,c,controls,part2,part3,part4 (default: all, in that order) + * Parts: GOAL_PART=a,b0,b,c,d,controls,part2,part3,part4 (default: all, in that order) * Controls: GOAL_CONTROLS=hardcoded-accent,… (default: all of them) * Needs: a model key (leg a, and the real-model child checks), a signed-in * Claude Code (a4's harness, and b0's writer through the `claude` @@ -42,7 +43,7 @@ import { SHIFT_MANAGER, buildPages, injected, labApi, open, readStore, readTree, const HERE = fileURLToPath(new URL(".", import.meta.url)); const SCRATCH = goalTmpDir("shift-manager-closure"); -const PARTS = (process.env.GOAL_PART ?? "a,b0,b,c,controls,part2,part3,part4").split(",").map((s) => s.trim()); +const PARTS = (process.env.GOAL_PART ?? "a,b0,b,c,d,controls,part2,part3,part4").split(",").map((s) => s.trim()); const git = (...args: string[]) => execFileSync("git", args, { cwd: REPO_ROOT, encoding: "utf8" }).trim(); const COMMIT = git("rev-parse", "HEAD"); @@ -525,6 +526,38 @@ async function part3(): Promise { } } +// ---- d: FIX-1737's v2 look, by subprocess ------------------------------------------- + +const V2_LOOK = SM("it-draws-v2s-look"); +/** Each of the look check's controls, and the legs it must fail at (its `legs failing:` line), nothing else. */ +const V2_LOOK_CONTROLS: Array<{ control: string; legs: string[] }> = [ + { control: "drift", legs: ["surface", "type"] }, + { control: "unclassified", legs: ["totality"] }, + { control: "missing", legs: ["totality"] }, +]; +const legsFailing = (out: string) => (/legs failing: ([^\n]*)/.exec(out.slice(out.lastIndexOf("FAIL —")))?.[1] ?? "").split(",").map((l) => l.trim()).filter(Boolean).sort(); + +/** + * d. The v2 look on this commit: `it-draws-v2s-look` passes, then each of its + * controls fails at exactly the legs its goal.md names. Its own scratch, + * build and DevTeam store are the child's, fresh per subprocess. + */ +async function legD(): Promise { + const tsx = join(REPO_ROOT, "node_modules", ".bin", "tsx"); + const own = await runLogged("d it-draws-v2s-look", tsx, [V2_LOOK], { GOAL_CONTROL: undefined }); + const bullets = failBullets(own.out); + verdict("leg d (it-draws-v2s-look)", own.code === 0, own.code === 0 ? `PASS — ${verdictLine(own.out).slice(7, 400)}` : `FAIL (${bullets.length})`, [...bullets.slice(0, 12).map((b) => `✗ [d] ${b}`), `log: ${own.log}`]); + for (const { control, legs } of V2_LOOK_CONTROLS) { + const { code, out, log } = await runLogged(`d it-draws-v2s-look GOAL_CONTROL=${control}`, tsx, [V2_LOOK], { GOAL_CONTROL: control }); + const red = legsFailing(out); + const ok = code !== 0 && JSON.stringify(red) === JSON.stringify([...legs].sort()); + verdict(`control d:${control}`, ok, ok ? `FAIL (expected) at ${legs.join(" + ")} only` : `WRONG: exit ${code}, legs failing [${red.join(", ")}], expected [${legs.join(", ")}]`, [ + ...failBullets(out).slice(1, 9).map((b) => `✗ ${b}`), + `log: ${log}`, + ]); + } +} + // ---- the run --------------------------------------------------------------------- let PAGES: Built | undefined; @@ -554,6 +587,7 @@ await runGoal(async () => { if (want("b0")) await leg("b0", ["b0"], () => b0(report)); if (want("b")) await leg("leg b", ["b"], () => legB(ctx(PAGES!.pages))); if (want("c")) await leg("leg c", ["c"], () => legC(ctx(noTheme!.pages))); + if (want("d")) await legD(); if (want("part2")) { await leg("J3", ["J3"], () => j3(SCRATCH, browser, report)); await leg("J4", ["J4"], () => j4(SCRATCH, PAGES!.pages, browser, report)); diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts index cfe30e0a33..7989c59c1d 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts @@ -154,7 +154,8 @@ export async function startShiftManager( const child = spawn(TSX, args, { cwd: workDir, // GOAL_CONTROL is this script's, never the Lab's. - env: intentFreeEnv(process.env, { INIT_CWD: workDir, GOAL_CONTROL: "", SHIFT_MANAGER_SHIFT: "", ...(options.env ?? {}) }), + // DevTeam keeps a SQLite store; each start gets a fresh one in its own work dir, never the checkout's. + env: intentFreeEnv(process.env, { INIT_CWD: workDir, GOAL_CONTROL: "", SHIFT_MANAGER_SHIFT: "", DEVTEAM_STORE: join(workDir, "devteam.sqlite"), ...(options.env ?? {}) }), stdio: ["ignore", "pipe", "pipe"], }); child.stdout!.on("data", (d) => (log += String(d))); From f7269f5480cb5f5df32c8454f0a5f1887118bd5d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:43:27 +0000 Subject: [PATCH 06/19] goals(FIX-1663): part 3 reads it-opens-a-lab's unanswerable-asks control at its renamed signal FIX-1737 C renamed the child's signal to "an answer from the Stream lands in the store" (its goal.md names it so). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../a-lab-is-worked-through-one-skinned-shell/run.mts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts index 328bab57ee..6d245076a3 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts @@ -428,7 +428,7 @@ const CHILDREN: Child[] = [ { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab") }, { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab"), control: "static-names", must: /\[multi-seat-collab\] TEAMS equals the store's seats/, allowed: /\[multi-seat-collab\] TEAMS equals the store's seats/ }, { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab"), control: "optimistic-post", must: /the post is in the stored transcript/, allowed: /the post is in the stored transcript/ }, - { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab"), control: "unanswerable-asks", must: /an answer from Inbox lands in the store/, allowed: /an answer from Inbox lands in the store/ }, + { id: "P3.2 FIX-1662 it-opens-a-lab", run: SM("it-opens-a-lab"), control: "unanswerable-asks", must: /an answer from the Stream lands in the store/, allowed: /an answer from the Stream lands in the store/ }, { id: "P3.2 FIX-1664 it-shows-and-stops-a-task-run", run: SM("it-shows-and-stops-a-task-run") }, { id: "P3.2 FIX-1664 it-shows-and-stops-a-task-run", run: SM("it-shows-and-stops-a-task-run"), control: "worker-session", must: /items equal the run session's/, allowed: /items equal the run session's|\blive\b/ }, { id: "P3.2 FIX-1664 it-shows-and-stops-a-task-run", run: SM("it-shows-and-stops-a-task-run"), control: "optimistic-interrupt", must: /the request reads aborted first/, allowed: /the request reads aborted first/ }, From 35e3c0aa531828e07e411c0aaa3efe34e5625963 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:47:02 +0000 Subject: [PATCH 07/19] test(goals): verdict log for the FIX-1663 closure on main a01a0b7bd (3537738a7) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../a-lab-is-worked-through-one-skinned-shell/goal.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md index 9c394ecd39..3939da1a6a 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -45,3 +45,6 @@ | 2026-10-02 | 9bbc77b04 (main 48c31cfa6, with the earlier findings fixed) | Claude Code harness (a4), `claude` CLI (b0) | FAIL (finding) | **a FAIL:** a1 and a3 pass. a4 was refused 15 s into the run with "This run's harness can't continue with a message.", because the door refuses a run whose harness hasn't confirmed its session yet. a2 then opened the still-running task: from Tasks the Session drew nothing in 30 s while the run session held 2 items; from Board it drew 1 item, which the store held later. In the five control runs of leg a on the same commit, a4 was delivered and answered in four. **b0 PASS** (no guesses; same flows, org, seats, workstream and user as the committed config). **b, c, J3, J4 and part 4 PASS** (c: 0 Shift Manager values day and night, static fence 0 hits). | | 2026-10-02 | 9bbc77b04 | as above | controls | All six FAIL at their own signal only: today's main (a and b; c's static half green), hardcoded-accent (c:tool), static-names (b:teams), optimistic-post (a4 + b:post), worker-session (a2), no-org (b:org). | | 2026-10-02 | 9bbc77b04 | real model where each child names one | PASS (part 3) | 39 verdicts, all as expected: every child check passes, every child control fails at its named signal, and the design-system, registry and static tests, `pnpm typecheck` and `pnpm test` pass. | +| 2026-10-04 | 3537738a7 (main a01a0b7bd, all four FIX-1737 slices, leg d wired) | Claude Code harness (a4), `claude` CLI (b0) | FAIL (findings) | **d PASS:** `it-draws-v2s-look` 141 rows, 21 exceptions, DevTeam 2 teams, 4 seats, 1 running, 1 ask pending; drift FAIL at surface + type only, unclassified and missing at totality only. **c's fence PASS** (day and night: message 20, reasoning 16, tool 51, code block 32, ask 5, devtool 165/164 elements, 0 Shift Manager values; static fence 0 hits in 2457 files). a4 delivered and answered in the run session; a2 drew only stored items from Tasks and Board; b's teams, post and org PASS; J3 PASS. **Findings, from main's merges, not the shell's look:** (1) a3, b:reach, c:reach and J4: the project level is no longer four placeholder empty states. Projects shipped (dfa9f460d, FIX-1718): `/p/unassigned` now draws `project-stream-none`, `project-brief-none`, the Board's lanes and the workstream list, and the goal still looks for `project--empty`. (2) a1: eng.em now sits in four channels (eng.feature, eng.triage, ops.oncall, ops.release, same commit), and the EM's ask carries no workstream session, so `workstreamsOf` falls back to every channel the seat is in and Inbox names all four. The Stream's ask card is `feed-ask` since FIX-1737 C (b2a3f387f), and a1 still reads `stream-asks`. (3) b0: the writer guessed 4 steps this time (answer/modelResolver, which store, the chief-of-staff seat, how `@flow-state-dev/engine` resolves). (4) Part 4 ER-15: two writes the seam doesn't name, `lib/talk.ts` `sendAction` (the project room, FIX-1718) and `lib/reads.ts` `createSession` (the room session, 3f357aafe FIX-1752). | +| 2026-10-04 | 3537738a7 | as above | controls | today's main FAIL as expected (c's static half green). hardcoded-accent, static-names, optimistic-post, worker-session and no-org each go red at their own signal, but every one is **WRONG** because finding (1) and (2) also turn a1, a3, b:reach and c:reach red. The full run's driver ran out of heap (8 GB) after worker-session; no-org, part 3 and part 4 were rerun as separate processes on the same commit. | +| 2026-10-04 | 3537738a7, f7269f548 (part 3's unanswerable-asks regex follows the child's renamed signal) | real model where each child names one | FAIL (part 3) | PASS with every control at its signal: design-system, it-opens-a-lab (static-names, optimistic-post, unanswerable-asks), it-sends-a-turn-into-a-seat-session, it-briefs-and-talks-with-the-chief-of-staff, it-shows-who-is-on-shift, it-hands-a-run-the-work-it-approved, both D1 children, devforce wakes and commits, pentest a-post-reaches, multi-seat-collab; design-system, registry and static tests, `pnpm typecheck` and `pnpm test`. **FAIL:** it-shows-and-stops-a-task-run and all three of its controls: `reach()` clicks the unclaimed row in Tasks, and Tasks hides queued rows until Queued is toggled (1c5fd250c, FIX-1737 D). it-takes-its-look-from-the-design-system (and its controls, 6 strays): the sidebar's `NavIcon` `` (f41cc0642, FIX-1737 B) leaves fill at the default `#000000`; its path paints with stroke only, but the check grades the computed fill. devforce it-ships-an-artifact: the fan-out skips chief-of-staff too, since FIX-1718 added it to eng.feature, and the goal's member list is hardcoded. pentest a-seat-answers: environmental, the AI Gateway answers 403 with `x-vercel-mitigated: deny` on every call (twice), while a direct gateway call is accepted. | From 1d1e1cb5ac2fc4fc708525bf30f00cbc6e66056e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:54:55 +0000 Subject: [PATCH 08/19] fix(shift-manager): the sidebar's nav icons paint no fill (FIX-1663) NavIcon's left fill at its default, so its computed fill was #000000 and it-takes-its-look-from-the-design-system counted it as a stray. The icons are line icons: fill none, stroke currentColor and the stroke width now sit on the , as the registry's lucide icons set them. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- labs/shift-manager/src/surfaces/Sidebar.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/labs/shift-manager/src/surfaces/Sidebar.tsx b/labs/shift-manager/src/surfaces/Sidebar.tsx index 6469e4e00c..71622a503b 100644 --- a/labs/shift-manager/src/surfaces/Sidebar.tsx +++ b/labs/shift-manager/src/surfaces/Sidebar.tsx @@ -82,8 +82,8 @@ const ICON_PATHS = { function NavIcon({ name }: { name: keyof typeof ICON_PATHS }) { return ( - - + + ); } From fc97cbcaf95597b72e0255619443a42b2e9c1be7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:54:56 +0000 Subject: [PATCH 09/19] goals(FIX-1663): it-shows-and-stops-a-task-run turns Queued on before it reaches a row from Tasks Since FIX-1737 D, Tasks hides queued rows until the Queued toggle is on, so reach() could not click the unclaimed row. It now turns the toggle on, as a person looking for any open row would. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- goals/shift-manager/it-shows-and-stops-a-task-run/run.mts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/goals/shift-manager/it-shows-and-stops-a-task-run/run.mts b/goals/shift-manager/it-shows-and-stops-a-task-run/run.mts index 7f62645487..b0b37cdff5 100644 --- a/goals/shift-manager/it-shows-and-stops-a-task-run/run.mts +++ b/goals/shift-manager/it-shows-and-stops-a-task-run/run.mts @@ -293,6 +293,9 @@ async function reach(page: Page, origin: string, tree: Tree, row: Row) { await page.locator(`[data-testid=board-card][data-task-id="${row.id}"]`).click(); } else { await page.getByTestId("tasks-table").waitFor({ timeout: 20_000 }); + // Tasks hides queued rows until Queued is on; a person looking for any open row turns it on. + const queued = page.getByTestId("tasks-queued-toggle"); + if ((await queued.getAttribute("aria-pressed")) !== "true") await queued.click(); await page.locator(`[data-testid=task-row][data-task-id="${row.id}"]`).click(); } await page.locator(`[data-testid=task-frame][data-task-id="${row.id}"]`).waitFor({ timeout: 10_000 }); From 5d82d5d50aff507dc436cfff30028f9749428aff Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:54:56 +0000 Subject: [PATCH 10/19] goals(FIX-1663): it-ships-an-artifact reads the channel's declared members off the tree The fan-out's expected skips came from a hardcoded member list, which missed the chief-of-staff seat FIX-1718 added to the board's channel. They now come from the board channel's CHANNEL.md, through the roster the lab opened. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../run.mts | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts b/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts index ebd4fc0f4f..7bc4fd927f 100644 --- a/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts +++ b/goals/devforce-lab/it-ships-an-artifact-a-person-can-open/run.mts @@ -85,7 +85,7 @@ import { harnessTaskId } from "@flow-state-dev/harness-manager/checkout"; import type { Task } from "@flow-state-dev/orchestration/tasks"; import { z } from "zod"; import { RUN_STAMP, runGoal, silentLogger, stripIntentOverrides } from "../../lib/index.mts"; -import { LAB_ORG_ID, LAB_TREE, LAB_USER_ID, openLab, type Lab } from "../lab/host.mts"; +import { boardChannelOf, LAB_ORG_ID, LAB_TREE, LAB_USER_ID, openLab, type Lab } from "../lab/host.mts"; import { PHASE } from "../lab/phase.mts"; import { createNotifyLog, type NotifyLog } from "../lab/notify.mts"; import { ACCEPTANCE_MODULE, runAcceptance } from "../lab/acceptance.mts"; @@ -112,8 +112,6 @@ const ASSIGNED_SEAT = "eng.coder"; const COORDINATOR_SEAT = "eng.em"; /** Declared on the channel, hired into the same kind as the coder, and never given work. */ const REVIEWER_SEAT = "eng.reviewer"; -/** Every member `CHANNEL.md` declares, in the order the fan-out walks them. */ -const DECLARED_MEMBERS = [COORDINATOR_SEAT, ASSIGNED_SEAT, REVIEWER_SEAT]; /** The feature, and the line an operator posts to ask for it. */ const ISSUE = "greeting-module"; @@ -743,9 +741,8 @@ await runGoal(async () => { coderSeatId: ASSIGNED_SEAT, runTimeoutMs: RUN_TIMEOUT_MS, logger: silentLogger, - // Only the EM is addressed. The coder and the reviewer are declared members - // of the channel and are true no-ops in the fan-out — recorded and skipped, - // never dispatched to. + // Only the EM is addressed. Every other declared member of the channel is a + // true no-op in the fan-out — recorded and skipped, never dispatched to. channels: { addresses: { [COORDINATOR_SEAT]: COORDINATOR_SEAT }, log: notifyLog }, harness: ({ cwd, resume, onSession }) => sequencer({ @@ -829,10 +826,12 @@ await runGoal(async () => { } if (failures.length > 0) return { failures, evidence: "" }; - // BR-8's positive half: exactly the EM was addressed, and the other two - // declared members were seen and skipped. Not an absence — a record. + // BR-8's positive half: exactly the EM was addressed, and every other + // declared member was seen and skipped. Not an absence — a record. const skipped = [...notifyLog.skipped].sort(); - const expectedSkips = DECLARED_MEMBERS.filter((m) => m !== COORDINATOR_SEAT).sort(); + // Every member the board's `CHANNEL.md` declares, read off the tree the lab opened. + const declaredMembers = (boardChannelOf(lab.roster).declared.members as string[] | undefined) ?? []; + const expectedSkips = declaredMembers.filter((m) => m !== COORDINATOR_SEAT).sort(); if (notifyLog.addressed.join(",") !== COORDINATOR_SEAT) { failures.push( `the fan-out addressed [${notifyLog.addressed.join(", ")}]; wanted only ${COORDINATOR_SEAT}`, From 1fdbfe858900f27282de461e13ffae97b124d66f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:55:07 +0000 Subject: [PATCH 11/19] goals(FIX-1663): the closure grades the project level FIX-1718 shipped Projects shipped (dfa9f460d), so the project level no longer draws four placeholder empty states. a3, b's and c's reach now open No project and each of the store's projects, read through the Lab's routes: No project's Stream and Brief show their named empty states, its Board's lanes and Workstreams list are the workstreams no project lists; a project's Stream is its room (or Join, or members only), its Board one lane per listed workstream holding a board with the store's rows, its Workstreams the row's list and its Brief the row's brief. J4 opens /p/unassigned's four tabs at their new surfaces. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../legs.mts | 58 +++++++++++++++++-- .../parts.mts | 11 +++- .../shell.mts | 15 ++++- 3 files changed, 74 insertions(+), 10 deletions(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts index 5e2cdd0469..f10d8fa676 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts @@ -222,12 +222,58 @@ export async function walkSurfaces( if ((await page.getByTestId(back).getAttribute("aria-pressed")) !== "true") reach(`the switch does not mark ${back} once clicked back`); } - // The project level: four tabs, each its named empty state. - await page.getByTestId("projects-heading").click(); - for (const tab of ["stream", "board", "workstreams", "brief"]) { - await page.locator(`[role=tab][data-tab=${tab}]`).click(); - if (!(await tabSelected(page, tab))) reach(`the project's ${tab} tab is not selected`); - if (!(await visible(page, `project-${tab}-empty`))) reach(`the project's ${tab} tab shows no named empty state`); + // The project level: No project, then each of the store's projects, in four + // tabs. A tab draws the store's content, or its named empty state when the + // store holds none: No project has no room and no brief. + const inProject = new Set(store.projects.flatMap((p) => p.workstreams)); + const levels = [ + { id: "unassigned", nav: "projects-heading", room: false, brief: null, workstreams: store.channels.map((c) => c.id).filter((id) => !inProject.has(id)) }, + ...store.projects.map((p) => ({ id: p.id, nav: `nav-project-${p.id}`, room: true, brief: p.brief, workstreams: p.workstreams })), + ]; + const holdsBoard = new Set(tree.channels.filter((c) => c.boardRefs.length > 0).map((c) => c.id)); + for (const level of levels) { + const where = level.id === "unassigned" ? "No project" : `project ${level.id}`; + await page.getByTestId(level.nav).click(); + if (!(await page.locator(`[data-testid=project][data-project-id="${level.id}"]`).waitFor({ timeout: 10_000 }).then(() => true, () => false))) { + reach(`${where} does not open`); + continue; + } + for (const tab of ["stream", "board", "workstreams", "brief"]) { + await page.locator(`[role=tab][data-tab=${tab}]`).click(); + if (!(await tabSelected(page, tab))) reach(`${where}'s ${tab} tab is not selected`); + if (tab === "stream") { + // A project's room as this person reaches it: read, or Join, or members only. No project has none. + const named = level.room ? "[data-testid=stream], [data-testid=project-stream-join], [data-testid=project-stream-members-only]" : "[data-testid=project-stream-none]"; + if (!(await page.locator(named).first().waitFor({ timeout: 10_000 }).then(() => true, () => false))) reach(`${where}'s Stream shows ${level.room ? "neither its room nor a named state" : "no named empty state"}`); + } else if (tab === "board") { + const lanesWanted = level.workstreams.filter((id) => holdsBoard.has(id)); + if (lanesWanted.length === 0) { + if (!(await visible(page, "project-board-none"))) reach(`${where} holds no board and its Board shows no named empty state`); + } else { + await page.getByTestId("project-lane").first().waitFor({ timeout: 10_000 }).catch(() => undefined); + const lanes = await attr(page, "project-lane", "data-channel-id"); + if (!same(lanes, lanesWanted)) reach(`${where}'s Board lanes: ${diff(lanesWanted, lanes)}`); + for (const id of lanesWanted) { + const cards = (await page.locator(`[data-testid=project-lane][data-channel-id="${id}"] [data-testid=board-card]`).evaluateAll((els) => els.map((e) => `${e.getAttribute("data-board-ref")}/${e.getAttribute("data-task-id")}`))) as string[]; + const want = (store.rows[id] ?? []).map((r) => `${r.ref}/${r.id}`); + if (!same(cards, want)) reach(`${where}'s ${id} lane: ${diff(want, cards)}`); + } + } + } else if (tab === "workstreams") { + if (level.workstreams.length === 0) { + if (!(await visible(page, "project-workstreams-none"))) reach(`${where} lists no workstream and says nothing`); + } else { + await page.getByTestId("project-workstream").first().waitFor({ timeout: 10_000 }).catch(() => undefined); + const listed = await attr(page, "project-workstream", "data-channel-id"); + if (!same(listed, level.workstreams)) reach(`${where}'s Workstreams: ${diff(level.workstreams, listed)}`); + } + } else if (level.brief === null) { + if (!(await visible(page, "project-brief-none"))) reach(`${where} has no brief and its Brief shows no named empty state`); + } else { + const shown = ((await page.getByTestId("project-brief").textContent({ timeout: 10_000 }).catch(() => null)) ?? "").trim(); + if (shown !== level.brief.trim()) reach(`${where}'s Brief reads "${shown.slice(0, 80)}", the row's is "${level.brief.slice(0, 80)}"`); + } + } } // Each workstream: four tabs, the right panel, the board, and the task level from a card. diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts index 8fe28d16c5..d22072fff1 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts @@ -254,11 +254,15 @@ export async function j4(scratch: string, pages: string, browser: Browser, repor if (row === undefined) return fail("DevForce filed no row after its ask was approved"); const ch = tree.channels[0]!.id; const task = `/tasks/${encodeURIComponent(row.ref)}/${encodeURIComponent(row.id)}`; - const addresses: Array<{ path: string; surface: string; owner: string }> = [ + const addresses: Array<{ path: string; surface: string | string[]; owner: string }> = [ { path: "/cos", surface: "cos", owner: "Chief of Staff (FIX-1719's seat; FIX-1722's view)" }, { path: "/roster", surface: "roster", owner: "TEAMS, workers, shift status (Workforce; FIX-1723)" }, { path: `/roster?team=${tree.teams[0]}`, surface: "roster", owner: "a team's workers (Workforce; FIX-1723)" }, - ...["stream", "board", "workstreams", "brief"].map((tab) => ({ path: `/p/unassigned/${tab}`, surface: `project-${tab}-empty`, owner: "projects (FIX-1650)" })), + // No project: no room and no brief, by name; its Board and Workstreams draw the workstreams no project lists, or say there are none. + { path: "/p/unassigned/stream", surface: "project-stream-none", owner: "No project's room (FIX-1718)" }, + { path: "/p/unassigned/board", surface: ["project-board", "project-board-none"], owner: "No project's board (FIX-1718)" }, + { path: "/p/unassigned/workstreams", surface: ["project-workstreams", "project-workstreams-none"], owner: "No project's workstreams (FIX-1718)" }, + { path: "/p/unassigned/brief", surface: "project-brief-none", owner: "No project's brief (FIX-1718)" }, { path: `/w/${encodeURIComponent(ch)}/stream`, surface: "workstream", owner: "a workstream (FIX-1650)" }, ...["board", "brief", "results"].map((tab) => ({ path: `/w/${encodeURIComponent(ch)}/${tab}`, surface: "workstream", owner: `a workstream's ${tab} (FIX-1651)` })), { path: "/inbox", surface: "inbox", owner: "Inbox (FIX-1652)" }, @@ -272,7 +276,8 @@ export async function j4(scratch: string, pages: string, browser: Browser, repor page.on("pageerror", (e) => errors.push(e.message)); try { await open(page, served.origin, address.path); - if (!(await page.getByTestId(address.surface).first().waitFor({ timeout: 15_000 }).then(() => true, () => false))) { + const surface = [address.surface].flat().map((id) => `[data-testid=${id}]`).join(", "); + if (!(await page.locator(surface).first().waitFor({ timeout: 15_000 }).then(() => true, () => false))) { fail(`${address.path} (${address.owner}) does not open its surface on a fresh load`); continue; } diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts index 7989c59c1d..7c1a018fc2 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts @@ -282,6 +282,8 @@ export type Store = { asks: StoredAsk[]; /** The organizations the person's sessions are bound to. */ orgs: string[]; + /** The organization's projects; none when no flow declares the collection. */ + projects: Array<{ id: string; title: string; brief: string | null; workstreams: string[] }>; }; /** Suspension reasons that are a person being asked something. */ @@ -301,6 +303,17 @@ export async function readStore(api: LabApi, tree: Tree, userId: string): Promis ? [] : (await api.collection(host, channelsRef)).map((r) => ({ id: String(r.id), kind: String(r.kind), members: Array.isArray(r.members) ? (r.members as string[]) : [] })); + const projectsRef = refOf("projects/*"); + const projects = + projectsRef === undefined + ? [] + : (await api.collection(host, projectsRef)).map((r) => ({ + id: String(r.id), + title: String(r.title), + brief: typeof r.brief === "string" ? r.brief : null, + workstreams: Array.isArray(r.workstreams) ? (r.workstreams as string[]) : [], + })); + const rows: Store["rows"] = {}; for (const channel of tree.channels) { rows[channel.id] = []; @@ -333,7 +346,7 @@ export async function readStore(api: LabApi, tree: Tree, userId: string): Promis } } } - return { seats, channels, rows, asks, orgs }; + return { seats, channels, rows, asks, orgs, projects }; } /** Whether a session holds a resume for `suspensionId`. */ From 600853cd27b3b9ddaebce94a32c781a1862fbb3c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 02:55:08 +0000 Subject: [PATCH 12/19] goals(FIX-1663): a1 and c read the Stream's ask card at feed-ask FIX-1737 C draws a member's pending ask in the feed as feed-ask; the stream-asks list is gone, so a1 found no card in the workstream's stream. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../a-lab-is-worked-through-one-skinned-shell/legs.mts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts index f10d8fa676..b9e2e36cc7 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts @@ -381,7 +381,7 @@ async function inboxJourney(page: Page, api: LabApi, store: Store, tree: Tree, s const detailText = ((await detailCard.textContent()) ?? "").trim(); if (workstream !== undefined) { await page.getByTestId(`nav-workstream-${workstream}`).click(); - const streamCard = page.locator(`[data-testid=stream-asks] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"]`); + const streamCard = page.locator(`[data-testid=feed-ask] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"]`); if (!(await streamCard.waitFor({ timeout: 10_000 }).then(() => true, () => false))) fail(`${workstream}'s stream shows no card for the ask`); else if (((await streamCard.textContent()) ?? "").trim() !== detailText) fail("the detail pane's card and the stream's card differ"); await page.getByTestId("nav-inbox").click(); @@ -398,9 +398,9 @@ async function inboxJourney(page: Page, api: LabApi, store: Store, tree: Tree, s if (!gone) fail("after Approve the ask is still listed in Inbox"); if (workstream !== undefined) { await page.getByTestId(`nav-workstream-${workstream}`).click(); - await page.getByTestId("stream-asks").waitFor({ timeout: 10_000 }).catch(() => undefined); + await page.locator(`[data-testid=workstream][data-channel-id="${workstream}"] [data-testid=stream]`).waitFor({ timeout: 10_000 }).catch(() => undefined); await sleep(500); - if ((await page.locator(`[data-testid=stream-asks] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"] button:not([disabled])`).count()) > 0) { + if ((await page.locator(`[data-testid=feed-ask] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"] button:not([disabled])`).count()) > 0) { fail(`${workstream}'s stream still offers an answer on the approved ask`); } } @@ -736,8 +736,8 @@ export async function legC(ctx: LegCtx): Promise { await sweep(page, { ask: `[data-testid=inbox-detail] ${SWEPT.ask}` }, tally); const workstream = tree.channels.find((c) => c.members.includes(ask.seat))!.id; await page.getByTestId(`nav-workstream-${workstream}`).click(); - await page.locator("[data-testid=stream-asks] [data-testid=ask-card]").waitFor().catch(() => undefined); - await sweep(page, { ask: `[data-testid=stream-asks] ${SWEPT.ask}` }, tally); + await page.locator("[data-testid=feed-ask] [data-testid=ask-card]").waitFor().catch(() => undefined); + await sweep(page, { ask: `[data-testid=feed-ask] ${SWEPT.ask}` }, tally); // Approve, so a run's Session and its trace page can be read. await page.getByTestId("nav-inbox").click(); await page.locator(`[data-testid=inbox-item][data-suspension-id="${ask.suspensionId}"]`).click(); From dd9054581faa9ecf5f5beef2882af26a72ff8da4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 03:08:31 +0000 Subject: [PATCH 13/19] goals(FIX-1663): a1 reads Inbox's detail as its question heading and its card Since FIX-1737 D, Inbox's detail draws the ask's question as its heading and hands the card the ask without it, while the Stream's card carries the question itself. a1 compared the two cards' text alone, so they always differed. It now requires the Stream's card to say the detail's question, and the rest of it to equal the detail's card. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../legs.mts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts index b9e2e36cc7..9ff80cc65d 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts @@ -378,12 +378,22 @@ async function inboxJourney(page: Page, api: LabApi, store: Store, tree: Tree, s fail("the detail pane draws no ask card for the selected ask"); return false; } - const detailText = ((await detailCard.textContent()) ?? "").trim(); + // Inbox's detail draws the ask's question as its heading and the card without it (FIX-1737 D); + // the stream's card carries the question itself. Together they must say the same. + const squash = (t: string | null) => (t ?? "").replace(/\s+/g, ""); + const detailTitle = squash(await page.getByTestId("inbox-detail-title").textContent().catch(() => null)); + const detailText = squash(await detailCard.textContent()); if (workstream !== undefined) { await page.getByTestId(`nav-workstream-${workstream}`).click(); const streamCard = page.locator(`[data-testid=feed-ask] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"]`); if (!(await streamCard.waitFor({ timeout: 10_000 }).then(() => true, () => false))) fail(`${workstream}'s stream shows no card for the ask`); - else if (((await streamCard.textContent()) ?? "").trim() !== detailText) fail("the detail pane's card and the stream's card differ"); + else { + const streamText = squash(await streamCard.textContent()); + const at = detailTitle === "" ? -1 : streamText.indexOf(detailTitle); + const rest = at < 0 ? streamText : streamText.slice(0, at) + streamText.slice(at + detailTitle.length); + if (at < 0) fail(`the stream's card does not say the detail pane's question "${detailTitle.slice(0, 80)}"`); + else if (rest !== detailText) fail(`the detail pane's card and the stream's card differ: "${detailText.slice(0, 120)}" / "${rest.slice(0, 120)}"`); + } await page.getByTestId("nav-inbox").click(); await item.click(); } From 6e0201344d6dd4acbb0001c0e81ec27dcacc0fdc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 04:18:20 +0000 Subject: [PATCH 14/19] test(goals): verdict log for the FIX-1663 closure on main a01a0b7bd (dd9054581) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../a-lab-is-worked-through-one-skinned-shell/goal.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md index 3939da1a6a..34c85b5c79 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -48,3 +48,7 @@ | 2026-10-04 | 3537738a7 (main a01a0b7bd, all four FIX-1737 slices, leg d wired) | Claude Code harness (a4), `claude` CLI (b0) | FAIL (findings) | **d PASS:** `it-draws-v2s-look` 141 rows, 21 exceptions, DevTeam 2 teams, 4 seats, 1 running, 1 ask pending; drift FAIL at surface + type only, unclassified and missing at totality only. **c's fence PASS** (day and night: message 20, reasoning 16, tool 51, code block 32, ask 5, devtool 165/164 elements, 0 Shift Manager values; static fence 0 hits in 2457 files). a4 delivered and answered in the run session; a2 drew only stored items from Tasks and Board; b's teams, post and org PASS; J3 PASS. **Findings, from main's merges, not the shell's look:** (1) a3, b:reach, c:reach and J4: the project level is no longer four placeholder empty states. Projects shipped (dfa9f460d, FIX-1718): `/p/unassigned` now draws `project-stream-none`, `project-brief-none`, the Board's lanes and the workstream list, and the goal still looks for `project--empty`. (2) a1: eng.em now sits in four channels (eng.feature, eng.triage, ops.oncall, ops.release, same commit), and the EM's ask carries no workstream session, so `workstreamsOf` falls back to every channel the seat is in and Inbox names all four. The Stream's ask card is `feed-ask` since FIX-1737 C (b2a3f387f), and a1 still reads `stream-asks`. (3) b0: the writer guessed 4 steps this time (answer/modelResolver, which store, the chief-of-staff seat, how `@flow-state-dev/engine` resolves). (4) Part 4 ER-15: two writes the seam doesn't name, `lib/talk.ts` `sendAction` (the project room, FIX-1718) and `lib/reads.ts` `createSession` (the room session, 3f357aafe FIX-1752). | | 2026-10-04 | 3537738a7 | as above | controls | today's main FAIL as expected (c's static half green). hardcoded-accent, static-names, optimistic-post, worker-session and no-org each go red at their own signal, but every one is **WRONG** because finding (1) and (2) also turn a1, a3, b:reach and c:reach red. The full run's driver ran out of heap (8 GB) after worker-session; no-org, part 3 and part 4 were rerun as separate processes on the same commit. | | 2026-10-04 | 3537738a7, f7269f548 (part 3's unanswerable-asks regex follows the child's renamed signal) | real model where each child names one | FAIL (part 3) | PASS with every control at its signal: design-system, it-opens-a-lab (static-names, optimistic-post, unanswerable-asks), it-sends-a-turn-into-a-seat-session, it-briefs-and-talks-with-the-chief-of-staff, it-shows-who-is-on-shift, it-hands-a-run-the-work-it-approved, both D1 children, devforce wakes and commits, pentest a-post-reaches, multi-seat-collab; design-system, registry and static tests, `pnpm typecheck` and `pnpm test`. **FAIL:** it-shows-and-stops-a-task-run and all three of its controls: `reach()` clicks the unclaimed row in Tasks, and Tasks hides queued rows until Queued is toggled (1c5fd250c, FIX-1737 D). it-takes-its-look-from-the-design-system (and its controls, 6 strays): the sidebar's `NavIcon` `` (f41cc0642, FIX-1737 B) leaves fill at the default `#000000`; its path paints with stroke only, but the check grades the computed fill. devforce it-ships-an-artifact: the fan-out skips chief-of-staff too, since FIX-1718 added it to eng.feature, and the goal's member list is hardcoded. pentest a-seat-answers: environmental, the AI Gateway answers 403 with `x-vercel-mitigated: deny` on every call (twice), while a direct gateway call is accepted. | +| 2026-10-04 | dd9054581 (main a01a0b7bd; the project level graded as FIX-1718 ships it, a1 on `feed-ask` and Inbox's titled detail, the three child fixes) | Claude Code harness (a4), `claude` CLI (b0) | FAIL (finding) | **a FAIL at a1 only:** Inbox names the EM's ask's workstream as "eng.feature, eng.triage, ops.oncall, ops.release" (the ask has no workstream session, so `workstreamsOf` names every channel eng.em is in); the specs leave that case open, so a1 still holds it to the asking seat's first channel pending a decision. The detail's question and card match the Stream's `feed-ask` card; approved, resume stored, gone from Inbox. a4 delivered and answered in the run session; a2 9 items drawn, all stored, from Tasks and Board, trace followed; a3 every surface, the project level now graded against the store (No project's room and brief named empty, its lanes and workstream list; Storefront and Platform's room, lanes, workstreams and brief). **b0 PASS** (no guesses this time, same flows, org, seats, workstream and user). **b, c, d, J3, J4 PASS** (c: message 20, reasoning 16, tool 51, code block 32, ask 11, devtool 165 elements, 0 Shift Manager values day and night; static fence 0 hits in 2457 files; d: 141 rows, drift red at surface + type only, unclassified and missing at totality only). | +| 2026-10-04 | dd9054581 | as above | controls | today's main FAIL as expected (c's static half green). Each other control is red at its own signal: hardcoded-accent (c:tool), static-names (b:teams, b:reach's Jump to Workers), optimistic-post (a4 + b:post), worker-session (a2, with c:sweep as goal.md allows), no-org (b:org). Every one is **WRONG** only because a1's open workstream finding is red in each. Run as its own process; no heap failure. | +| 2026-10-04 | dd9054581 | real model where each child names one | PASS (part 3) | 39 verdicts, all as expected: every child check passes and every child control fails at its named signal, including it-shows-and-stops-a-task-run (reach turns Queued on), it-takes-its-look-from-the-design-system (NavIcon paints no fill), devforce it-ships-an-artifact (expected skips read off the board channel's CHANNEL.md) and pentest a-seat-answers (the gateway answered this time). Design-system, registry and static tests, `pnpm typecheck` and `pnpm test` PASS. | +| 2026-10-04 | dd9054581 | none | FAIL (part 4) | ER-15 only: `lib/talk.ts` `sendAction` (the project room's read, post and join, FIX-1718) and `lib/reads.ts` `createSession` (the person's room session, FIX-1718 PR 3 and FIX-1752). Both are the shipped client routes on the person's own session on the channel kind, never a worker's session; held open pending the seam-list decision. Literal colours, pinned routes, one ask card, layer fence, final visuals and docs smoke PASS. | From 6c603093958d38d91e280fd2c891e3745194ada5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 04:21:30 +0000 Subject: [PATCH 15/19] goals(FIX-1663): a1 holds Inbox to every channel the asking seat is in Decided for the closure: an ask with no workstream session belongs to every channel the seat is a member of, because BR-18 draws its card on each of those Streams. a1 now reads the set from the store (the ask's parent channel when a post started it, else the seat's memberships), requires Inbox to name exactly that set, and checks the card on each of those Streams. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../goal.md | 2 +- .../legs.mts | 23 ++++++++++++++----- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md index 34c85b5c79..cfea9cb53b 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -8,7 +8,7 @@ **Signal:** each failure is tagged with its leg or part. -- **a1, the Inbox journey.** The EM seat's ask is in Inbox with its kind and workstream. The detail pane's card says what the workstream's stream card says. Approve leaves the resume stored and the ask gone from Inbox. +- **a1, the Inbox journey.** The EM seat's ask is in Inbox with its kind and its workstreams. An ask with no workstream session belongs to every channel the store lists its seat in, because FIX-1662's BR-18 draws its card on each of those Streams (decided for this closure, 2026-10-04); an ask a channel post started belongs to that channel. Inbox names exactly that set, and on each of those Streams the card says what the detail pane says (its question heading and its card). Approve leaves the resume stored and the ask gone from Inbox. - **a2, the task journey.** From Tasks, then from the workstream's Board: the task's Session tab draws only items the run session holds, the inspector's trace link is the in-process devtool's `?session=`, and following it opens that session. - **a3, reach.** Chief of Staff, the org switcher, Jump to, Inbox against the store's asks, Tasks in its three groupings, Roster for all teams and for each team row in TEAMS, PROJECTS, the Day/Night switch, the project level's four tabs, each workstream's four tabs, panel and Board against the store's rows, and the task frame's four tabs and panel slot. Every empty one names what will be there. - **a4, the `@worker` turn** (the one step on the real model). While the coder's task runs, `@coder ` in the workstream composer is in the running task session as a person's turn before the composer reads delivered, and the next attempt answers in that session. Never retried. diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts index 9ff80cc65d..91d85af3b9 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/legs.mts @@ -361,7 +361,13 @@ async function inboxJourney(page: Page, api: LabApi, store: Store, tree: Tree, s fail("no ask is pending in the store, so there is nothing to answer"); return false; } - const workstream = tree.channels.find((c) => c.members.includes(ask.seat))?.id; + // The ask's workstreams (BR-18, decided for FIX-1663): the channel whose post started the run when + // the ask's session has one as its parent, otherwise every channel the store lists the seat in. + const session = await api.get(`/sessions/${encodeURIComponent(ask.sessionId)}`); + const parent = (session.session ?? session).parentSessionId as string | null | undefined; + const memberOf = store.channels.filter((c) => c.members.includes(ask.seat)).map((c) => c.id); + const streams = parent != null && store.channels.some((c) => c.id === parent) ? [parent] : memberOf; + const workstream = streams[0]; await page.getByTestId("nav-inbox").click(); const item = page.locator(`[data-testid=inbox-item][data-suspension-id="${ask.suspensionId}"]`); if (!(await item.waitFor({ timeout: 15_000 }).then(() => true, () => false))) { @@ -371,7 +377,8 @@ async function inboxJourney(page: Page, api: LabApi, store: Store, tree: Tree, s const kind = (await item.getByTestId("inbox-item-kind").textContent()) ?? ""; const shownStream = (await item.getByTestId("inbox-item-workstream").textContent()) ?? ""; if (kind.trim() === "") fail("the ask's Inbox item names no kind"); - if (workstream !== undefined && shownStream.trim() !== workstream) fail(`the ask's Inbox item names workstream "${shownStream}", the asking seat's is ${workstream}`); + const named = shownStream.trim() === "no workstream" ? [] : shownStream.split(",").map((w) => w.trim()).filter(Boolean); + if (!same(named, streams)) fail(`the ask's Inbox item names workstreams ${diff(streams, named)}`); await item.click(); const detailCard = page.locator(`[data-testid=inbox-detail] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"]`); if (!(await detailCard.waitFor({ timeout: 10_000 }).then(() => true, () => false))) { @@ -383,17 +390,21 @@ async function inboxJourney(page: Page, api: LabApi, store: Store, tree: Tree, s const squash = (t: string | null) => (t ?? "").replace(/\s+/g, ""); const detailTitle = squash(await page.getByTestId("inbox-detail-title").textContent().catch(() => null)); const detailText = squash(await detailCard.textContent()); - if (workstream !== undefined) { - await page.getByTestId(`nav-workstream-${workstream}`).click(); + // The card is on each of those Streams, and says what Inbox's detail says. + for (const stream of streams) { + await page.getByTestId(`nav-workstream-${stream}`).click(); + await page.locator(`[data-testid=workstream][data-channel-id="${stream}"]`).waitFor({ timeout: 10_000 }).catch(() => undefined); const streamCard = page.locator(`[data-testid=feed-ask] [data-testid=ask-card][data-suspension-id="${ask.suspensionId}"]`); - if (!(await streamCard.waitFor({ timeout: 10_000 }).then(() => true, () => false))) fail(`${workstream}'s stream shows no card for the ask`); + if (!(await streamCard.waitFor({ timeout: 10_000 }).then(() => true, () => false))) fail(`${stream}'s stream shows no card for the ask`); else { const streamText = squash(await streamCard.textContent()); const at = detailTitle === "" ? -1 : streamText.indexOf(detailTitle); const rest = at < 0 ? streamText : streamText.slice(0, at) + streamText.slice(at + detailTitle.length); if (at < 0) fail(`the stream's card does not say the detail pane's question "${detailTitle.slice(0, 80)}"`); - else if (rest !== detailText) fail(`the detail pane's card and the stream's card differ: "${detailText.slice(0, 120)}" / "${rest.slice(0, 120)}"`); + else if (rest !== detailText) fail(`the detail pane's card and ${stream}'s card differ: "${detailText.slice(0, 120)}" / "${rest.slice(0, 120)}"`); } + } + if (streams.length > 0) { await page.getByTestId("nav-inbox").click(); await item.click(); } From c59c5749168ef4f93ef98c45cb75d25962758596 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 04:21:30 +0000 Subject: [PATCH 16/19] goals(FIX-1663): ER-15's seam list names the project room's writes, pinned to the room kind Decided for the closure: lib/talk.ts's sendAction (a project room's read, post and join, FIX-1718) and lib/reads.ts's createSession (the person's room session, FIX-1718 and FIX-1752) write only to the person's own sessions on the channel kind, never a worker's. Part 4 allows them only so: talk.ts sends once, through runTalkAction, for read, post or join; every room call passes ROOM_KIND; every createSession in reads.ts is on ROOM_KIND. ER-15's row in the epic's business rules lists the two. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../goal.md | 2 +- .../parts.mts | 26 ++++++++++++++++--- specs/epics/FIX-1649/BUSINESS-RULES.md | 2 +- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md index cfea9cb53b..405f780941 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -19,7 +19,7 @@ - **J3.** In a fresh host, `fsdev ui add tool approval` from the commit's registry gives byte-identical copies; with the docs' token block applied as written, changing `--success` repaints both. - **J4.** Every surface in the epic's ownership table opens by its address on a fresh load and shows rows or its named empty state; none blank, none refused. - **Part 3.** Every child's goal check with its controls, the goal labs the set touched, the design-system and registry tests, `pnpm typecheck` and `pnpm test`. -- **Part 4.** No literal colour in Shift Manager's source; the pinned routes; Shift Manager's only session writes; one ask card; the layer fence; the final visuals after the hand-back; the docs smoke. +- **Part 4.** No literal colour in Shift Manager's source; the pinned routes; Shift Manager's only session writes (ER-15's doors, plus the project room's read, post and join and the person's room session, each pinned to the room kind); one ask card; the layer fence; the final visuals after the hand-back; the docs smoke. **Anti-game:** a hollow pass would be a shell that draws its own rows, a no-theme build that removed more than the theme, or a control that never reaches the code it names. So no assertion reads Shift Manager's own state or a child's output: rows are compared by id with the store, read through the Lab's HTTP routes with the bearer the page was handed. Every scratch patch is printed in full. Each control must fail at its own signal and leave the rest green, or the run says WRONG. diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts index d22072fff1..097b774596 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/parts.mts @@ -356,15 +356,16 @@ export function part4(base: string, report: Report): void { // One session write path (ER-15): every write Shift Manager makes, by call and by module. const allowed: Record = { - "sendAction(": ["lib/send.ts", "lib/transcript.ts"], + "sendAction(": ["lib/send.ts", "lib/transcript.ts", "lib/talk.ts"], "abortRequest(": ["lib/run.ts"], "resumeSuspension(": ["lib/reads.ts"], + "createSession(": ["lib/reads.ts"], }; const writes: string[] = []; for (const file of own) { const text = stripComments(readFileSync(file, "utf8")); const rel = relative(src, file).replace(/\\/g, "/"); - for (const call of [...Object.keys(allowed), "createSession(", "appendItem(", "saveItem(", "/actions/"]) { + for (const call of [...Object.keys(allowed), "appendItem(", "saveItem(", "/actions/"]) { if (!text.includes(call)) continue; writes.push(`${rel} ${call}`); if (!(allowed[call] ?? []).includes(rel)) report.fail("P4:ER-15", `${rel} writes through ${call}, outside the doors ER-15 names`); @@ -372,7 +373,26 @@ export function part4(base: string, report: Report): void { } const transcriptPost = /sendAction\("post"/.test(readFileSync(join(src, "lib", "transcript.ts"), "utf8")); if (!transcriptPost) report.fail("P4:ER-15", "lib/transcript.ts sends something other than the channel's post"); - report.note(`P4 ER-15: Shift Manager's writes are [${writes.join("; ")}]: the seat's door (send.ts), the channel's post (transcript.ts), Interrupt's abort (run.ts) and the one resume (reads.ts); Inbox's reply is graded by FIX-1690's check in part 3`); + // The project room (FIX-1718): talk.ts sends one action, through runTalkAction, and only read, + // post or join; every caller hands its room functions the room kind. The person's own session, never a worker's. + const talk = stripComments(readFileSync(join(src, "lib", "talk.ts"), "utf8")); + const talkSends = talk.match(/\bsendAction\(/g)?.length ?? 0; + const talkCalls = [...talk.matchAll(/\brunTalkAction\(\s*clients,\s*kind,\s*[^,]+,\s*("?)(\w+)\1/g)].map((m) => (m[1] === '"' ? m[2]! : `<${m[2]}>`)); + const talkRuns = (talk.match(/\brunTalkAction\(/g)?.length ?? 0) - 1; // less its definition + if (talkSends !== 1 || !/sendAction\(action, input, \{ sessionId: session \}\)/.test(talk)) report.fail("P4:ER-15", `lib/talk.ts sends ${talkSends} action(s) outside runTalkAction's one send`); + const offTalk = talkCalls.filter((a) => !["read", "post", "join"].includes(a)); + if (offTalk.length > 0 || talkCalls.length !== talkRuns) report.fail("P4:ER-15", `lib/talk.ts runs talk actions other than read, post and join: [${offTalk.join(", ")}]${talkCalls.length !== talkRuns ? `, ${talkRuns - talkCalls.length} unread` : ""}`); + const roomCalls = own + .filter((f) => !f.endsWith(join("lib", "talk.ts"))) + .flatMap((f) => [...stripComments(readFileSync(f, "utf8")).matchAll(/\b(readRoom|postToRoom|joinRoom)\(\s*clients,\s*([^,)]+)/g)].map((m) => `${relative(src, f)} ${m[1]}(${m[2]!.trim()})`)); + const offRoom = roomCalls.filter((c) => !c.endsWith("(ROOM_KIND)")); + if (offRoom.length > 0) report.fail("P4:ER-15", `a talk action runs on a kind other than the room kind: ${offRoom.join("; ")}`); + // The person's room session (FIX-1718, FIX-1752): reads.ts creates sessions on the room kind only. + const reads = stripComments(readFileSync(join(src, "lib", "reads.ts"), "utf8")); + const creates = [...reads.matchAll(/\bcreateSession\(\s*\{([^}]*)\}/g)].map((m) => m[1]!); + const createCount = reads.match(/\bcreateSession\(/g)?.length ?? 0; + if (createCount !== creates.length || creates.some((args) => !/\bflowKind:\s*ROOM_KIND\b/.test(args))) report.fail("P4:ER-15", "lib/reads.ts creates a session on a kind other than the room kind"); + report.note(`P4 ER-15: Shift Manager's writes are [${writes.join("; ")}]: the seat's door (send.ts), the channel's post (transcript.ts), the project room's ${talkCalls.join("/")} on the room kind (talk.ts; ${roomCalls.length} call(s)), the person's room session (reads.ts; ${creates.length} createSession on ROOM_KIND), Interrupt's abort (run.ts) and the one resume (reads.ts); Inbox's reply is graded by FIX-1690's check in part 3`); // One ask rendering: Inbox's detail and the stream's card draw through AskCard. for (const surface of ["Inbox.tsx", "Stream.tsx", "ChiefOfStaff.tsx"]) { diff --git a/specs/epics/FIX-1649/BUSINESS-RULES.md b/specs/epics/FIX-1649/BUSINESS-RULES.md index 6b907eb697..2b06ad3bf4 100644 --- a/specs/epics/FIX-1649/BUSINESS-RULES.md +++ b/specs/epics/FIX-1649/BUSINESS-RULES.md @@ -23,7 +23,7 @@ checks. Each says who owns it and where it's checked. | ER-6 | No child restyles an FSD component or hardcodes paint on it inside App Lab. Registry components arrive by `fsdev ui add` and stay unedited copies of their source; a component that can't take the skin is fixed at its source by FIX-1655 and re-synced, and FIX-1655's re-sync check fails on any App Lab copy that differs from its source | [D2](DECISIONS.md#d2). A restyled copy drifts from every later FSD fix, and a stale one makes leg c test the copy, not the skin | | ER-7 | No child adds an L1 noun (Agent, Team, Channel, MessageBoard, Project-as-required) or puts Workforce concepts into `core` or `engine`; the design-system package imports nothing from `@flow-state-dev/workforce` | Jake's layer rule. L1 offers generic hooks only | | ER-8 | No child builds anything below [the box's fence](SPEC.md#whats-in-the-box), and none adds `CHANNELS.md` or `kind:` frontmatter | The PRD's and the Architect's invent-kills, and D-12; the fence is their one list | -| ER-15 | No child writes into a worker's session except through that session's shipped operations: a turn from the task composer, a workstream's `@worker` or a reply from Inbox, Interrupt, Hand off. The shell writes no session item of its own and shows a message as delivered only when the session says so. Owned by FIX-1664; FIX-1662's composers (a workstream's, Inbox's reply) consume it | A second write path into a harness session is a model the shell invented; the stream's "sent into PAY-14" line must be the session's answer, not the shell's hope | +| ER-15 | No child writes into a worker's session except through that session's shipped operations: a turn from the task composer, a workstream's `@worker` or a reply from Inbox, Interrupt, Hand off. The shell writes no session item of its own and shows a message as delivered only when the session says so. Owned by FIX-1664; FIX-1662's composers (a workstream's, Inbox's reply) consume it. Two writes go to the person's own sessions, never a worker's:
· a project room's `read`, `post` and `join`, on the room kind (FIX-1718)
· opening the person's room session, on the room kind (FIX-1718, FIX-1752) | A second write path into a harness session is a model the shell invented; the stream's "sent into PAY-14" line must be the session's answer, not the shell's hope | ## How the set is run From 25d026528d72c755b80a378a70df4ab859e2c63b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 04:21:30 +0000 Subject: [PATCH 17/19] docs(shift-manager): the devteam excerpt shows the SQLite store devteam opens The excerpt said stores: inMemoryStores(), while the devteam profile opens sqliteStores({ filename: STORE }). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- labs/shift-manager/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/labs/shift-manager/README.md b/labs/shift-manager/README.md index fba77ed8b9..404824b902 100644 --- a/labs/shift-manager/README.md +++ b/labs/shift-manager/README.md @@ -70,7 +70,7 @@ A host module can do some of this setup for you. When its options say they open ```ts title="teams/devteam/fsdev.config.mts (excerpt)" const lab = await openLab({ - stores: inMemoryStores(), + stores: sqliteStores({ filename: STORE }), inventory: true, // its host opens the channels, then the inventory devtool: true, // its host hands the page the Lab's user // ...options of its own From 49fd744e387d28095c35123f548eb33f43f2439f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 4 Oct 2026 05:32:25 +0000 Subject: [PATCH 18/19] test(goals): verdict log for the FIX-1663 closure on main a01a0b7bd (25d026528): PASS Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cnm5DbhFmkarpesBpPQ9Dq --- .../a-lab-is-worked-through-one-skinned-shell/goal.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md index 405f780941..c483e5d3ba 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/goal.md @@ -52,3 +52,7 @@ | 2026-10-04 | dd9054581 | as above | controls | today's main FAIL as expected (c's static half green). Each other control is red at its own signal: hardcoded-accent (c:tool), static-names (b:teams, b:reach's Jump to Workers), optimistic-post (a4 + b:post), worker-session (a2, with c:sweep as goal.md allows), no-org (b:org). Every one is **WRONG** only because a1's open workstream finding is red in each. Run as its own process; no heap failure. | | 2026-10-04 | dd9054581 | real model where each child names one | PASS (part 3) | 39 verdicts, all as expected: every child check passes and every child control fails at its named signal, including it-shows-and-stops-a-task-run (reach turns Queued on), it-takes-its-look-from-the-design-system (NavIcon paints no fill), devforce it-ships-an-artifact (expected skips read off the board channel's CHANNEL.md) and pentest a-seat-answers (the gateway answered this time). Design-system, registry and static tests, `pnpm typecheck` and `pnpm test` PASS. | | 2026-10-04 | dd9054581 | none | FAIL (part 4) | ER-15 only: `lib/talk.ts` `sendAction` (the project room's read, post and join, FIX-1718) and `lib/reads.ts` `createSession` (the person's room session, FIX-1718 PR 3 and FIX-1752). Both are the shipped client routes on the person's own session on the channel kind, never a worker's session; held open pending the seam-list decision. Literal colours, pinned routes, one ask card, layer fence, final visuals and docs smoke PASS. | +| 2026-10-04 | 25d026528 (main a01a0b7bd; a1 on the decided workstream set, ER-15's room writes pinned, the devteam README excerpt) | Claude Code harness (a4), `claude` CLI (b0) | **PASS** | **a PASS:** a1 approval ask from eng.em, Inbox names exactly the store's memberships [eng.feature, eng.triage, ops.oncall, ops.release] and the card on each of those four Streams says what the detail says; approved, resume stored, gone from Inbox. a4 delivered (held when drawn) and answered in the run session; a2 7 and 8 items drawn, all stored, from Tasks and Board, trace followed; a3 every surface, the project level against the store. **b0 PASS** (no guesses). **b, c, d, J3, J4 PASS** (c: message 20, reasoning 16, tool 51, code block 32, ask 11, devtool 165/164 elements, 0 Shift Manager values; static fence 0 hits in 2457 files; d: 141 rows, drift red at surface + type only, unclassified and missing at totality only; J4 17 addresses). | +| 2026-10-04 | 25d026528 | as above | controls | All six RIGHT: today's main FAIL as expected (c's static half green); hardcoded-accent at c:tool only; static-names at b:teams only; optimistic-post at a4 + b:post only; worker-session at a2 only; no-org at b:org only. Each ran in the controls' own process. | +| 2026-10-04 | 25d026528 | real model where each child names one | PASS (part 3) | 39 verdicts, all as expected: every child check passes (pentest a-seat-answers included) and every child control fails at its named signal; design-system, registry and static tests, `pnpm typecheck` and `pnpm test` PASS. | +| 2026-10-04 | 25d026528 | none | PASS (part 4) | ER-15: the seat's door, the channel's post, the project room's read/post/join on the room kind (3 calls), the person's room session (2 `createSession` on `ROOM_KIND`), Interrupt's abort and the one resume. Negatives on 6e0201344's tree, each reverted: a `hire` talk action, `joinRoom(clients, "agent")` in Project.tsx, `createSession({ flowKind: "agent" })` in reads.ts, and a second `sendAction` in talk.ts each turned part 4 red at P4:ER-15 alone. Literal colours, pinned routes, one ask card, layer fence, final visuals and docs smoke PASS. | From 34d0034744a0b2de220847741a136a038b5f4f7a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 4 Oct 2026 05:48:18 +0000 Subject: [PATCH 19/19] POC: closure shell uses the shared Shift Manager helper Patch builds and the Lab route client call goals/lib/shift-manager.mts. The no-theme swap build calls that same build instead of pasting the Vite plugin. Co-authored-by: Jake Hoffner --- goals/lib/shift-manager.mts | 7 +- .../run.mts | 55 +----- .../shell.mts | 176 ++++++------------ 3 files changed, 72 insertions(+), 166 deletions(-) diff --git a/goals/lib/shift-manager.mts b/goals/lib/shift-manager.mts index dc2b8ab2d0..2a5f44cb53 100644 --- a/goals/lib/shift-manager.mts +++ b/goals/lib/shift-manager.mts @@ -160,12 +160,13 @@ export function labApi(origin: string, bearer: string | undefined) { } return rows; }; - /** Every item of the given types in one session, oldest first. */ - const items = async (sessionId: string, types: string[]): Promise>> => { + /** Every item in one session, oldest first. `types` limits the query to those item types; omit it for every type. */ + const items = async (sessionId: string, types: string[] = []): Promise>> => { const out: Array> = []; + const typeQuery = types.length === 0 ? "" : `&item_types=${types.join(",")}`; for (let offset = 0, page = 0; page < 100; page += 1) { const body = await get( - `/sessions/${encodeURIComponent(sessionId)}/state?include_items=true&item_types=${types.join(",")}&offset=${offset}&limit=200`, + `/sessions/${encodeURIComponent(sessionId)}/state?include_items=true${typeQuery}&offset=${offset}&limit=200`, ); out.push(...(body.items ?? [])); if (body.pagination?.hasMore !== true) break; diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts index 6d245076a3..3e40d534c9 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/run.mts @@ -32,14 +32,14 @@ import { execFileSync, spawn } from "node:child_process"; import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { join, relative } from "node:path"; -import { fileURLToPath } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; import { REPO_ROOT, goalTmpDir, runGoal } from "../../lib/index.mts"; import { readShiftManagerTheme } from "../../lib/colour.mts"; import { launchChromium } from "../../lib/playwright.mts"; import { PENTEST_CONFIG, TREES, legA, legB, legC, staticFence, type LegCtx, type Report } from "./legs.mts"; import { j3, j4, part4 } from "./parts.mts"; -import { SHIFT_MANAGER, buildPages, injected, labApi, open, readStore, readTree, startShiftManager, type Built, type Patch, type Swap } from "./shell.mts"; +import { SHIFT_MANAGER, THEME_IMPORT, buildPages, injected, labApi, open, readStore, readTree, startShiftManager, type Built, type Patch, type Swap } from "./shell.mts"; const HERE = fileURLToPath(new URL(".", import.meta.url)); const SCRATCH = goalTmpDir("shift-manager-closure"); @@ -82,7 +82,6 @@ function legVerdict(id: string, prefix: string[], report: ReturnType */ async function swapBuild(name: string, swap: Swap, noTheme: boolean, staticSeats?: Array<{ id: string; kind: string }>): Promise { if (!noTheme) return buildPages(SCRATCH, name, { swap, staticSeats }); - // In a process of its own: Tailwind's Vite plugin keeps a stylesheet's - // compiled CSS per file across builds in one process, so this build would - // otherwise ship the themed build's CSS for the same \`src/styles.css\`. + // Tailwind's Vite plugin keeps a stylesheet's compiled CSS per file across + // builds in one process, so the no-theme swap runs in a child that calls the same build. const pages = join(SCRATCH, name, "pages"); const script = join(SCRATCH, name, "build.mts"); mkdirSync(join(SCRATCH, name), { recursive: true }); writeFileSync( script, - `import { createRequire } from "node:module"; -import { readFileSync } from "node:fs"; -import { pathToFileURL } from "node:url"; -const [root, outDir, target, withFile, seats] = ${JSON.stringify([SHIFT_MANAGER, pages, swap.target, swap.with, staticSeats ?? []])}; -const THEME_IMPORT = ${THEME_IMPORT.toString()}; -const vite = await import(pathToFileURL(createRequire(root + "/package.json").resolve("vite")).href); -let swapped = 0; -const hit = new Set(); -let stripped = 0; -await vite.build({ - root, - configFile: root + "/vite.config.ts", - logLevel: "error", - build: { outDir, emptyOutDir: true }, - define: { __STATIC_SEATS__: JSON.stringify(seats) }, - plugins: [ - { - name: "goal-control-swap", - enforce: "pre", - async resolveId(source, importer, opts) { - if (importer === undefined || importer === withFile) return null; - const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true }); - if (resolved?.id === undefined || ![target].flat().includes(resolved.id)) return null; - hit.add(resolved.id); - swapped += 1; - return withFile; - }, - }, - { - name: "goal-no-theme", - enforce: "pre", - load(id) { - if (id.includes("?") || !id.endsWith("/src/styles.css")) return null; - const code = readFileSync(id, "utf8"); - const out = code.replace(THEME_IMPORT, ""); - if (out !== code) stripped += 1; - return out; - }, - }, - ], -}); -if (swapped === 0 || [target].flat().some((t) => !hit.has(t))) throw new Error("the build never imported " + [target].flat().filter((t) => !hit.has(t)).join(", ")); -if (stripped === 0) throw new Error("the theme import was never removed"); + `import { buildPages } from ${JSON.stringify(pathToFileURL(join(HERE, "shell.mts")).href)}; +await buildPages(${JSON.stringify(SCRATCH)}, ${JSON.stringify(name)}, ${JSON.stringify({ swap, staticSeats: staticSeats ?? [], stripTheme: true })}); `, ); try { diff --git a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts index 7c1a018fc2..d2527939b9 100644 --- a/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts +++ b/goals/shift-manager/a-lab-is-worked-through-one-skinned-shell/shell.mts @@ -1,27 +1,24 @@ /** - * The closure check's scaffolding: building Shift Manager (as written, with a - * scratch patch, or with a control module swapped in), serving it over a Lab - * with its own start script, reading the Lab's store through its HTTP routes, - * and reading what Chromium paints. + * The closure check's scaffolding: building Shift Manager, serving it over a + * Lab, reading the store through the Lab's routes, and reading what Chromium paints. * - * Every piece is lifted from the child checks under `goals/shift-manager/` - * (`it-opens-a-lab` for the swap build, the start script and the store reads; - * `it-takes-its-look-from-the-design-system` for the scratch-copy build and - * the colour sweep; `it-sends-a-turn-into-a-seat-session` for watching a - * composer settle). Their run files execute on import, so the helpers are - * lifted here rather than imported. The grading lives in `legs.mts`. + * Patch builds and the route client come from `goals/lib/shift-manager.mts`. + * The start script stays here: `--team` or `--config`, an optional `--shift`, + * a fresh DevTeam sqlite in the work dir, and the devtool URL on the ready line. + * The grading lives in `legs.mts`. */ import { execFileSync, spawn, type ChildProcess } from "node:child_process"; -import { cpSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync } from "node:fs"; import { createRequire } from "node:module"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import type { Page } from "playwright"; import { readDeclaredRoster } from "@flow-state-dev/workforce/loader"; import { REPO_ROOT, intentFreeEnv } from "../../lib/index.mts"; +import { SHIFT_MANAGER, buildShiftManagerCopy, labApi as labRoutes, type Patch } from "../../lib/shift-manager.mts"; + +export { SHIFT_MANAGER, type Patch }; -/** Shift Manager's package, in this checkout. */ -export const SHIFT_MANAGER = join(REPO_ROOT, "labs", "shift-manager"); const TSX = join(REPO_ROOT, "node_modules", ".bin", "tsx"); export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -37,8 +34,9 @@ export const diff = (want: Iterable, got: Iterable) => { // ---- building ---------------------------------------------------------------- -/** One edit to a scratch copy of Shift Manager. A patch that matches nothing fails the setup. */ -export type Patch = { file: string; from: string | RegExp; to: string; why: string }; +/** The design-system import leg c removes, as a scratch patch or in the bundler when a swap build cannot use a copy. */ +export const THEME_IMPORT = /^@import "@flow-state-dev\/design-system\/shift-manager\.css";\n/m; + /** A source module swapped for a control module at build time (a child check's control). */ export type Swap = { target: string | string[]; with: string }; /** A build: where its pages are, and the full diff of every patch applied to it. */ @@ -53,73 +51,73 @@ async function vite() { /** * Build Shift Manager's pages into `scratch/`. * - * - With `patches`, Shift Manager is copied to scratch and patched there, - * never in the checkout (Tailwind reads class names off the files on disk, - * so a patch has to land in a copy). The diff of every patched file is - * returned in full, for the report. - * - With `swap`, the build runs from the checkout and one module is swapped - * for a control module, as the child checks' controls do. The build fails - * if the swap never fired. - * - `staticSeats` feeds the `static-names` control module its written-in list. + * `patches` go through {@link buildShiftManagerCopy}. The unified diff of each + * patched file is what the report prints. + * + * `swap` builds from the checkout and replaces one module. `staticSeats` is the + * list the `static-names` control reads. `stripTheme` drops {@link THEME_IMPORT} + * in the bundler, for a swap build that cannot use a scratch copy. */ export async function buildPages( scratch: string, name: string, - options: { patches?: Patch[]; swap?: Swap; staticSeats?: Array<{ id: string; kind: string }> } = {}, + options: { patches?: Patch[]; swap?: Swap; staticSeats?: Array<{ id: string; kind: string }>; stripTheme?: boolean } = {}, ): Promise { const pages = join(scratch, name, "pages"); - const define = { __STATIC_SEATS__: JSON.stringify(options.staticSeats ?? []) }; const patches = options.patches ?? []; if (patches.length === 0) { let swapped = 0; const hit = new Set(); + const theme = { stripped: 0 }; const swap = options.swap; + const plugins: Array> = []; + if (swap !== undefined) { + plugins.push({ + name: "goal-control-swap", + enforce: "pre", + async resolveId(this: any, source: string, importer: string | undefined, opts: Record) { + if (importer === undefined || importer === swap.with) return null; + const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true }); + if (resolved?.id === undefined || ![swap.target].flat().includes(resolved.id)) return null; + hit.add(resolved.id); + swapped += 1; + return swap.with; + }, + }); + } + if (options.stripTheme === true) { + plugins.push({ + name: "goal-no-theme", + enforce: "pre", + load(id: string) { + if (id.includes("?") || !id.endsWith("/src/styles.css")) return null; + const code = readFileSync(id, "utf8"); + const out = code.replace(THEME_IMPORT, ""); + if (out !== code) theme.stripped += 1; + return out; + }, + }); + } await (await vite()).build({ root: SHIFT_MANAGER, configFile: join(SHIFT_MANAGER, "vite.config.ts"), logLevel: "error", build: { outDir: pages, emptyOutDir: true }, - define, - plugins: - swap === undefined - ? [] - : [ - { - name: "goal-control-swap", - enforce: "pre", - async resolveId(this: any, source: string, importer: string | undefined, opts: Record) { - if (importer === undefined || importer === swap.with) return null; - const resolved = await this.resolve(source, importer, { ...opts, skipSelf: true }); - if (resolved?.id === undefined || ![swap.target].flat().includes(resolved.id)) return null; - hit.add(resolved.id); - swapped += 1; - return swap.with; - }, - }, - ], + define: { __STATIC_SEATS__: JSON.stringify(options.staticSeats ?? []) }, + plugins, }); const missed = swap === undefined ? [] : [swap.target].flat().filter((t) => !hit.has(t)); if (swapped === 0 && swap !== undefined || missed.length > 0) throw new Error(`setup [${name}]: the build never imported ${missed.join(", ")}, so nothing was swapped`); + if (options.stripTheme === true && theme.stripped === 0) throw new Error("the theme import was never removed"); return { pages, diff: "" }; } - const root = join(scratch, name, "shift-manager"); - cpSync(SHIFT_MANAGER, root, { recursive: true, filter: (src) => !/[/\\](node_modules|dist)$/.test(src) }); - symlinkSync(join(SHIFT_MANAGER, "node_modules"), join(root, "node_modules")); - // The copy sits outside the workspace; its tsconfig still extends the workspace's. - const tsconfig = join(root, "tsconfig.json"); - writeFileSync(tsconfig, readFileSync(tsconfig, "utf8").replace('"../../tsconfig.base.json"', JSON.stringify(join(REPO_ROOT, "tsconfig.base.json")))); - const diffs: string[] = []; - for (const patch of patches) { - const path = join(root, patch.file); - const before = readFileSync(path, "utf8"); - const after = before.replace(patch.from, patch.to); - if (after === before) throw new Error(`setup [${name}]: ${patch.why}, but ${patch.file} has nothing to patch (looked for ${String(patch.from)})`); - writeFileSync(path, after); - diffs.push(`# ${patch.why}\n${unifiedDiff(join(SHIFT_MANAGER, patch.file), path, `labs/shift-manager/${patch.file}`)}`); - } - await (await vite()).build({ root, configFile: join(root, "vite.config.ts"), logLevel: "error", build: { outDir: pages, emptyOutDir: true }, define }); - return { pages, diff: diffs.join("\n") }; + const built = await buildShiftManagerCopy(scratch, name, patches); + const diffs = patches.map((patch) => { + const patched = join(scratch, name, "shift-manager", patch.file); + return `# ${patch.why}\n${unifiedDiff(join(SHIFT_MANAGER, patch.file), patched, `labs/shift-manager/${patch.file}`)}`; + }); + return { pages: built.pages, diff: diffs.join("\n") }; } /** `diff -u` of the checkout's file against its patched copy, labelled with the repo path. */ @@ -186,62 +184,12 @@ export async function startShiftManager( // ---- the store, read by this script ----------------------------------------- -/** GET/POST against the Lab's routes, with the page's bearer when the Lab has one. */ +/** The shared Lab routes, plus whether a session holds a message of `role` containing `needle`. */ export function labApi(origin: string, bearer: string | undefined) { - const enc = encodeURIComponent; - const call = async (method: string, path: string, body?: unknown): Promise<{ status: number; body: any }> => { - const response = await fetch(`${origin}/api/flows${path}`, { - method, - headers: { "content-type": "application/json", ...(bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }) }, - ...(body === undefined ? {} : { body: JSON.stringify(body) }), - }); - const text = await response.text(); - if (text.length === 0) return { status: response.status, body: null }; - try { - return { status: response.status, body: JSON.parse(text) }; - } catch { - throw new Error(`${method} ${path}: ${response.status}, and the body is not JSON: ${text.slice(0, 200)}`); - } - }; - const get = async (path: string): Promise => { - const { status, body } = await call("GET", path); - if (status !== 200) throw new Error(`GET ${path}: ${status} ${JSON.stringify(body)}`); - return body; - }; - /** Every row of a collection, through one session, page by page. */ - const collection = async (sessionId: string, ref: string): Promise>> => { - const rows: Array> = []; - let cursor: string | undefined; - for (let page = 0; page < 100; page += 1) { - const body = await get(`/sessions/${enc(sessionId)}/resources/${enc(ref)}?limit=200${cursor === undefined ? "" : `&cursor=${enc(cursor)}`}`); - rows.push(...((body.items ?? []) as Array<{ clientData?: Record }>).map((i) => i.clientData ?? {})); - if (body.nextCursor === undefined || body.nextCursor === null || body.nextCursor === cursor) break; - cursor = body.nextCursor; - } - return rows; - }; - /** Every item of the given types in one session, oldest first (all types when none are given). */ - const items = async (sessionId: string, types: string[] = []): Promise>> => { - const out: Array> = []; - for (let offset = 0, page = 0; page < 100; page += 1) { - const filter = types.length === 0 ? "" : `&item_types=${types.join(",")}`; - const body = await get(`/sessions/${enc(sessionId)}/state?include_items=true${filter}&offset=${offset}&limit=200`); - out.push(...(body.items ?? [])); - if (body.pagination?.hasMore !== true) break; - offset = body.pagination.nextOffset ?? offset + 200; - } - return out; - }; - /** Whether the session holds a message of `role` whose content contains `needle`. */ + const api = labRoutes(origin, bearer); const holds = async (sessionId: string, role: string, needle: string): Promise => - (await items(sessionId, ["message"])).some((m) => m.role === role && JSON.stringify(m.content ?? m.text ?? m).includes(needle)); - const ownerOf = async (sessionId: string): Promise => { - const body = await get(`/sessions/${enc(sessionId)}`); - return String((body.session ?? body).flowId); - }; - const requestStatus = async (flowId: string, requestId: string): Promise => - String((await get(`/${enc(flowId)}/requests/${enc(requestId)}/status`)).status); - return { call, get, collection, items, holds, ownerOf, requestStatus }; + (await api.items(sessionId, ["message"])).some((m) => m.role === role && JSON.stringify(m.content ?? m.text ?? m).includes(needle)); + return { ...api, holds }; } export type LabApi = ReturnType;