diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7fe3a09077..274b93035f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -69,6 +69,12 @@ jobs: working-directory: packages/artifact-canvas run: pnpm test + # Spec 1963: the shared Work and Decisions views. Source-exported (no build step); its + # tests include the import-boundary guard, and check-types covers the tests as well. + - name: Type-check and test workspace-views package + working-directory: packages/workspace-views + run: pnpm check-types && pnpm test + - name: Copy skeleton for unit tests working-directory: packages/codev run: pnpm copy-skeleton @@ -106,6 +112,14 @@ jobs: working-directory: apps/vscode run: pnpm test:unit + # Spec 1963: the Cockpit's rendered-verification harness runs by hand only (it needs a + # browser, VS Code and its own Tower); CI at least keeps every script of it parsing. + - name: Syntax-check the cockpit harness + working-directory: apps/vscode/scripts/cockpit-harness + run: | + for f in *.mjs *.cjs stubs/*.mjs; do node --check "$f" || exit 1; done + for f in stubs/afx stubs/codev stubs/porch; do sh -n "$f" || exit 1; done + # Streamdeck check-types resolves the sdk's dist .d.ts — the "Build sdk # package" step above must stay ahead of these. - name: Type-check streamdeck plugin diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 72c1021e3a..0432b90266 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -242,6 +242,12 @@ jobs: working-directory: packages/core run: pnpm test + # Spec 1963: the VS Code webview path containment (realpath + path.relative) on real Windows + # paths: drive-letter case, separators and a directory junction leading outside the workspace. + - name: Run vscode webview path-containment tests + working-directory: apps/vscode + run: pnpm exec vitest run src/__tests__/workspace-views-security.test.ts + - name: Copy skeleton for unit tests working-directory: packages/codev run: pnpm copy-skeleton diff --git a/apps/vscode/.vscodeignore b/apps/vscode/.vscodeignore index 159277f024..e6e1799f77 100644 --- a/apps/vscode/.vscodeignore +++ b/apps/vscode/.vscodeignore @@ -6,9 +6,12 @@ src/** .gitignore .yarnrc esbuild.js +esbuild.webview.cjs vsc-extension-quickstart.md **/tsconfig.json +**/tsconfig.*.json **/eslint.config.mjs **/*.map **/*.ts **/.vscode-test.* +scripts/cockpit-harness/** diff --git a/apps/vscode/CHANGELOG.md b/apps/vscode/CHANGELOG.md index dd67dd2ca2..a13f03f659 100644 --- a/apps/vscode/CHANGELOG.md +++ b/apps/vscode/CHANGELOG.md @@ -1,5 +1,19 @@ # Change Log +## [Unreleased] + +### What's new + +- **Codev Cockpit: the whole fleet in one tree.** A new button below Codev opens Tower → workspaces → architects → builders → changed files. This window's workspace keeps every action of the Workspace and Agents views, and another workspace's rows open that workspace's window (#1963). +- **Work and Decisions in VS Code.** `Codev: Open Work` and `Codev: Open Decisions` (or the Cockpit's Decisions entry) open the dashboard's Work and Decisions views in the editor area, in your color theme. Rule on decisions, open a builder's terminal, start a shell, and follow issue, PR and spec links without leaving the editor (#1963). +- **Arrange Cockpit: architect | Work over Decisions.** `Codev: Arrange Cockpit`, or the layout button on the Cockpit's title bar, puts the `main` architect on the left with Work above Decisions on the right. It also runs by itself the first time the Cockpit is shown in a window, and once a notice offers to turn that off (`codev.cockpit.autoArrange`). It never closes an editor, unsaved or untitled ones included (#1963). + +### Fixes + +- **Work and Decisions render in the Codev IDE 1.138.** That IDE's webview host cannot deliver a webview's files, so a panel that loads its code by URL stays blank there (cluesmith/codev-ide#67). The Work and Decisions panels now carry their code inside the page, on every VS Code version, and load nothing from the extension; only that page's own script runs. The contextual panel and the Markdown preview stay blank in that IDE until it is fixed. +- **The Codev button's badge clears while Tower is disconnected.** It kept the last count of builders needing attention through a Tower outage; it now repaints whenever the connection changes, and shows nothing until Tower is back. +- **Spawn Builder runs in this window's workspace.** It ran `afx spawn` in the extension host's own directory (Tower's, in the Codev IDE), so it could spawn into another project, or fail where that directory is no project. It now runs in this window's workspace, the parent workspace in a builder-worktree window, and without a workspace it says so instead of prompting. + ## [3.3.8] - 2026-11-24 ### What's new diff --git a/apps/vscode/README.md b/apps/vscode/README.md index f249bfcede..5839df104f 100644 --- a/apps/vscode/README.md +++ b/apps/vscode/README.md @@ -40,6 +40,65 @@ The Codev sidebar contains seven collapsible views: - **Team** — per-member counts (`Assigned: N`, `Open PRs: N`, `Last 7d: X merged, Y closed`). Manual refresh from the title bar. - **Status** — connection state; click to reconnect if Tower drops. +## Codev Cockpit + +The **Codev Cockpit** button sits directly below Codev in the Activity Bar. It opens one tree holding the machine's whole fleet: + +``` +Tower +├─ my-project (current) ← this window's workspace +│ ├─ MAIN +│ │ └─ #42 builder … ← changed files below each builder +│ └─ WEB +└─ other-project + └─ MAIN + └─ #7 builder … +Dormant (2) +``` + +- **Workspaces** are the Tower view's rows, in the same urgency order and with the same labels, *current* marker and attention summary. Every active workspace expands to its architects; dormant workspaces fold into *Dormant (N)*. +- **This window's workspace acts here.** Its builder rows carry the Agents view's full right-click menu and the inline Approve Gate. A sibling architect carries *Remove Architect*; `main` never does. The workspace row carries inline *Spawn Builder*, *New Shell* and *Add Architect*. Its right-click menu adds *Open Web Interface*, *Start Dev* or *Stop Dev*, and *Open Dev URL…* when `worktree.devUrls` is set. +- **Other workspaces navigate.** Clicking another workspace's architect or builder opens that workspace's window. Their rows carry no actions that would act from this window. Their workspace rows keep the Tower view's inline *Open* and *Deactivate*. +- **In a builder-worktree window**, the parent workspace's row carries only *Open Web Interface*, the worktree's *Start Dev* / *Stop Dev* and *Open Dev URL…*. It has no spawn, shell or architect actions. +- **Title bar:** *Arrange Cockpit* (below), Refresh, plus the same accordion and tree-vs-list toggles as Agents. +- **Following the active file:** a builder diff in the editor reveals its file row in the Cockpit, expanding the workspace, architect and builder rows above it. +- **Agent cycling** (`ctrl+alt+n` / `ctrl+alt+p`) follows the Cockpit's order while the Cockpit is visible, Agents is not, and the Cockpit shows this window's agents. Otherwise it keeps the Agents order, as before (for example in a builder-worktree window). +- **Before the first load** the Tower row holds a state row: *Connecting to Tower…*, then *Not connected to Tower* (click to reconnect) if the attempt fails. Once loaded, the tree keeps its last content through a Tower drop and refreshes when Tower returns. + +The Cockpit reads what the Codev and Tower views already fetch. It adds no poll or stream of its own. + +## Work and Decisions + +The dashboard's **Work** and **Decisions** views open in the editor area, for this window's workspace: + +- **Codev: Open Work** shows builders, Needs Attention, Backlog and Recently Closed. A builder's *Open* shows its terminal, *+ Shell* opens a new Tower shell, and *Refresh* re-reads the overview from Tower. Issue and PR links open in your browser; *spec*, *plan* and *review* links open the file in an editor. +- **Codev: Open Decisions**, or the *Decisions* entry under this window's workspace in the Cockpit, lets you rule on pending decisions as in the dashboard. Item images load inside the panel; click one to see it full size. A workspace without a decisions file shows how to start one (`afx decisions init`). +- Each panel is one per window: opening it again brings it forward. It comes back after a window reload, and follows your color theme, including high contrast. A Decisions draft survives the panel being hidden or moved, but not a window reload. +- While Tower is not connected, each panel keeps what it last showed, under a notice, and recovers when Tower returns. +- Neither is offered in a builder-worktree window or a window with no Codev workspace. There, the commands say why. +- Left out from the dashboard: *Open Files & Shells* (VS Code's editor tabs and terminal list do this), the *Files* panel (the Explorer does) and the tip of the day. + +## Arrange Cockpit + +**Codev: Arrange Cockpit** (the Command Palette, or the layout button on the Cockpit's title bar) arranges the editor area around the workspace's `main` architect: + +``` ++------------------+------------------+ +| main architect | Work | +| (terminal) | | +| +------------------+ +| | Decisions | +| | | ++------------------+------------------+ +``` + +- Each of the three is the active tab in its group, and the architect has focus. +- **Nothing you have open is closed.** Your editors stay open, unsaved and untitled ones included, though some may move to another group: editors from groups beyond the three end up behind Decisions. An architect terminal, Work or Decisions panel that is already open is the same one, moved, never reopened, so a Decisions draft survives. +- **The architect is always `main`.** If `main` is not running you get the usual warning, no other architect is opened, and Work and Decisions are still arranged. The architect goes to the left editor group even when `codev.terminalPosition` is `panel`. Every other way of opening a terminal keeps honouring that setting. If another terminal has the architect's name (one you renamed, say), arranging stops before moving any editor and asks you to rename or close it: VS Code tells terminal tabs apart only by name. When it arranges by itself with Tower not connected, the architect is skipped without an error message. +- **It arranges by itself once per window.** The first time the Cockpit is shown in a window, including a window reopened with the Cockpit already showing, the editor area is arranged. Showing the Cockpit again leaves your layout alone, and a window reload starts over. The first time this happens for you, a notice says so and offers *Don't arrange automatically*, which turns `codev.cockpit.autoArrange` off. The command arranges at any time and is safe to repeat: an arranged window does not change. +- **Not in a builder-worktree window or a window with no Codev workspace.** There it never arranges by itself and the title-bar button is hidden. The command says why it does nothing. +- **Builder terminals and issue previews** that open in the second editor group land in the Work group while the split is in place. Where they should go instead is #1671's to settle. + ## Builder actions (right-click) Right-click any builder in the Agents view for three grouped action menus: @@ -178,6 +237,7 @@ All actions are also reachable via the Command Palette (`Cmd/Ctrl+Shift+P`): | Codev: Connect / Disconnect Tunnel | Cloud tunnel for remote access | | Codev: Cron Tasks | List, run, enable, or disable cron tasks | | Codev: Add Review Comment | Insert a `REVIEW(@architect):` comment at cursor | +| Codev: Arrange Cockpit | The `main` architect on the left, Work over Decisions on the right (see **Arrange Cockpit**) | Right-click actions on builders and workspace rows are listed in the **Builder actions (right-click)** section above. @@ -207,7 +267,8 @@ When a builder reaches a human-approval gate, a toast surfaces it with the issue | `codev.towerHost` | `localhost` | Tower server host | | `codev.towerPort` | `4100` | Tower server port | | `codev.workspacePath` | auto-detect | Override workspace path for Tower matching | -| `codev.terminalPosition` | `editor` | Terminal placement (`editor` or `panel`) | +| `codev.terminalPosition` | `editor` | Terminal placement (`editor` or `panel`). *Arrange Cockpit* puts the `main` architect in the left editor group either way | +| `codev.cockpit.autoArrange` | `true` | Arrange the editor area the first time the Codev Cockpit is shown in a window. When off, only *Codev: Arrange Cockpit* arranges it | | `codev.autoConnect` | `true` | Connect to Tower on activation | | `codev.autoStartTower` | `true` | Auto-start Tower if not running | | `codev.autoOpenBuilderTerminal` | `notify` | Behavior on builder-spawn events (`off` / `notify` / `auto`) | diff --git a/apps/vscode/esbuild.js b/apps/vscode/esbuild.js index 802e016172..2f0f6dcbf6 100644 --- a/apps/vscode/esbuild.js +++ b/apps/vscode/esbuild.js @@ -1,4 +1,5 @@ const esbuild = require("esbuild"); +const { decisionsWebviewConfig, workWebviewConfig } = require('./esbuild.webview.cjs'); const production = process.argv.includes('--production'); const watch = process.argv.includes('--watch'); @@ -83,8 +84,20 @@ const contextualPanelWebviewConfig = { plugins: [esbuildProblemMatcherPlugin], }; +/** The Decisions panel's webview bundle (Spec 1963): `dist/webview/decisions.{js,css}`. */ +const decisionsPanelWebviewConfig = { + ...decisionsWebviewConfig({ production }), + plugins: [esbuildProblemMatcherPlugin], +}; + +/** The Work panel's webview bundle (Spec 1963): `dist/webview/work.{js,css}`. */ +const workPanelWebviewConfig = { + ...workWebviewConfig({ production }), + plugins: [esbuildProblemMatcherPlugin], +}; + async function main() { - const configs = [extensionConfig, webviewConfig, contextualPanelWebviewConfig]; + const configs = [extensionConfig, webviewConfig, contextualPanelWebviewConfig, decisionsPanelWebviewConfig, workPanelWebviewConfig]; if (watch) { const contexts = await Promise.all(configs.map((c) => esbuild.context(c))); await Promise.all(contexts.map((c) => c.watch())); diff --git a/apps/vscode/esbuild.webview.cjs b/apps/vscode/esbuild.webview.cjs new file mode 100644 index 0000000000..58b273145c --- /dev/null +++ b/apps/vscode/esbuild.webview.cjs @@ -0,0 +1,47 @@ +/** + * The Work and Decisions panels' webview bundles (Spec 1963), as esbuild options. A module of its + * own so `esbuild.js` builds from it and the bundle tests (`decisions-webview-bundle.test.ts`, + * `work-webview-bundle.test.ts`) build the very same bundles, with no `dist` from an earlier build: + * CI runs the unit tests without one. + * + * - `jsx: 'automatic'` is explicit: these are the first TSX sources under `apps/vscode`, and + * esbuild would otherwise read the nearest `tsconfig.json`, which sets no `jsx`; + * - the imported stylesheets (the shared views', `vscode-theme.css` and, for Decisions, the + * markdown theme) are emitted next to the script as one `.css`; + * - `process.env.NODE_ENV` is defined so React's dev/prod branch resolves in the browser. + */ + +const path = require('node:path'); + +/** + * One panel's bundle: `src/workspace-views/webview/-main.tsx` → `dist/webview/.{js,css}`. + * @param {string} name @param {{ production: boolean }} options @returns {import('esbuild').BuildOptions} + */ +function workspaceViewWebviewConfig(name, { production }) { + return { + absWorkingDir: __dirname, + entryPoints: [`src/workspace-views/webview/${name}-main.tsx`], + bundle: true, + format: 'iife', + minify: production, + // Inline, as the panel inlines the bundle itself (panel-template.ts): a map file beside it + // could not be fetched by the webview. + sourcemap: production ? false : 'inline', + sourcesContent: false, + platform: 'browser', + outfile: `dist/webview/${name}.js`, + loader: { '.css': 'css' }, + jsx: 'automatic', + tsconfig: path.join(__dirname, 'tsconfig.webview.json'), + define: { 'process.env.NODE_ENV': production ? '"production"' : '"development"' }, + logLevel: 'silent', + }; +} + +/** The Decisions panel's bundle. @param {{ production: boolean }} options */ +const decisionsWebviewConfig = (options) => workspaceViewWebviewConfig('decisions', options); + +/** The Work panel's bundle. @param {{ production: boolean }} options */ +const workWebviewConfig = (options) => workspaceViewWebviewConfig('work', options); + +module.exports = { decisionsWebviewConfig, workWebviewConfig }; diff --git a/apps/vscode/eslint.config.mjs b/apps/vscode/eslint.config.mjs index 9449da001f..b4f6bbd5ce 100644 --- a/apps/vscode/eslint.config.mjs +++ b/apps/vscode/eslint.config.mjs @@ -1,7 +1,7 @@ import typescriptEslint from "typescript-eslint"; export default [{ - files: ["**/*.ts"], + files: ["**/*.ts", "**/*.tsx"], }, { plugins: { "@typescript-eslint": typescriptEslint.plugin, @@ -36,4 +36,25 @@ export default [{ message: "Use reg(...) or regCli(...) from extension.ts instead of bare vscode.commands.registerCommand — regCli adds the CLI-preflight guard (#791). If a registration legitimately can't use the helpers, add an eslint-disable-next-line with a one-line reason.", }], }, -}]; \ No newline at end of file +}, { + // Spec 1963: the Work and Decisions webviews never contact Tower, or anywhere else. Every read + // and action is a message to the extension host, which holds the Tower connection. The CSP has + // no connect-src; this keeps the source honest too (CI runs the same check as + // workspace-views-webview-source.test.ts). + files: ["src/workspace-views/webview/**/*.ts", "src/workspace-views/webview/**/*.tsx"], + ignores: ["src/workspace-views/webview/__tests__/**"], + rules: { + "no-restricted-globals": ["error", + { name: "fetch", message: "Webviews do no I/O: post a message to the extension host (Spec 1963)." }, + { name: "XMLHttpRequest", message: "Webviews do no I/O: post a message to the extension host (Spec 1963)." }, + { name: "WebSocket", message: "Webviews do no I/O: post a message to the extension host (Spec 1963)." }, + { name: "EventSource", message: "Webviews do no I/O: post a message to the extension host (Spec 1963)." }, + ], + "no-restricted-properties": ["error", + { object: "window", property: "fetch", message: "Webviews do no I/O (Spec 1963)." }, + { object: "globalThis", property: "fetch", message: "Webviews do no I/O (Spec 1963)." }, + { object: "navigator", property: "sendBeacon", message: "Webviews do no I/O (Spec 1963)." }, + { object: "window", property: "open", message: "A webview cannot open browser tabs: ask the host (Spec 1963)." }, + ], + }, +}]; diff --git a/apps/vscode/icons/codev-cockpit.svg b/apps/vscode/icons/codev-cockpit.svg new file mode 100644 index 0000000000..a61eb9a6a2 --- /dev/null +++ b/apps/vscode/icons/codev-cockpit.svg @@ -0,0 +1 @@ + diff --git a/apps/vscode/package.json b/apps/vscode/package.json index f503603c84..48f8796497 100644 --- a/apps/vscode/package.json +++ b/apps/vscode/package.json @@ -42,7 +42,9 @@ "activationEvents": [ "workspaceContains:.codev", "workspaceContains:codev", - "onStartupFinished" + "onStartupFinished", + "onWebviewPanel:codev.decisions", + "onWebviewPanel:codev.work" ], "main": "./dist/extension.js", "capabilities": { @@ -91,6 +93,30 @@ "title": "Codev: Refresh Tower", "icon": "$(refresh)" }, + { + "command": "codev.cockpit.refresh", + "title": "Codev: Refresh Cockpit", + "icon": "$(refresh)" + }, + { + "command": "codev.cockpit.arrange", + "title": "Codev: Arrange Cockpit", + "icon": "$(editor-layout)" + }, + { + "command": "codev.cockpit.openWebInterface", + "title": "Codev: Open Web Interface", + "icon": "$(globe)" + }, + { + "command": "codev.openDecisions", + "title": "Codev: Open Decisions", + "icon": "$(law)" + }, + { + "command": "codev.openWork", + "title": "Codev: Open Work" + }, { "command": "codev.helloWorld", "title": "Codev: Show Connection State" @@ -165,11 +191,13 @@ }, { "command": "codev.newShell", - "title": "Codev: New Shell" + "title": "Codev: New Shell", + "icon": "$(terminal-new)" }, { "command": "codev.spawnBuilder", - "title": "Codev: Spawn Builder" + "title": "Codev: Spawn Builder", + "icon": "$(rocket)" }, { "command": "codev.sendMessage", @@ -721,6 +749,10 @@ { "command": "codev.dev.switchTarget", "when": "codev.hasDevCommand" + }, + { + "command": "codev.cockpit.openWebInterface", + "when": "false" } ], "editor/context": [ @@ -860,6 +892,136 @@ "command": "codev.copyBacklogIssueNumber", "when": "view == codev.backlog && viewItem == backlog-item", "group": "1_primary@4" + }, + { + "command": "codev.approveGate", + "when": "view == codev.cockpit && viewItem =~ /^blocked-builder-/", + "group": "inline@1" + }, + { + "command": "codev.openBuilderById", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "1_primary@1" + }, + { + "command": "codev.approveGate", + "when": "view == codev.cockpit && viewItem =~ /^blocked-builder-/", + "group": "1_primary@2" + }, + { + "command": "codev.viewSpecFile", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir)(-review)?$/", + "group": "1_primary@3" + }, + { + "command": "codev.viewPlanFile", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-(spir|aspir|pir)(-review)?$/", + "group": "1_primary@4" + }, + { + "command": "codev.viewReviewFile", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-((spir|aspir|air)(-review)?|pir-review)$/", + "group": "1_primary@5" + }, + { + "command": "codev.viewDiff", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "2_worktree@0" + }, + { + "command": "codev.openWorktreeWindow", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "2_worktree@1" + }, + { + "command": "codev.openWorktreeFolder", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "2_worktree@2" + }, + { + "command": "codev.runWorktreeSetup", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/", + "group": "3_dev@1" + }, + { + "command": "codev.runWorktreeDev", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/ && codev.hasDevCommand", + "group": "3_dev@2" + }, + { + "command": "codev.stopWorktreeDev", + "when": "view == codev.cockpit && viewItem =~ /^(builder|blocked-builder|awaiting-builder)-/ && codev.hasDevCommand", + "group": "3_dev@3" + }, + { + "command": "codev.removeArchitect", + "when": "view == codev.cockpit && viewItem == cockpit-architect-sibling", + "group": "1_primary@1" + }, + { + "command": "codev.tower.openWorkspace", + "when": "view == codev.cockpit && viewItem =~ /^tower-workspace-(active|dormant)$/", + "group": "inline@1" + }, + { + "command": "codev.tower.deactivateWorkspace", + "when": "view == codev.cockpit && viewItem == tower-workspace-active", + "group": "inline@2" + }, + { + "command": "codev.spawnBuilder", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "inline@3" + }, + { + "command": "codev.newShell", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "inline@4" + }, + { + "command": "codev.addArchitect", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "inline@5" + }, + { + "command": "codev.spawnBuilder", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "1_workspace@1" + }, + { + "command": "codev.newShell", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "1_workspace@2" + }, + { + "command": "codev.addArchitect", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-current(-.*)?$/", + "group": "1_workspace@3" + }, + { + "command": "codev.cockpit.openWebInterface", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)(-.*)?$/", + "group": "2_web@1" + }, + { + "command": "codev.runWorkspaceDev", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)-dev-start(-devurls)?$/", + "group": "3_dev@1" + }, + { + "command": "codev.stopWorkspaceDev", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)-dev-stop(-devurls)?$/", + "group": "3_dev@1" + }, + { + "command": "codev.stopWorktreeDev", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)-dev-stop-other(-devurls)?$/", + "group": "3_dev@1" + }, + { + "command": "codev.openDevUrl", + "when": "view == codev.cockpit && viewItem =~ /^cockpit-workspace-(current|parent)(-.*)?-devurls$/", + "group": "3_dev@2" } ], "view/title": [ @@ -868,6 +1030,36 @@ "when": "view == codev.tower", "group": "navigation@1" }, + { + "command": "codev.cockpit.arrange", + "when": "view == codev.cockpit && !codev.isBuilderWorktree && codev.hasWorkspace", + "group": "navigation@0" + }, + { + "command": "codev.cockpit.refresh", + "when": "view == codev.cockpit", + "group": "navigation@1" + }, + { + "command": "codev.disableBuildersAutoCollapse", + "when": "view == codev.cockpit && codev.buildersAutoCollapse", + "group": "navigation@2" + }, + { + "command": "codev.enableBuildersAutoCollapse", + "when": "view == codev.cockpit && !codev.buildersAutoCollapse", + "group": "navigation@2" + }, + { + "command": "codev.disableBuildersFileTreeMode", + "when": "view == codev.cockpit && codev.buildersFileViewAsTree", + "group": "navigation@3" + }, + { + "command": "codev.enableBuildersFileTreeMode", + "when": "view == codev.cockpit && !codev.buildersFileViewAsTree", + "group": "navigation@3" + }, { "command": "codev.refreshOverview", "when": "view == codev.agents", @@ -1131,6 +1323,11 @@ "id": "codev", "title": "Codev", "icon": "icons/codev.svg" + }, + { + "id": "codev-cockpit", + "title": "Codev Cockpit", + "icon": "icons/codev-cockpit.svg" } ], "secondarySidebar": [ @@ -1163,6 +1360,9 @@ ], "codev-tower": [ { "id": "codev.tower", "name": "Codev Tower" } + ], + "codev-cockpit": [ + { "id": "codev.cockpit", "name": "Codev Cockpit" } ] }, "viewsWelcome": [ @@ -1207,7 +1407,12 @@ "type": "string", "enum": ["editor", "panel"], "default": "editor", - "description": "Where to open Codev terminals (editor area or bottom panel)" + "description": "Where to open Codev terminals (editor area or bottom panel). Codev: Arrange Cockpit puts the main architect in the left editor group either way." + }, + "codev.cockpit.autoArrange": { + "type": "boolean", + "default": true, + "description": "Arrange the editor area for the Codev Cockpit (the main architect on the left, Work over Decisions on the right) the first time the Cockpit is shown in a window. When off, only Codev: Arrange Cockpit arranges it." }, "codev.terminalLinks.issueTarget": { "type": "string", @@ -1430,6 +1635,7 @@ "@cluesmith/codev-artifact-canvas": "workspace:*", "@cluesmith/codev-sdk": "workspace:*", "@cluesmith/codev-types": "workspace:*", + "@cluesmith/codev-workspace-views": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0", "ws": "^8.18.0" @@ -1441,6 +1647,8 @@ "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@types/ws": "^8.18.1", + "@testing-library/react": "^16.0.0", + "jsdom": "^26.0.0", "typescript-eslint": "^8.48.1", "eslint": "^9.39.1", "esbuild": "^0.27.1", diff --git a/apps/vscode/scripts/cockpit-harness/README.md b/apps/vscode/scripts/cockpit-harness/README.md new file mode 100644 index 0000000000..664bf5f57b --- /dev/null +++ b/apps/vscode/scripts/cockpit-harness/README.md @@ -0,0 +1,200 @@ +# Cockpit verification harness + +Dev-only. Excluded from the vsix (`.vscodeignore`) and not run in CI. + +This harness gives Spec 1963's rendered checkpoints an isolated Tower and an isolated VS Code +(`code serve-web`, or the IDE server binary) running the branch's vsix. Neither can reach the +owner's Tower (`:4100`), `~/.agent-farm`, `~/.codev/run` or IDE (`/ide/`). The plan's *Verification harness* section is the +design; this file covers how to run it. + +## Running it + +```sh +export COCKPIT_SCRATCH= # must be under a temp root +export COCKPIT_TOWER_PORT=18764 COCKPIT_WEB_PORT=18765 +H=apps/vscode/scripts/cockpit-harness/harness.mjs + +node $H selftest # prove every pre-flight refusal, the tripwire and the sandbox +node $H selftest tripwire settings sandbox # only these sections (no Tower, no VS Code) +node $H build-vsix # vsce package → $COCKPIT_SCRATCH/cockpit-harness/codev-vscode.vsix +node $H start # pre-flight, Tower, `empty` fixture, VS Code, tripwire +node $H seed one-builder # seed a scenario; gate 6 asserts its overview +node $H check # gates 3-5 again, plus the extension running against the Tower +node $H verify render # a scripted rendered check (cockpit-verify.mjs); see below +node $H tower-down # stop only the isolated Tower (by PID); tower-up starts it again +node $H vscode-restart # restart only the isolated VS Code (by PID) +COCKPIT_PRE_COCKPIT=1 node $H vscode-restart # the same, the install without the Cockpit container +node $H stop # kill the harness's own PIDs; remove runtime dirs +``` + +`selftest` needs both ports set and free, even though it serves no web. Its refusal cases run real +`start` processes, and each must refuse for the gate under test, not for a missing port. Its +sections, run when named or all by default: +- `gates`: gates 1 and 2; +- `tower`: gates 3 and 4 against a real isolated Tower; +- `fixtures`: `stop`'s refusals; +- `tripwire`, `settings`, `sandbox`: throwaway listeners and stand-in processes only. `settings` + also reads, without launching them, the bundles of any server binaries named in + `COCKPIT_SELFTEST_SERVER_BINS` (colon-separated). + +`build-vsix` records a digest of every tracked or untracked file the vsix is built from. `check` +treats the installed vsix as the branch's only while that digest still matches, so an +uncommitted edit that was built in passes, and any edit since the build fails until you run +`build-vsix` again. The loop while iterating is: edit, `build-vsix`, `stop`, `start`, `check`. + +If `code serve-web` cannot run, start with the IDE server binary instead: + +```sh +COCKPIT_VSCODE=ide-server COCKPIT_IDE_SERVER_BIN= node $H start +``` + +**ide-server mode needs the owner's go-ahead** (the 2026-11-24 incident). Its first run wrote the +machine settings under `--user-data-dir`, which this kind of server ignores. Its extension host +then used the default port and sent about 9,100 requests to the owner's Tower over 25 minutes; +every one was refused with a 401. The mode now: +- writes the settings where the server's own code says it reads them, and refuses a server whose + bundle does not show where that is (gate 5); +- runs the server inside a network sandbox (`sandbox.mjs`) that denies outbound TCP to `:4100`, + and proves the sandbox applies at each launch with a canary port. + +Prerequisites: +- `packages/codev` is built, because the Tower and the fixture driver load its `dist`; +- `pnpm install` has run, because the browser driver resolves `playwright` from `packages/codev`. + +Never run `playwright install`. The driver uses the Chromium already in +`~/Library/Caches/ms-playwright`, or in `PLAYWRIGHT_BROWSERS_PATH` when that is set. + +## What runs, and how it is kept away from the owner's + +| Piece | How it is isolated | +|---|---| +| Tower | Started as `node --require request-log.cjs packages/codev/dist/agent-farm/servers/tower-server.js -p $COCKPIT_TOWER_PORT`, never through `afx tower start`.
Its environment is built from an allowlist: `CODEV_AGENT_FARM_DIR`, `HOME` and `TMPDIR` are in the scratchpad, and `NODE_ENV`, `AF_TEST_DB` and `CODEV_TOWER_KEY` are unset.
`request-log.cjs` appends each HTTP request and WebSocket upgrade it receives to `/logs/tower-requests.jsonl` (for the request-count check). | +| Shellper sockets | They live in `/run`, reached through a short `/tmp/cckp-` symlink.
macOS caps a socket path at 104 bytes, and the scratchpad path alone is longer. Gate 2 checks the link's real path, and every teardown removes the link. | +| Fixture driver (`fixtures.mjs`) | Runs in the isolated environment. Creates state only through:
  • explicit-port HTTP calls (activation, builder terminals);
  • the dist's in-process writers (porch `writeState`, `upsertBuilder`);
  • git.
It runs no Tower-contacting `afx` or `porch` command. | +| Fixture workspaces | Git repos in a fresh `cockpit-fixtures-*` dir (`mkdtemp`) under the real per-user temp dir (`/private/var/folders/…/T`), **not** the scratchpad. Tower's `/api/workspaces` drops every workspace under `/tmp`, `/private/tmp` or its own `os.tmpdir()` (`isTempDirectory`), and the scratchpad is under `/private/tmp`, so fixtures there never reach the fleet the Tower and Cockpit views list. The Tower's own `TMPDIR` points into the scratchpad, so this dir is not its temp dir. `start` writes a marker holding a per-run token in it; see *Teardown*. | +| Fixture sessions | Architects and builders are `/bin/bash --noprofile --norc`, through a no-op custom harness in each fixture's `.codev/config.json`. They are never agents. | +| VS Code | Runs on `$COCKPIT_WEB_PORT` in one of two modes, set by `COCKPIT_VSCODE`:
  • `serve-web` (default): `code serve-web`, with the CLI, server, user and extensions dirs all under the root.
  • `ide-server`: the plan's alternative for when serve-web cannot run. It launches the VS Code Server binary Tower's IDE support uses (`COCKPIT_IDE_SERVER_BIN`) **directly**, never through any Tower's `/api/ide`. It passes the flags `ide-server.ts` passes (`--host 127.0.0.1`, `--port`, `--server-base-path /ide`, `--connection-token-file`, `--extensions-dir`), plus `--server-data-dir`, all in the scratchpad. It passes no `--user-data-dir`, because the server replaces it with `/data`. The server runs under `sandbox-exec` with a profile that denies outbound TCP to `:4100` and to a canary port, on any host. Before the server starts, a wrapper inside the sandbox connects to the canary port, and the server starts only if that connect is refused.
The mode is chosen explicitly. A serve-web failure fails the start; it does not switch modes by itself.
  • Machine settings: `codev.towerPort=$COCKPIT_TOWER_PORT`, `codev.autoStartTower=false`, `files.autoSave=off`. serve-web: in `/Machine/settings.json`. ide-server: in `/data/Machine/settings.json`. That is where the server's bundle (`out/server-main.js`) reads them, and gate 5 confirms it from the code before every start.
  • Environment: `CODEV_TOWER_KEY` is the isolated key, `HOME` is the scratch home, and `stubs/` comes first on `PATH`.
| +| Stubs (`stubs/afx`, `porch`, `codev`) | Each call appends `{ tool, argv, cwd, caller }` to `/logs/stub-calls.jsonl` and exits 0, so CLI-shelling actions are verified by their recorded argv.
`codev --version` prints the branch version.
The stubs are on the Tower's `PATH` too. | +| Browser (`workbench.mjs`) | Headless Chromium with a persistent profile under the root, so the folder-trust decision holds. Any request to `:4100` fails the check. | +| Tripwire (`tripwire.mjs`) | Samples `lsof` for ESTABLISHED connections on `:4100` every second. The machine-wide socket-holder scan runs on every 5th sample only. A connection counts if it belongs to the harness tree:
  • the PIDs in `/pids/`, each only while its command still carries the markers its pid file records;
  • holders of sockets in the run dir;
  • descendants of either.
On one, it **stops the run at once**:
  1. writes `tripwire.tripped`, so every harness command refuses from then on;
  2. freezes the whole tree with SIGSTOP, rescanning until no new process appears;
  3. SIGKILLs the tree, which includes the CLI that ran `start` or `verify`;
  4. adds what it killed, and any survivor, to the marker;
  5. exits 3.
Read the marker, or the `NOTE` that `stop` prints. It never connects to `:4100`. | + +The tripwire **detects and stops**; it does not prevent. It samples every second, so a connect, +request and close to `:4100` that completes between two samples would escape it. (The extension's Tower +connection is a long-lived event stream, so a misdirected one would not.) Isolation is enforced by +the layers above: +- no Tower-contacting CLI; +- recording stubs on `PATH`; +- `codev.autoStartTower=false` and the pinned `codev.towerPort`; +- the isolated `CODEV_TOWER_KEY`, so a stray request to the owner's Tower would get a 401; +- in ide-server mode, the network sandbox, which refuses the connect itself. + +## Pre-flight gates + +These match the plan's numbering. Any refusal exits with code 2. + +1. Each port is set, numeric and not 4100, and has no listener before the start. +2. `COCKPIT_SCRATCH` is under a temp root. The agent-farm dir and socket dir resolve under it, never + into `~/.agent-farm` or `~/.codev`. A shellper socket path also fits the Unix-socket limit. + - Gates 1 and 2 run before anything is created. +3. The fixture driver's `AGENT_FARM_DIR` is the isolated dir, and its `getGlobalDbPath()` is the + one `.db` file the isolated Tower has open (`lsof`). + - The driver re-checks this before every seed, and refuses before writing. +4. The only listener on the Tower port is the PID the harness spawned. `/api/version` answers the + isolated key, and a wrong key gets 401. +5. The VS Code Machine settings pin the port and turn auto-start off, and `afx`, `porch` and + `codev` resolve to the stubs in the VS Code server's environment. +6. After a seed, each fixture workspace's `/api/overview` lists exactly the expected builders (with + `spawnedByArchitect`) and architects, and `/api/workspaces` lists each activated workspace as + active or dormant as seeded. There is no fallback to faked data. + +## Teardown + +`stop` kills, by PID only: +- the recorded roots, each re-verified by its command line; +- the shellpers holding sockets in the run dir; +- previously recorded descendants whose command line is unchanged; +- all live descendants of those. + +It then checks that none of them is still alive. It also removes: +- the socket symlink; +- the runtime dirs (`af`, `run`, `home`, `tmp`, `pids`, the VS Code server, user and + extensions dirs, and the browser profile); +- the fixtures dir, which is outside the scratchpad, **only if every check holds**: + - it is a real directory, not a symlink, and its realpath is the recorded path; + - the realpath's parent is the per-user temp dir; + - its basename is `cockpit-fixtures-*`; + - it holds the `.cockpit-harness-fixtures` marker `start` wrote, with this run's token. + + Otherwise `stop` deletes nothing there, prints `REFUSED … deleted nothing: `, keeps the + state record and exits 1. `selftest` proves each refusal; +- the state record. + +It keeps `logs/`, `shots/`, the vsix and the downloaded VS Code server cache (`cache/`). A failed +`start` runs the same teardown. + +If the tripwire fires, or a pre-flight gate refuses in a real run, stop and tell the architect +before retrying. + +## Scenarios + +`fixtures.mjs` defines them in `SCENARIOS`: +- `empty`: workspace `alpha`, not activated. `start` seeds it. +- `one-builder`: `alpha` activated, plus builder `spir-101` spawned by `main`. +- `fleet` (Phase 5): four workspaces. + - `alpha` is activated with a sibling architect `web` and a dev config (`devCommand` and two + `devUrls`). It has three builders: `#101` (spawned by `main`, blocked on spec approval, with a + committed spec and a changed file), `#102` (`main`) and `#103` (`web`). + - `alpha` also has (Phase 6): + - a decisions file (`codev/state/pending-decisions.md`): `main-1` open with an SVG image and an + http(s) link, `web-1` with a ruling already written, and one `## Ruled` line; + - a forge: its `.codev/config.json` points the `pr-list`, `issue-list`, `recently-closed` and + `recently-merged` concepts at `cat` of fixed JSON under `.codev/forge/`, committed with the + spec, plan and review those items name. Work's Needs Attention gets PR `#301`, Backlog gets + `#401` (spec and plan) and `#402` (a bug), and Recently Closed gets `#399` (review, merged PR + `#398`). The other workspaces have no forge, so their `gh` concepts fail, as on a machine + without `gh`. + - `beta` has one builder, `#201`. + - `gamma` has none. + - `delta` is activated and then deactivated, so it is dormant. + +Seed each scenario once per `start`. Re-seeding is not supported, for two reasons: +- `seedBuilder` refuses an existing worktree. +- The extension activates `alpha` on the isolated Tower by itself when the workbench first + loads, so `empty`'s "no architects" expectation stops holding after the first `check`. + +To get a different scenario, `stop` and `start` again. + +## Scripted Cockpit checks (`verify`) + +`node $H verify `); + expect(html).toContain(``); + expect(html).not.toMatch(/\bsrc=|\bhref=|webview\.vscode-cdn\.net/); + expect(html).toContain("default-src 'none'"); + expect(manager.panel).toBe(panels[0]); + }); + + it('reads the bundle once: a later panel in the window reuses it', () => { + const { manager } = setup(); + manager.show(); + panels[0].dispose(); + writeFileSync(join(EXTENSION_DIR, 'dist', 'webview', 'decisions.js'), 'window.changed = true;'); + try { + manager.show(); + expect(panels).toHaveLength(2); + expect(panels[1].webview.html).toContain(BUNDLE_SCRIPT); + } finally { + writeFileSync(join(EXTENSION_DIR, 'dist', 'webview', 'decisions.js'), BUNDLE_SCRIPT); + } + }); + + it('a bundle that cannot be read fails the open loudly, naming the file, and leaves no panel', () => { + const empty = mkdtempSync(join(tmpdir(), 'codev-decisions-nobundle-')); + try { + const { manager, log } = setup({ extensionDir: empty }); + expect(() => manager.show()).toThrow(`the Decisions panel cannot open: its bundle ${empty}/dist/webview/decisions.js could not be read`); + expect(createWebviewPanel).not.toHaveBeenCalled(); + expect(manager.panel).toBeUndefined(); + expect(log).toHaveBeenCalledWith(expect.stringContaining(`${empty}/dist/webview/decisions.js`)); + } finally { + rmSync(empty, { recursive: true, force: true }); + } + }); + + it('reveals the open panel instead of creating a second one, and never reloads it', () => { + const { manager } = setup(); + manager.show(); + const html = panels[0].webview.html; + manager.show(); + manager.show(); + expect(createWebviewPanel).toHaveBeenCalledTimes(1); + expect(panels[0].reveal).toHaveBeenCalledTimes(2); + expect(panels[0].reveal).toHaveBeenCalledWith(); + expect(panels[0].webview.html).toBe(html); + }); + + it('opens a new panel once the open one is closed', () => { + const { manager } = setup(); + manager.show(); + panels[0].dispose(); + expect(manager.panel).toBeUndefined(); + manager.show(); + expect(createWebviewPanel).toHaveBeenCalledTimes(2); + expect(manager.panel).toBe(panels[1]); + }); + + it('says why, and opens nothing, where Decisions is not offered', () => { + const { manager } = setup({ reason: 'Codev: Decisions is not offered in a builder-worktree window.' }); + manager.show(); + expect(createWebviewPanel).not.toHaveBeenCalled(); + expect(showInformationMessage).toHaveBeenCalledWith('Codev: Decisions is not offered in a builder-worktree window.'); + }); +}); + +describe('visibility: the poll runs only while the panel is on screen', () => { + it('answers ready with the visibility, and relays every change', async () => { + const { manager } = setup(); + manager.show(); + const panel = panels[0]; + await panel.send({ type: 'ready' }); + panel.setVisible(false); + panel.setVisible(true); + expect(panel.posted).toEqual([ + { type: 'visibility', visible: true }, + { type: 'visibility', visible: false }, + { type: 'visibility', visible: true }, + ]); + }); + + it('runs no timer of its own: nothing is read unless the webview asks', async () => { + vi.useFakeTimers(); + try { + const { manager, bridge } = setup(); + manager.show(); + await vi.advanceTimersByTimeAsync(60_000); + expect(bridge.read).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); +}); + +describe('requests from the webview', () => { + it('answers a read, a ruling and an image once each, echoing the request id', async () => { + const { manager, bridge } = setup(); + manager.show(); + const panel = panels[0]; + await panel.send({ type: 'decisions/read', requestId: 4 }); + await panel.send({ type: 'decisions/rule', requestId: 5, request: { id: 'D-1', fingerprint: 'f', word: 'ship', extra: 'dropped' } }); + await panel.send({ type: 'decisions/image', requestId: 6, path: 'shots/a.png' }); + expect(bridge.read).toHaveBeenCalledTimes(1); + expect(bridge.rule).toHaveBeenCalledWith({ id: 'D-1', fingerprint: 'f', word: 'ship' }); + expect(bridge.image).toHaveBeenCalledWith('shots/a.png'); + expect(panel.posted).toEqual([ + { type: 'decisions/read-result', requestId: 4, result: { kind: 'document', document: DOC } }, + { type: 'decisions/rule-result', requestId: 5, result: { kind: 'document', document: DOC } }, + { type: 'decisions/image-result', requestId: 6, result: { kind: 'image', bytes: new Uint8Array([1, 2, 3]), contentType: 'image/png' } }, + ]); + }); + + it('ignores a malformed message, saying so in the log', async () => { + const { manager, bridge, log } = setup(); + manager.show(); + for (const bad of [null, 'read', { type: 'decisions/read' }, { type: 'decisions/rule', requestId: 1, request: { id: '' } }, + { type: 'decisions/image', requestId: 1, path: '' }, { type: 'decisions/delete', requestId: 1 }]) { + await panels[0].send(bad); + } + expect(bridge.read).not.toHaveBeenCalled(); + expect(bridge.rule).not.toHaveBeenCalled(); + expect(bridge.image).not.toHaveBeenCalled(); + expect(panels[0].posted).toEqual([]); + expect(log).toHaveBeenCalledTimes(6); + }); + + it('opens http(s) links in the browser and refuses every other scheme', async () => { + const { manager, log } = setup(); + manager.show(); + await panels[0].send({ type: 'open-external', url: 'https://github.com/cluesmith/codev/pull/1971' }); + await panels[0].send({ type: 'open-external', url: 'http://localhost:3000/' }); + for (const url of ['javascript:alert(1)', 'file:///etc/passwd', 'vscode://cluesmith.codev-vscode/x', 'command:workbench.action.reloadWindow']) { + await panels[0].send({ type: 'open-external', url }); + } + expect(openExternal.mock.calls.map(([uri]) => String(uri))).toEqual([ + 'https://github.com/cluesmith/codev/pull/1971', 'http://localhost:3000/', + ]); + expect(log).toHaveBeenCalledTimes(4); + }); + + it('drops a reply that lands after the panel closed: no post, no error, no new panel', async () => { + let release!: (value: { kind: 'document'; document: DecisionsDocument }) => void; + const bridge = fakeBridge(); + bridge.read.mockImplementation(() => new Promise(resolve => { release = resolve; })); + const { manager } = setup({ bridge }); + manager.show(); + const panel = panels[0]; + await panel.send({ type: 'decisions/read', requestId: 1 }); + panel.dispose(); + release({ kind: 'document', document: DOC }); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(panel.webview.postMessage).not.toHaveBeenCalled(); + expect(createWebviewPanel).toHaveBeenCalledTimes(1); + expect(showInformationMessage).not.toHaveBeenCalled(); + // Its listeners are gone with it. + expect(panel.received.count).toBe(0); + expect(panel.viewState.count).toBe(0); + }); +}); + +describe('restore after a window reload', () => { + it('adopts the restored panel: it renders the view and answers its webview', async () => { + const { manager, bridge } = setup(); + const restored = new FakePanel(); + await manager.deserializeWebviewPanel(restored as never); + expect(restored.webview.options).toEqual({ enableScripts: true, localResourceRoots: [] }); + expect(restored.webview.html).toContain(BUNDLE_SCRIPT); + await restored.send({ type: 'decisions/read', requestId: 0 }); + expect(bridge.read).toHaveBeenCalledTimes(1); + manager.show(); + expect(createWebviewPanel).not.toHaveBeenCalled(); + expect(restored.reveal).toHaveBeenCalledTimes(1); + }); + + it('closes a second restored panel, and one restored where Decisions is not offered', async () => { + const { manager, reason } = setup(); + const first = new FakePanel(); + const second = new FakePanel(); + await manager.deserializeWebviewPanel(first as never); + await manager.deserializeWebviewPanel(second as never); + expect(first.disposed).toBe(false); + expect(second.disposed).toBe(true); + + first.dispose(); + reason.value = 'Codev: Decisions needs a Codev workspace, and this window has none.'; + const third = new FakePanel(); + await manager.deserializeWebviewPanel(third as never); + expect(third.disposed).toBe(true); + }); + + it('closes a restored panel whose bundle cannot be read, and fails naming the file', async () => { + const empty = mkdtempSync(join(tmpdir(), 'codev-decisions-nobundle-')); + try { + const { manager } = setup({ extensionDir: empty }); + const restored = new FakePanel(); + await expect(manager.deserializeWebviewPanel(restored as never)).rejects.toThrow(`${empty}/dist/webview/decisions.js could not be read`); + expect(restored.disposed).toBe(true); + expect(restored.webview.html).toBe(''); + expect(manager.panel).toBeUndefined(); + } finally { + rmSync(empty, { recursive: true, force: true }); + } + }); +}); + +describe('the Tower key, URL and port never reach the webview (scenario 22, state)', () => { + const KEY = 'tower-key-1963-do-not-leak'; + const PORT = 18764; + + it('across a read, a refusal, a ruling, an image and the document itself', async () => { + const requests: Array<{ url: string; headers: Record }> = []; + const answers = [ + { status: 200, json: { ok: true, document: DOC } }, + { status: 409, json: { ok: false, code: 'item-changed', message: 'D-1 changed; nothing was written.' } }, + { status: 200, bytes: new Uint8Array([0x89, 0x50]), type: 'image/png' }, + { status: 404, json: { ok: false, code: 'not-found', message: 'There is no image at b.png.' } }, + ]; + const fetchFn = vi.fn(async (url: string, init: RequestInit) => { + requests.push({ url, headers: init.headers as Record }); + const answer = answers.shift()!; + const text = 'json' in answer ? JSON.stringify(answer.json) : ''; + const bytes = 'bytes' in answer ? answer.bytes! : new TextEncoder().encode(text); + return { + ok: answer.status < 300, + status: answer.status, + headers: new Headers('type' in answer ? { 'Content-Type': answer.type! } : { 'Content-Type': 'application/json' }), + text: async () => text, + arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), + } as unknown as Response; + }); + const client = new TowerClient({ port: PORT, getAuthKey: () => KEY, fetchFn: fetchFn as never }); + const bridge = new DecisionsBridge({ getState: () => 'connected', getClient: () => client, getWorkspacePath: () => '/work/codev' }); + const manager = new DecisionsPanels({ extensionUri: EXTENSION as never, bridge, unavailableReason: () => null, log: vi.fn() }); + manager.show(); + const panel = panels[0]; + + await panel.send({ type: 'ready' }); + await panel.send({ type: 'decisions/read', requestId: 0 }); + await panel.send({ type: 'decisions/rule', requestId: 1, request: { id: 'D-1', fingerprint: 'f', word: 'ship' } }); + await panel.send({ type: 'decisions/image', requestId: 2, path: 'a.png' }); + await panel.send({ type: 'decisions/image', requestId: 3, path: 'b.png' }); + + // The host did make keyed requests to Tower's port... + expect(requests).toHaveLength(4); + for (const request of requests) { + expect(request.url.startsWith(`http://localhost:${PORT}/workspace/`)).toBe(true); + expect(request.headers['codev-tower-key']).toBe(KEY); + } + // ...and none of it reached the webview, in any message or in the document. + expect(panel.posted.map(m => (m as { type: string }).type)).toEqual([ + 'visibility', 'decisions/read-result', 'decisions/rule-result', 'decisions/image-result', 'decisions/image-result', + ]); + const everything = JSON.stringify(panel.posted, (_k, v) => (v instanceof Uint8Array ? [...v] : v)) + panel.webview.html; + for (const secret of [KEY, 'codev-tower-key', `localhost:${PORT}`, String(PORT), '/workspace/']) { + expect(everything, secret).not.toContain(secret); + } + }); +}); diff --git a/apps/vscode/src/__tests__/decisions-webview-bundle.test.ts b/apps/vscode/src/__tests__/decisions-webview-bundle.test.ts new file mode 100644 index 0000000000..6a2e9e3a14 --- /dev/null +++ b/apps/vscode/src/__tests__/decisions-webview-bundle.test.ts @@ -0,0 +1,160 @@ +/** + * Spec 1963: the Decisions panel's webview bundle, built the way `esbuild.js` builds it (from the + * same options in `esbuild.webview.cjs`) and booted in a jsdom window of its own with a fake + * `acquireVsCodeApi`. (The test runs in node: esbuild refuses to run inside vitest's jsdom + * environment, and a window of its own keeps the bundle's globals out of the test's.) + * Unit tests import the sources; this is what proves the shipped bundle starts: it mounts, says + * it is ready, reads only once the extension host says the panel is visible, and renders the reply. + * It also holds the bundle to one copy of React and to emitting its stylesheet. + * + * Every check runs on both builds, development and production (minified, what the vsix ships), each + * booted in the escaped form the panel inlines (`panel-template.ts`). + * + * Built into a temporary directory, never `dist`: CI runs the unit tests without a build. + */ + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { build, type Metafile } from 'esbuild'; +import { inlineScriptText, inlineStyleText } from '../workspace-views/panel-template.js'; +import { escapeContexts, SAFE_CONTEXTS } from './escape-contexts.js'; +import type { DecisionsDocument } from '@cluesmith/codev-types'; + +const require = createRequire(import.meta.url); +const { decisionsWebviewConfig } = require('../../esbuild.webview.cjs') as { + decisionsWebviewConfig: (options: { production: boolean }) => Parameters[0]; +}; + +/** The part of a jsdom window this test uses (the package ships no types of its own). */ +interface BundleWindow { + eval(code: string): unknown; + dispatchEvent(event: unknown): boolean; + MessageEvent: new (type: string, init: { data: unknown }) => unknown; + document: { querySelector(selector: string): { textContent: string | null } | null; visibilityState: string }; + acquireVsCodeApi?: () => { postMessage(message: unknown): void }; + close(): void; +} +const { JSDOM } = require('jsdom') as { + JSDOM: new (html: string, options: { runScripts: 'outside-only'; pretendToBeVisual: boolean }) => { window: BundleWindow }; +}; + +const DOC: DecisionsDocument = { + path: 'codev/state/pending-decisions.md', + version: 'v1', + items: [{ + id: 'main-12', + stamp: null, + question: 'Merge the onboarding scan fix?', + bodyMarkdown: 'It fixes the scan.', + options: [{ word: 'accept', description: 'merge as is', recommended: true }], + currentRuling: '', + qa: [], + fingerprint: 'fp-main-12', + problems: [], + writable: true, + }], + ruledMarkdown: '', + problems: [], +}; + +/** Both builds: the development one, and the production (minified) one that ships in the vsix. */ +const BUILDS = [ + { label: 'development', production: false }, + { label: 'production, as shipped', production: true }, +]; + +describe.each(BUILDS)('built for $label', ({ production }) => { + let outDir: string; + let metafile: Metafile; + let script: string; + let win: BundleWindow; + const posted: unknown[] = []; + + const fromHost = (data: unknown) => win.dispatchEvent(new win.MessageEvent('message', { data })); + + beforeAll(async () => { + outDir = mkdtempSync(join(tmpdir(), 'codev-decisions-bundle-')); + const result = await build({ + ...decisionsWebviewConfig({ production }), + outfile: join(outDir, 'decisions.js'), + sourcemap: false, + metafile: true, + }); + metafile = result.metafile!; + script = readFileSync(join(outDir, 'decisions.js'), 'utf8'); + + win = new JSDOM('
', { runScripts: 'outside-only', pretendToBeVisual: true }).window; + // Copied out of the window's realm, as postMessage's structured clone would. + win.acquireVsCodeApi = () => ({ postMessage: (message: unknown) => posted.push(JSON.parse(JSON.stringify(message))) }); + // Booted as the panel inlines it (panel-template.ts): the escaped text is what runs. + win.eval(inlineScriptText(script)); + }, 60_000); + + afterAll(() => { + if (win) { + fromHost({ type: 'visibility', visible: false }); + win.close(); + } + if (outDir) { rmSync(outDir, { recursive: true, force: true }); } + }); + + describe('the Decisions webview bundle', () => { + it('mounts and tells the extension host it is ready, reading nothing yet', () => { + expect(posted).toEqual([{ type: 'ready' }]); + }); + + it('reads once the extension host says the panel is visible, and renders the reply', async () => { + fromHost({ type: 'visibility', visible: true }); + await vi.waitFor(() => expect(posted).toContainEqual({ type: 'decisions/read', requestId: 0 })); + fromHost({ type: 'decisions/read-result', requestId: 0, result: { kind: 'document', document: DOC } }); + expect(win.document.visibilityState).toBe('visible'); + await vi.waitFor(() => { + const card = win.document.querySelector('article.decisions-card'); + expect(card?.textContent).toContain('Merge the onboarding scan fix?'); + expect(card?.textContent).toContain('It fixes the scan.'); + }); + }); + + it('bundles one copy of React and of React DOM', () => { + const copies = (name: string) => new Set(Object.keys(metafile.inputs) + .map(input => input.replace(/\\/g, '/').match(new RegExp(`^(.*(?:^|/)node_modules/${name}/)`))?.[1]) + .filter((root): root is string => root !== undefined)); + expect(copies('react').size).toBe(1); + expect(copies('react-dom').size).toBe(1); + }); + + it("emits one stylesheet holding the shared views' styles and the VS Code theme mapping", () => { + const outputs = Object.keys(metafile.outputs).map(output => output.replace(/\\/g, '/')); + expect(outputs.filter(output => output.endsWith('.css'))).toHaveLength(1); + const css = readFileSync(join(outDir, 'decisions.css'), 'utf8'); + expect(css).toContain('.decisions-card'); + expect(css).toContain('--codev-wv-accent: var(--vscode-'); + expect(css).toContain('.wv-fullsize'); + }); + + it('loads nothing by URL, so it renders where a webview cannot fetch (cluesmith/codev-ide#67)', () => { + const css = readFileSync(join(outDir, 'decisions.css'), 'utf8'); + expect(css).not.toMatch(/url\(|@import|@font-face/i); + // No import of any kind is left in the output (a dynamic one would be fetched); React's dev + // warnings quote `import('./MyComponent')` as text, so the metafile is the check, not the text. + expect(Object.values(metafile.outputs).flatMap(output => output.imports)).toEqual([]); + expect(script).not.toMatch(/\bWorker\s*\(|importScripts|sourceMappingURL=(?!data:)/); + expect(decisionsWebviewConfig({ production: true }).sourcemap).toBe(false); + expect(decisionsWebviewConfig({ production: false }).sourcemap).toBe('inline'); + }); + + it('inlines without a sequence that would end its element, though the bundle holds them', () => { + expect(script).toMatch(/", empty = ""; + var re = /^ + +## Problem Statement + +The Codev extension (`apps/vscode`) spreads the surfaces an architect watches across three places +and two layouts: + +- **This workspace's controls and agents** sit in the Codev activity-bar container as two separate + views, Workspace (`codev.workspace`) and Agents (`codev.agents`), stacked with Backlog, Pull + Requests, Recently Closed, Team and Status. +- **The machine-wide fleet** sits in a third view, Tower (`codev.tower`), in its own + secondary-sidebar container (`codev-tower`), on the other side of the window, hidden until revealed. +- **Work and Decisions**, the dashboard's two summary surfaces, are not in the extension at all. + Work is the one-screen list of builders, what needs attention, backlog and recently closed. + Decisions is where the owner rules on the architect's pending decisions (Spec 1819). To rule on a + decision from VS Code today the owner has to leave the editor for the browser dashboard. + +The owner wants a second, alternative layout for the same extension. It opens from a new button +under the Codev button. It shows one combined left-hand panel, a single hierarchy of Tower → +workspaces → architects and Decisions → the builders each architect spawned, that brings together +what the Workspace, Agents and Tower views show today. It also shows an editor-area split, with the +`main` architect's terminal on the left and Work and Decisions on the right. The existing Codev container and its views stay as they are. This is an **addition**, not +a replacement. + +Affected: the owner (and any Codev user who runs an architect from VS Code or the Codev IDE), in +both distribution channels. Those are the marketplace vsix and the same extension built into the +Codev IDE, including the IDE served by Tower at `/ide/`. + +Pain points today: + +1. Ruling on a decision means switching to the browser dashboard and back. +2. Seeing "what needs me in this workspace" (Agents) and "what needs me anywhere" (Tower) at once + means having both side bars open. +3. There is no one-click way to get the architect-centred working layout. The user has to arrange + editor groups and open each surface by hand. + +## Current State + +**Activity bar / containers** (`apps/vscode/package.json` → `contributes.viewsContainers`): + +| Container | Location | Views | +|---|---|---| +| `codev` "Codev" (`icons/codev.svg`) | activity bar | `codev.workspace` (when `codev.hasWorkspace`), `codev.agents` (when `!codev.isBuilderWorktree`), `codev.backlog`, `codev.pullRequests`, `codev.recentlyClosed`, `codev.team`, `codev.status` | +| `codev-tower` "Codev Tower" | secondary side bar | `codev.tower` | +| `codevPanel` "Codev" | bottom panel | `codev.contextualPanel` (webview) | + +**The three views to combine:** + +- **Workspace** (`views/workspace.ts`, `WorkspaceProvider`): an expandable *Architects* root (one + child per architect, `main` first; click opens that architect's terminal; a sibling has a *Remove + Architect* context entry; the root has an inline *Add Architect*), *Open Web Interface*, *Spawn + Builder*, *New Shell*, a single *Start Dev* / *Stop Dev* row, and one row per `worktree.devUrls` + entry. In a builder-worktree window (#1809) the architect, spawn and shell rows are omitted. +- **Agents** (`views/builders.ts`, `BuildersProvider` over `OverviewCache`): builders grouped on a + switchable axis (stage / area / architect, `codev.buildersGroupBy`). Each builder row expands to + its changed files (`BuilderDiffCache`), flat or as a folder tree. Rows carry a state glyph, inline + *Approve Gate* on blocked builders, and a context menu: open terminal, approve, view + spec/plan/review, view diff, open worktree window/folder, run setup, run/stop dev. Behaviour is + wired to the `codev.agents` **TreeView instance** in `extension.ts`: + - the click handler `codev.openBuilderRow` reveals and expands the row (`codev.buildersClickExpands`); + - the accordion collapses peers on expand (`codev.buildersAutoCollapse`); + - active-file sync reveals the open diff file's row (#1066); + - agent-terminal cycling selects the row (#1563); + - selection fires the `builder-active` activity hook; + - the title shows a live count ("Agents (3)"); + - the view's badge is the Codev activity-bar badge (blocked + idle + held + waiting architects, + suppressed in a worktree window). + + The title bar holds refresh, group-by cycle, accordion toggle and file-tree toggle. +- **Tower** (`views/tower.ts`, `TowerProvider` over `TowerFleetCache`): every workspace Tower knows. + Active workspaces are ordered by urgency, each expandable to its attention rows (pending gates, + waits, architects at a prompt, held mail, queued feedback), and dormant ones sit in a collapsed + group. Rows have inline *Open* / *Deactivate* actions. The title bar has refresh, and the view's + badge carries the machine-wide needs-attention count. + +Menus target the source views by id (`view == codev.agents && viewItem =~ …`), so a row rendered in +any other view today would lose its inline and context actions. + +**What the extension knows about other workspaces.** + +- `TowerFleetCache` already calls `client.getOverview(path)` for **every active workspace** on each + fleet refresh (SSE-triggered with a 300 ms debounce, plus a 20 s fallback poll). + - Each overview carries that workspace's live `architects` and its `builders`, each with + `spawnedByArchitect`, state, gate and worktree path. + - The cache keeps only the derived `AttentionSummary` and discards the overview. + - Dormant workspaces are not fetched. +- No overview carries anything about the decisions file. Its presence is only in `/api/state`'s + `decisionsEnabled`, and its open count is only in `/api/decisions` itself. +- The extension's *actions* are single-workspace: + - `TerminalManager` builds terminal URLs from the window's workspace path and keys its cache by + unqualified names (`architect:main`, `builder-`); + - `codev.openArchitectTerminal` and every builder-row command (approve, diff, artifacts, worktree, + dev) resolve the target against `connectionManager.getWorkspacePath()`; + - `BuilderDiffCache` is keyed by builder id alone. + +**Editor-area placement** (`terminal-manager.ts`): with `codev.terminalPosition: "editor"` (the +default) the architect terminal opens in editor group 1. Builder and shell terminals open in group 2 +if it exists, else group 1. With `"panel"` they open in the bottom panel. `open-architect.ts` holds +the #1497 invariant: a terminal is opened, and cached, only under its occupant's own name, and a +non-live `main` gets the warning *"Codev: No 'main' architect found — is the workspace activated?"*. +Another architect is never substituted. + +**Dashboard Work and Decisions** (`apps/web`): + +- `WorkView.tsx` composes `BuilderCard` (builders table with an *Open* button that selects the + builder's dashboard tab), `NeedsAttentionList`, `BacklogList`, `RecentlyClosedList`, `TipBanner`, + `OpenFilesShellsSection` (dashboard shell and annotation-viewer tabs) and a collapsible `FileTree` + file browser. It has a *+ Shell* button (creates a dashboard shell tab) and *Refresh*. Data comes + from `useOverview` (polls `/api/overview` every 2.5 s, plus SSE) and the dashboard's + `DashboardState`. +- `DecisionsView.tsx` + `hooks/useDecisions.ts` (Spec 1819, #1938): polls `GET …/api/decisions` + every 2 s while the tab is active and the page is visible. It renders open items with + options/comment/Submit, Q&A threads, the current ruling, held drafts and the Ruled section, and + posts rulings to `POST …/api/decisions/rule`. Item images that are workspace paths are fetched + with the key from `GET …/api/decisions/image` and shown as object URLs. http(s) links and images + open in a new tab via `window.open`. +- Both import their transport (`lib/api.ts`) directly. It uses relative URLs, the injected Tower + key and `window`/`localStorage`. So as written they can only run inside the dashboard page. + `DecisionsView` already uses `renderMarkdown` from `@cluesmith/codev-artifact-canvas`, which the + extension also depends on. + +**Extension webview precedent:** `esbuild.js` already bundles two React webviews: the +markdown-preview canvas (#859) and the contextual panel (#1049). Each uses a nonce CSP, a typed +host↔webview message contract with `is*Message` guards on inbound messages (`contextual-panel/ +messages.ts`), and `retainContextWhenHidden`. `@cluesmith/codev-artifact-canvas` is the precedent +for a host-agnostic React package that both apps bundle, with the host supplying I/O through adapter +interfaces and themes through `--codev-canvas-*` tokens. + +**Tower client:** the extension host reaches Tower only through `ConnectionManager`'s shared +`TowerClient` (`@cluesmith/codev-sdk`), which carries the key and the workspace-scoped route prefix. +The SDK has no decisions methods today. Its generic `request()` drops the response body on a non-2xx +status, so it would lose the decisions routes' structured refusal (`{ ok: false, code, message }`). +The precedent for keeping it is the client's existing private `requestPreservingBody`, written so +canvas commands keep a machine-readable `code` across a non-2xx. + +## Desired State + +### 1. A second activity-bar button + +A new activity-bar container, working name **"Codev Cockpit"**, registered directly after the +`codev` container so it sits under the Codev button. Its icon is a new SVG that wraps the same path +as `icons/codev.svg` in `transform="rotate(90 400 400)"` (clockwise). The shape is not redrawn. The +existing `codev`, `codev-tower` and `codevPanel` containers and every view in them are unchanged. + +### 2. One combined left-hand panel: a single hierarchy + +The container holds **one tree view** with **one hierarchy**. In the owner's words, at the spec +gate: *"towers -> workspaces -> architects / decisions -> builders"*. This supersedes the issue +body's reading of step 2 as three side-by-side sections (issue #1963, owner revision comment). + +``` +Tower ← root: this machine's Tower +├─ codev current · 1 gate ← workspace (Tower view's set, labels, order) +│ ├─ MAIN (3) waiting for input ← architect (its own Spec 1595 state) +│ │ ├─ ⚠ spir-1963 [PLAN] … ← builder spawned by MAIN +│ │ │ └─ src/views/cockpit.ts ← changed files (this window's workspace only) +│ │ └─ ● bugfix-1970 … 2 held +│ ├─ WEB (0) ← architect with no builders (leaf) +│ └─ Decisions ← that workspace's Decisions screen +├─ marketmaker 2 waiting +│ ├─ MAIN (1) +│ │ └─ ◐ air-88 … +│ └─ Decisions +└─ Dormant (4) + └─ old-project +``` + +**Levels:** + +1. **Tower.** One root row for the machine's Tower, expanded by default. While there is nothing to + list, it holds a state row that follows the connection: + - *Connecting to Tower…* during the first connection attempt; + - *Not connected to Tower* once an attempt has failed. `ConnectionManager` is then + `disconnected` or `reconnecting`: it keeps retrying with backoff and never gives up. The row + is clickable and runs the existing *Reconnect to Tower* command (`codev.reconnect`) to retry + now. So a window where Tower is not running never sits on "Connecting…" indefinitely; + - *No workspaces registered* when Tower lists none. +2. **Workspaces.** Exactly the Tower view's workspaces, with the same labels (so twelve workspaces' + `MAIN`s are told apart by their parent row), urgency order, *current* marker, icons, attention + summary in the description, inline *Open* / *Deactivate*, and the collapsed *Dormant (N)* group. + This reuses `orderFleet` and `TowerProvider`'s row building, with one behavioural difference: + - **Clicking a workspace row.** In the Tower view, a quiet active workspace is a leaf whose click + opens it. In the hierarchy, every active workspace has children, so clicking its row expands or + collapses it, and *Open* is reached only through the row's inline and context-menu action. + - **Dormant workspaces** have no children, because they have no live session. They keep + click-to-open, as today. + - **Initial expansion.** The window's own workspace and every workspace that needs attention + start expanded; quiet ones start collapsed. + - **Before data arrives.** Until its overview arrives, the window's own workspace shows a single + *Loading…* child, as does any other active workspace whose overview the fleet cache has not + yet fetched, so a row never sprouts its chevron late. +3. **Architects + Decisions.** Under an active workspace: + - its live architects, `main` first, then siblings alphabetically. Two or more idle siblings roll + up into *Idle Architects*. This is the Agents view's architect-axis rendering + (`architectGrouping`, `partitionArchitectGroups`); + - then a **Decisions** entry for that workspace's decisions file. +4. **Builders.** Under each architect, the builders that architect spawned (`spawnedByArchitect`), + in the Agents view's order (blocked, then waiting, then active) and with the architect axis's + `[stage]` prefix. + - A builder with **no recorded spawning architect** sits under `main` (architectGrouping's + existing fold). + - A builder whose recorded architect is **not live** gets that architect's row anyway, as the + architect axis does today. Clicking that row gives the existing "No '' architect found" + warning. + - An **architect with no builders** is a leaf row with no chevron. +5. **Changed files.** Under a builder of the window's own workspace, its changed files, flat or as a + folder tree, exactly as in the Agents view. + +**Data.** There are no Tower route changes, no new requests and no new poll loop: + +- **The window's own workspace** reads `OverviewCache`, as the Agents view does. While visible, the + combined view counts toward the periodic overview refresh (`codev.overviewRefreshSeconds`) the + way the Codev-container views do. So with the Codev container hidden and only the Cockpit + visible, this workspace's rows stay current. +- **Every other active workspace** reads the overview `TowerFleetCache` *already fetches* for it on + each fleet refresh (`client.getOverview(path)` in its fan-out). Today the cache derives attention + from each overview and discards it. It will keep it, last-known-good like the attention it keeps. + These rows refresh when the Tower view's do: on SSE events (debounced) and on the existing 20 s + fallback poll. +- **Decisions:** the overview carries nothing about the decisions file, neither presence nor an + open count, so the Decisions entry carries **no pending count**. It is shown under every active + workspace. Opening it for a workspace with no decisions file shows the Decisions empty state + (section 3). A count, or hiding the entry when there is no file, would need an additive overview + field; see Open Questions. + +**Where rows act: this window's workspace vs the rest.** Every `TerminalManager` key +(`architect:`, `builder-`), the #1497 architect resolution, and every builder command +(approve, view diff, spec/plan/review, worktree window/folder, setup, dev) resolve against **this +window's** workspace today. So: + +- **Rows of the window's own workspace act here, fully.** Every action listed below works, with the + same commands and the same effects as in the source views. The Decisions entry opens, or reveals, + that workspace's Decisions panel (single instance; section 3) without arranging the split. +- **Rows of any other workspace show state and navigate.** Its architects, builders and Decisions + entry display what the overview says (glyphs, labels, descriptions). Clicking one opens that + workspace's window, using the Tower view's existing *Open Workspace* action, where the same rows + are fully actionable. Their tooltip says so. + - They carry their own **navigate-only `contextValue`s**, distinct from the source rows', so none + of this window's builder or architect menus can attach to them. Their only action is + *Open Workspace*, and they do not expand to changed files. + - This is not a regression against the issue's "every action on a row today works on the same + row". Rows of other workspaces' architects and builders do not exist anywhere in the extension + today, and Tower's attention rows carry no actions. + - Acting on another workspace from this window is a separate, larger change; see Open Questions. + +**Placement of everything the three source views do.** Nothing is dropped: + +| Today | In the hierarchy | +|---|---| +| Workspace: *Spawn Builder*, *New Shell* | Inline and context-menu actions on this window's workspace row | +| Workspace: *Add Architect* (inline on the *Architects* root) | Inline and context-menu action on this window's workspace row | +| Workspace: *Remove Architect* (sibling context menu) | Context menu on a sibling architect row of this window's workspace | +| Workspace: architect rows (click opens the terminal) | The architect level. Click runs `codev.openArchitectTerminal(name)`, under the #1497 invariant | +| Workspace: *Open Web Interface* | Context menu on this window's workspace row | +| Workspace: *Start Dev* / *Stop Dev* | Context menu on this window's workspace row, offering whichever one the Workspace view would show (same single-slot rules) | +| Workspace: one row per `worktree.devUrls` entry | *Open Dev URL…* on this window's workspace row's context menu. It opens the only URL, or picks among several (the existing palette path of `codev.openDevUrl`). This is the one Workspace affordance that goes from one click to a menu entry | +| Agents: builder rows: click (open terminal + expand), inline *Approve Gate*, context menu (open terminal, approve, view spec/plan/review, view diff, open worktree window/folder, run setup, run/stop dev) | Builder rows of this window's workspace: identical | +| Agents: changed-files expansion (flat/tree), file click → diff | Identical, for this window's workspace | +| Agents: architect-axis headers (click opens architect), *Idle Architects* container | They are the architect level | +| Agents: stage / area grouping axes, group-by cycle | **Not in the combined panel.** The hierarchy fixes the architect axis. Stage and area grouping stay in the Agents view, and the architect axis's `[stage]` row prefix stays | +| Agents: refresh, accordion toggle, file-tree toggle (title bar) | The combined view's title bar. The toggles write the same global settings (`codev.buildersAutoCollapse`, `codev.buildersFileViewAsTree`), so flipping one in either view changes both | +| Agents: live count in the title | Each architect row's builder count. The workspace row's attention summary | +| Agents: activity badge | The combined view's badge (same count and suppression, as ruled at the gate) | +| Tower: workspace rows, *current* marker, urgency order, inline *Open* / *Deactivate*, *Dormant* group | The workspace level: the same, except that clicking an active workspace's row expands it (it now has children), so *Open* is the inline/context action; dormant rows keep click-to-open | +| Tower: refresh (title bar) | The combined view's *Refresh*, which refreshes both caches | +| Tower attention row: pending gate | The blocked builder row (gate glyph + wait time) under its architect | +| Tower attention row: waits (needs input / idle / dead) | The builder row's state glyph and label | +| Tower attention row: architect at a prompt / agent dead (Spec 1595) | The architect row's description and glyph (the same wait text the attention row uses) | +| Tower attention row: held mail for a builder | The builder row's description (*N held*) | +| Tower attention row: held mail not attributed to a builder | The workspace row's description (*N held*, *escalated*) | +| Tower attention row: queued feedback | The builder row's description (*N queued*) | +| Tower: machine-wide badge | Stays on the Codev Tower container | + +The same state rendering applies to other workspaces' rows (from their overviews), so a gate or +wait anywhere on the machine is visible on the row it concerns. + +**Other requirements:** + +- **Provider instances.** The combined panel has its own provider instances over the shared caches. + - **This window's workspace:** its rows are built by the same code as the source views' rows, + with the same labels, `contextValue`s and `command`s, but they are distinct objects. + - **Other workspaces:** their rows use the same labels and glyphs, with navigate-only + `contextValue`s and commands (above). + - **Per-view state:** row-id versioning for the accordion, the parent map used by `reveal`, and + expansion stay per view, and a row belongs to exactly one view. The *settings* behind the + title-bar toggles are shared and global. + - **Ids:** tree-item ids are qualified by workspace, so two workspaces' `main` or a builder id + that appears in two workspaces never collide. +- **Tree behaviours follow the view a row is in.** Click-expands, the accordion, active-file reveal + (when the combined panel is the visible one), agent-cycle selection and the `builder-active` hook + act on the combined panel's rows for this window's workspace. +- **Menu contributions are added, not edited.** The existing `view/item/context` and `view/title` + entries for `codev.workspace`, `codev.agents` and `codev.tower` stay byte-for-byte. The combined + view gets its own entries, scoped to it, at the placements in the table above. + - **The parity test's oracle** is a checked-in mapping, one record per existing source-view + entry. Each record says either *same command at a combined-view `viewItem`* (the builder, + architect, file and Tower workspace rows of this window's workspace) or *relocated to* a named + combined-view entry. + - **Relocations:** Workspace-view row entries move to this window's workspace row. Agents and + Tower `view/title` entries move to the combined title bar. Dev-URL rows become *Open Dev URL…*. + - **Excluded,** with the reason recorded: the three `codev.agentsCycleGroupFrom*` title entries + (the hierarchy fixes the axis). + - **What fails the test:** an unmapped source entry, or a mapped counterpart missing from + `package.json`. A navigate-only `contextValue` that matches any builder or architect menu + entry's `viewItem` pattern also fails it. +- **Badge.** The combined view badges the new activity-bar button with the same workspace "needs me" + count as the Codev button (`composeActivityBadge`), under the same suppression rules. +- **Degraded windows:** + - In a **builder-worktree window**, the parent workspace's row is marked current but behaves like + another workspace's row: its architects, builders and Decisions entry navigate to the parent's + window and act on nothing here (#1809, and the gate ruling that Decisions is not offered there). + The worktree-scoped actions the Workspace view shows in such a window (*Open Web Interface*, + *Start* / *Stop Dev*, dev URLs) sit on that row's context menu. + - In a **window with no Codev workspace**, every workspace's rows navigate; none acts here. + - A **dormant window** (the marketplace extension in plain VS Code, in a folder with no Codev project) does not connect. Its panel shows *Not connected to Tower*, + not Tower with the fleet. This keeps issue #1144's dormant-window inertness (owner's ruling of + 2026-11-24, at the PR gate). +- **Footprint.** The combined view has no `when`, so the new button appears in every window where + the extension activates (`onStartupFinished`), including non-Codev windows, as the owner ruled at + the gate. This matches today's Codev and Codev Tower containers, which also appear there. In a + dormant window the panel shows *Not connected to Tower*, not Tower with the fleet (owner's ruling + of 2026-11-24). + +### 3. Work and Decisions in the extension, in a split with the `main` architect + +- **Ported views.** The dashboard's Work and Decisions views render in VS Code editor-area webview + panels, from the **same React components** the dashboard uses. The components move to a shared + location that both `apps/web` and `apps/vscode` import. Neither app keeps its own copy. +- **Transport through the host.** The webviews never contact Tower. The extension host serves their + data and performs their actions over webview messaging, using `ConnectionManager`'s client: + - Work's data is pushed from the host's `OverviewCache`, the same source the sidebar uses. A + visible Work panel counts toward the periodic overview refresh, as the sidebar views do. + - Decisions' read, ruling and image requests go through the host to the existing Tower routes. + Refusals keep their structured `code`/`message`, so the card shows the same text the dashboard + shows. + - The Tower key never enters a webview. +- **Decisions is fully functional:** + - it polls while its panel is visible and stops while hidden; + - drafts, held drafts and in-flight submits behave as in the dashboard (Spec 1819), and survive + the panel being hidden or moved between groups; + - a ruling round-trips: Submit → Tower writes the file → the card shows the written ruling, and + Tower's ruling notice to the hub architect (#1828) is sent as it is from the dashboard; + - workspace-path item images load through the host, as bytes the panel shows as object URLs; + - an item image given as an http(s) URL is loaded by the webview itself as a plain ``, as + the dashboard loads it. This is an image load with no key and no script access, not a data + request. A URL the browser refuses (for example an `http:` image inside the IDE served over + `https:`, which mixed-content rules block, or a Tower URL, which answers 401 without the key) + shows the existing "Image not loaded" note; + - an http(s) link opens in the user's browser; + - clicking an image shows it full size inside the panel, because a webview cannot open browser + tabs. +- **Connection and failure states.** Both panels keep last-known-good content, as the sidebar's + caches do: + - before the first data arrives, each shows a loading state; + - while Tower is unreachable or reconnecting, each keeps showing what it last had, with a notice + that it is not connected. Decisions keeps its existing error state (the last document read stays + on screen under the banner), and an in-flight submit that fails shows the error on its card and + keeps the draft; + - a response that arrives after its panel was closed is dropped silently: no toast, no error, no + re-created panel. +- **No decisions file.** A workspace without one (no `afx decisions init`) shows an empty state: + Tower's "There is no decisions file at …" message plus a hint to run `afx decisions init`. It is + not an error banner. The panel keeps polling, so creating the file makes items appear. +- **Dashboard-only affordances, mapped or dropped** (no dead controls): + + | Dashboard affordance | In VS Code | + |---|---| + | Builders table *Open* (select builder tab) | Opens the builder's terminal via `TerminalManager`, as clicking its Agents row does | + | *+ Shell* (dashboard shell tab) | Runs the existing *New Shell* action (a Tower shell opened by `TerminalManager`) | + | *Refresh* | Re-reads the overview from Tower, bypassing Tower's overview cache as the dashboard's does, and updates every consumer of `OverviewCache` | + | Needs Attention / Backlog / Recently Closed http(s) links (issues, PRs) | Open in the user's browser (as the dashboard and the Pull Requests view do) | + | Backlog / Recently Closed *spec* / *plan* / *review* links (dashboard annotation tab) | Open that file in a VS Code editor. The host refuses the path unless its canonical (symlink-resolved) location is inside the workspace | + | *Open Files & Shells* section (dashboard tabs) | **Dropped.** VS Code's own terminal list and editor tabs are the equivalent | + | Collapsible *Files* panel (`FileTree`) | **Dropped.** VS Code's Explorer is the equivalent | + | *Tip of the day* banner | **Dropped.** Its tips are CLI/dashboard tips, some of which do not apply in VS Code | + | Decisions link / full-size image (`window.open`) | Browser for http(s) links. Full-size image shown in the panel | + + In the dashboard every one of these keeps its current behaviour. The dashboard's Work and + Decisions look and behave exactly as before. +- **Themed by VS Code.** Both panels take their colours, fonts and focus styles from VS Code theme + variables, so they read correctly in light, dark and high-contrast themes and follow a theme + change live. +- **Single instance.** One Work panel and one Decisions panel per window, both for the window's own + workspace. Opening either again reveals the existing panel and never creates a second one or + reloads the first. Each can also be opened on its own, from the Command Palette (*Codev: Open + Work*, *Codev: Open Decisions*). Decisions also opens from the hierarchy's Decisions entry under + the window's own workspace. +- **Restored after reload.** An open Work or Decisions panel comes back after a window reload in the + group it was in, using VS Code's webview restore. Decisions drafts do not survive a reload, as + they do not survive a dashboard page reload. + +**The split (*Arrange Cockpit*):** + +- **Result:** the editor area becomes a left column and a right column, with the right column split + into a top and a bottom group. Left holds the workspace's `main` architect terminal, top-right + Work, bottom-right Decisions. Each of the three is the active tab in its group. +- **Architect resolution** uses the existing path (`openResolvedArchitect` → `TerminalManager`). The + left side is always `main`, with no picker. A non-live `main` gets the existing warning and nothing + is substituted. The right side is arranged and renders regardless. An architect terminal already + open is reused, the same session moved to the left group, never closed and reopened. For this + action the architect goes to the left editor group even when `codev.terminalPosition` is `panel`. + Every other open path keeps honouring the setting. +- **The user's open editors are never closed, discarded or reloaded**, including dirty and untitled + ones. They stay open with their unsaved content and may end up in a different group. +- **Triggers:** + - the first time the Cockpit container is visible in a window session, that window is arranged. + This includes a window restored with the container already visible, where no visibility-change + event fires, so the check runs when the view is created as well as on change; + - a window session ends at reload. After a reload the next first show arranges again. Because + arranging is idempotent, an intact layout (panels restored in their groups) changes nothing + visible. The architect terminal, which VS Code does not restore across a reload, is reopened on + the left; + - after the first show, showing the container again leaves the editor area alone; + - *Arrange Cockpit* (Command Palette and the combined view's title bar) arranges on demand at any + time, and is idempotent: running it on an already-arranged window changes nothing visible; + - a setting, `codev.cockpit.autoArrange` (default on), turns the first-show auto-arrange off. With + it off, only the command arranges; + - **a one-time notice on the first auto-arrange** (ruled at the spec gate). VS Code has no + "undo layout", so the first time an auto-arrange happens for this user, an information + notification says the editor area was arranged for the Cockpit. It offers a *Don't arrange + automatically* action, which sets `codev.cockpit.autoArrange` to `false` at the user (global) + level. + - "First" is per user profile: a flag in the extension's global state is set when the notice is + shown, whatever the user does with it, so it never appears again in any window or workspace. + - *Arrange Cockpit* run by hand never shows it, and it is not shown while auto-arrange is off. +- **Where it is offered:** + - in a **builder-worktree window** the split is not offered. There is no auto-arrange and the + title-bar action is hidden. This follows #1809: surfaces that act on the parent workspace stay + in the parent's window. Work and Decisions likewise are not offered there; + - in a **window with no Codev workspace** there is nothing to arrange, and there is no + auto-arrange; + - in both kinds of window, *Arrange Cockpit*, *Open Work* and *Open Decisions* stay invocable + from the Command Palette. Invoking one shows a message saying why it does nothing there, + instead of being silently absent. +- **Placement interaction (accepted, not changed here):** with the split in place, builder terminals + and issue previews that target "group 2" land in the Work group, per today's placement rules. + Changing those rules is #1671's scope. + +### Increments + +The three steps are independently shippable, in this order. Each one leaves the extension complete +and usable, so the work can be cut after any of them; the plan phases against these boundaries. + +1. **The button and the combined hierarchy.** This includes the `TowerFleetCache` overview + retention and the generalised tree wiring. The Decisions entry is not added yet. +2. **The shared component package and the Work and Decisions panels.** They are openable from the + palette and, now added, from the hierarchy's Decisions entry. +3. ***Arrange Cockpit*.** The split, its triggers and `codev.cockpit.autoArrange`. + +## Success Criteria + +- [ ] A new activity-bar button with the rotated Codev icon (same path, `rotate(90 400 400)`) appears + directly under the Codev button on a fresh profile, in VS Code and in the Codev IDE (including + `/ide/`). +- [ ] The existing `codev`, `codev-tower` and `codevPanel` containers, their views, view ids, menu + entries and badges are byte-for-byte unchanged in `package.json` (additions only), and behave + as before. +- [ ] Clicking the new button opens one tree view with one hierarchy: Tower → workspaces (the Tower + view's set, labels, order, *current* marker, Dormant group) → each active workspace's live + architects plus a Decisions entry → the builders each architect spawned → (this window's + workspace only) their changed files. +- [ ] Builders with no recorded spawning architect appear under `main`. An architect with no + builders is a leaf. Two or more idle siblings roll up into *Idle Architects*. A builder whose + recorded architect is not live keeps that architect's row. +- [ ] Every item in the placement table (Desired State §2) is where the table says, and works there. + Every source-view row click, inline action and context-menu entry for this window's workspace + has its counterpart. This is checked by a test generated from `package.json` menus against + that table, so none is missed. +- [ ] Every Tower attention signal (pending gate, wait, architect at a prompt or dead, held mail per + builder and unattributed, queued feedback) is visible on the row it concerns, for this + workspace and for others. +- [ ] Rows of another workspace show state and, when clicked, open that workspace's window through + the existing *Open Workspace* action. They run no other action here and do not expand to + changed files. +- [ ] Two workspaces with an architect named `main`, and a builder id present in two workspaces, + render as distinct rows with no tree-id collision. +- [ ] Builder-row click-expands, the accordion, active-file reveal and agent-cycle selection act on + the combined panel's rows for this window's workspace when it is the visible view. +- [ ] The Agents and Tower title-bar actions other than group-by (refresh, accordion toggle, + file-tree toggle) are on the combined view's title bar. Stage and area grouping stay only in + the Agents view, and the combined panel ignores `codev.buildersGroupBy`. +- [ ] No second poll loop, SSE subscription or new Tower route is added for the combined panel. + Other workspaces' rows come from the overviews `TowerFleetCache` already fetches, so the Tower + request count while the Cockpit is open equals the count with the source views open. +- [ ] With the Codev container hidden and only the Cockpit visible, the overview still refreshes on + the `codev.overviewRefreshSeconds` cadence. With neither visible (nor the Work panel), the + periodic refresh stops, as today. +- [ ] *Arrange Cockpit* produces `main` architect | (Work over Decisions), each active in its group, + with live data in both panels. +- [ ] With `main` not live, *Arrange Cockpit* shows the existing warning, opens no other architect, + and still arranges and renders Work and Decisions. +- [ ] With a dirty file, an untitled buffer and a modified file open across two or more groups, + arranging closes none of them and loses no unsaved content. +- [ ] Re-running *Arrange Cockpit* on an arranged window creates no duplicate panel or terminal and + reloads neither panel. A Decisions draft typed before the re-run is still there after it. +- [ ] Decisions: a pending item can be ruled from VS Code. The file on disk carries the ruling, the + card shows it, and the hub architect receives the ruling notice, the same as from the dashboard. +- [ ] Decisions: a refused ruling (e.g. `item-changed`) shows the server's message on the card and + keeps the draft. +- [ ] Decisions: a workspace-path image (through the host) and an http(s) image (a direct `` + load) both render. A missing or browser-refused image shows the "Image not loaded" note. + Clicking an image shows it full size in the panel. +- [ ] Decisions: a workspace without a decisions file shows the empty state, not an error. Creating + the file makes its items appear without reopening the panel. +- [ ] Work: builders, Needs Attention, Backlog and Recently Closed render from the overview. *Open* + opens the builder's terminal, *+ Shell* opens a Tower shell, *Refresh* refreshes, artifact + links open the file, and http(s) links open the browser. No dropped affordance is rendered. +- [ ] Neither webview fetches from or opens a connection to Tower (no `fetch`, XHR or WebSocket; + the CSP has no `connect-src` beyond what VS Code itself requires). Every Tower request is the + host's, and the Tower key is absent from webview state and messages. The only network loads + a webview makes are http(s) `` sources written in decision items, as in the dashboard. +- [ ] The host opens externally only `http:`/`https:` URLs from a webview, and opens a file from a + webview only when its canonical path is inside the workspace. A symlink escape, `..`, an + absolute path outside the workspace or another URL scheme is refused. +- [ ] With Tower unreachable and then back, both panels keep their last content with a + not-connected notice and recover on reconnect, with no error toast. This is simulated in the + isolated verification instance, never by stopping the owner's Tower. +- [ ] With `codev.cockpit.autoArrange` off, showing the container never arranges, and the command + still does. +- [ ] The first auto-arrange for a user profile shows a one-time notice with *Don't arrange + automatically*. Choosing it sets `codev.cockpit.autoArrange` to `false` globally. The notice + does not appear again, in that or any other window, whether it was acted on or dismissed. It + never appears for a manual *Arrange Cockpit*. +- [ ] The dashboard's Work and Decisions views look and behave as before. Existing `apps/web` tests + (`DecisionsView*.test.tsx`, `useDecisions.test.ts`, `BuilderCard.test.tsx`, + `NeedsAttentionList.test.tsx`, `BacklogList.test.tsx`, `App.decisions-tab.test.tsx`, …) pass + unchanged in intent. +- [ ] No React component used by Work or Decisions exists in two copies in the repo. +- [ ] In a builder-worktree window: the button and combined panel work. The parent workspace's rows + navigate to the parent's window, the worktree-scoped actions are on its row, and the split, + Work and Decisions are not offered. In a no-workspace window: the button and panel work, and + every workspace's rows navigate. A dormant window (the marketplace extension in plain VS Code, + in a folder with no Codev project) does not connect: its panel shows *Not connected to Tower* + and lists no fleet (owner's ruling of 2026-11-24). +- [ ] The Decisions entry under this window's workspace opens, or reveals, the single Decisions + panel without arranging the split. For a workspace without a decisions file it opens the empty + state. +- [ ] Both panels render correctly in a light, a dark and a high-contrast theme and follow a live + theme change. +- [ ] `contributes-*` tests cover the new container, view, commands, setting, menus and their + `when` clauses. The existing `contributes-*` tests pass unmodified apart from additions. Other + existing tests that assert on `extension.ts` source text, such as + `worktree-window-1809.test.ts`'s badge-suppression match, may be updated to follow + generalised wiring, provided the behaviour they guard is unchanged. +- [ ] **Verified by rendering:** the PR carries screenshots taken from a running extension (the + Codev IDE at `/ide/` driven by Playwright, or an equivalent isolated instance). They show the + button; the combined hierarchy with N=0, N=1 and N>1 builders and with two or more workspaces; + the split with a pending decision; and light and dark themes. +- [ ] Lint, type-check and the full `apps/vscode`, `apps/web` and shared-package test suites pass. + +## Constraints + +Prescribed by the architect in the issue ("Prescribed design choices"; settled, not relitigated +here): + +- **Reuse the React components; don't rewrite them.** The extension already bundles React into + webviews (`esbuild.js`, the markdown-preview and contextual-panel webviews) and already depends on + `@cluesmith/codev-artifact-canvas`, which `DecisionsView` uses. If the components have to move to + be shared between `apps/web` and `apps/vscode`, move them to a shared location and have both + import from it. A forked copy inside `apps/vscode` is not acceptable. +- **Webviews don't talk to Tower directly.** Data and actions go through the extension host's + existing Tower connection (`connection-manager.ts`) over webview messaging. That keeps auth, the + workspace-scoped route prefix and web-workbench (`/ide/`) mode working, and respects the + codev-core / codev-sdk import boundary. +- **Dashboard-only affordances need an extension equivalent or get dropped, explicitly.** For each + one the spec says what it maps to in VS Code or that it is left out. No dead buttons. (The mapping + table above.) +- **Theme with VS Code variables**, so the ported views read correctly in light, dark and + high-contrast themes. +- **Both channels.** The same extension ships as the marketplace vsix and inside the Codev IDE. This + must work in both, including a builder-worktree window and a window with no Codev workspace. + +From the issue body: + +- Additive only: the existing Codev container and its views stay exactly as they are; nothing is + removed or moved. +- The icon is a new SVG rotating the same path (`transform="rotate(90 400 400)"`), not a redrawn + shape. +- One source of truth: the combined panel reuses `views/workspace.ts`, `views/builders.ts`, + `views/tower.ts`, `overview-data.ts` and `tower-cache.ts`, with no second copy of fetch or grouping + logic. + +From the owner at the spec gate (issue #1963 comments; supersedes the issue body's "one view with +three sections"): + +- *"towers -> workspaces -> architects / decisions -> builders."* The combined panel is one + hierarchy: Tower → workspaces → architects and a Decisions entry → the builders each architect + spawned. +- Nothing the three source views do may silently disappear. Each is placed in the hierarchy or + deliberately left to the existing views (the placement table). +- No per-workspace poll loop is added to supply hierarchy data, and the "no Tower route changes" + constraint is not dropped quietly. Any need for data Tower does not serve is a gate question. +- Otherwise the spec as drafted stands ("Other than that spec sounds good"): first-show trigger and + `codev.cockpit.autoArrange`; the `terminalPosition` override; no split in worktree windows; the + new shared package; name, rotation and badge; the button in every window; builder-terminal + placement left to #1671. +- The architect goes through `open-architect.ts` / `TerminalManager`, and the #1497 invariant + holds. + +From the system: + +- Server/client isolation (#1189): the shared component package and any new SDK methods import only + `codev-types` (and, for the components, the environment-agnostic SDK helpers and + `codev-artifact-canvas`). They never import `codev-core`. The SDK stays environment-agnostic with + zero runtime deps, and boundary tests enforce this in CI. +- No Tower or decisions-route changes: the Spec 1819 / #1938 routes are consumed as they are. +- VS Code engine floor `^1.128.0`. No API newer than that. +- Webview hardening as in the existing webviews: nonce-gated scripts, a CSP that admits only what + the panels load, `localResourceRoots` narrowed to the extension's bundled `dist` (as the + contextual panel and markdown preview do), and every inbound webview message validated by a type + guard before it is acted on. A path from a webview is treated as untrusted. It is confined to the workspace by its + canonical, symlink-resolved location, not by string prefix. A URL from a webview is opened + externally only if its scheme is `http:` or `https:`. +- The panels' CSP `img-src` is `${cspSource}` plus: + - `blob:`, for host-delivered workspace images shown as object URLs, as the dashboard does (or + `data:`, if the plan encodes them instead); + - `http:` and `https:`, for remote images written in items. Dashboard parity: it loads both. + The existing webviews' `img-src ${cspSource} https: data:` is the starting point. The CSP adds no + `connect-src`, so a webview cannot fetch from Tower or anywhere else. +- The extension stays under the existing `regCli` / `reg` command-registration guard (#791). +- UI changes are verified in a browser via Playwright before being called done + (`codev/resources/testing-guide.md`). Verification must not replace or disturb the owner's live + Codev IDE extension or running workspaces. + +## Assumptions + +- `vscode.setEditorLayout` (or an equivalent built-in layout command) can shape the editor area into + left | (top / bottom) while moving editors from groups it removes, not closing them. This is to be + confirmed in the plan by a spike against a running instance. If it does not hold, the arrangement + must only add or reuse groups and never remove one. +- An existing terminal-editor tab can be moved between editor groups, and from the bottom panel into + the editor area, without ending its session. Same spike. +- Webview `postMessage` can carry image bytes, or an equivalent encoding, efficiently enough for + images up to Tower's 10 MB image cap. +- `OverviewData.architects` stands in for the dashboard's `DashboardState.architects` as Work's + architect count, so Work needs no `/api/state` read. They differ: the overview lists *live* + architects, `DashboardState` all registered ones. In VS Code the builder-attribution tag + (shown when the count is above 1) therefore counts live architects. That is an accepted, + harmless divergence: a stale registration no longer turns the tag on. +- The Codev IDE at `/ide/` can be driven by Playwright with a build of this branch loaded in an + isolated extensions dir or server instance, so verification never touches the owner's live IDE. +- A fixture workspace, with builder entries but no real agents, can produce the N=0 / N=1 / N>1 + builder states and a pending decision without spawning builders. + +## Solution Approaches + +### A. The combined panel + +**A1 — A hierarchical composite over the existing row builders, acting only on this window's +workspace (recommended).** One `TreeDataProvider` renders the hierarchy: + +- the Tower root; +- workspace rows from `TowerProvider`'s row building and `orderFleet`; +- under this window's workspace, the architect-axis rows built by `BuildersProvider` over + `OverviewCache`, then the Decisions entry; +- under each other active workspace, the same architect-axis rows, built by the same pure functions + (`orderForDisplay`, `architectGrouping`, `partitionArchitectGroups`, `builderRowLabel`, + `classifyBuilderRow`) over the overview `TowerFleetCache` already fetched and now keeps. These + rows are navigate-only. + +Tower's attention signals fold onto the rows they concern, using `deriveAttention`'s summary and the +existing `describeWait` / `gateIconFor` text and glyphs. The combined view gets its own menu entries +at the placement table's positions; the existing entries are untouched. The TreeView-bound +behaviours (reveal on click, accordion, active-file reveal, agent cycle, selection hook, badge, +periodic-refresh visibility) are generalised from "the Agents view" to "the view the row is in". + +- Pros: the owner's hierarchy, with no Tower change and no new requests. No copied fetch, grouping + or row logic. Every action of this window's workspace works because the rows are built by the + same code. The rule "act here only for this window's workspace" matches #1809, the gate ruling on + worktree windows, and the Tower view's existing click-to-open behaviour. +- Cons: + - `extension.ts` wiring that today closes over `buildersView` must be generalised; + - `TowerFleetCache` keeps each overview (memory for N overviews, bounded by the number of active + workspaces); + - tree ids must be workspace-qualified; + - Tower's workspace-row node type and `vscode.TreeItem` rows make the element type a union; + - another workspace's rows navigate rather than act. +- Risk: medium. + +**A2 — The same hierarchy, fully actionable for every workspace in this window.** Clicking another +workspace's architect or builder opens its terminal here, its context menu works here, and its +Decisions entry opens its Decisions panel here. This needs no Tower route changes (terminal and +decisions routes are already workspace-scoped), but it is a large extension change: + +- `TerminalManager` keys and URLs qualified by workspace; +- the #1497 invariant restated over (workspace, architect name); +- the reference-injection commands, agent cycling and terminal pruning made workspace-aware; +- every builder command (approve, diff, artifacts, worktree, setup, dev) and `BuilderDiffCache` + made workspace-aware; +- per-workspace Decisions panel instances. + +Pros: one window drives the whole fleet. Cons: doubles the change's surface and reopens a +recently fixed invariant. Not recommended in this spec; offered at the gate as a follow-up. + +**A3 — Keep Tower's attention rows under each workspace, beside the architects.** Pros: the +attention list stays scannable as a list. Cons: every gate and wait appears twice (once as an +attention row, once on its builder row), which is the duplication a single hierarchy is meant to +remove. Not recommended. + +**A4 — A webview that renders the tree.** Re-implements every row, glyph, ordering and menu in HTML, +a second copy of row behaviour, and loses native context menus, keyboard navigation and tree +theming. Rejected. + +*(The draft's three-section composite, one section per source view, is superseded by the owner's +hierarchy ruling.)* + +### B. Sharing Work and Decisions + +**B1 — A new shared React package with host adapters (recommended).** Move `WorkView`, +`DecisionsView`, `useDecisions` and the components they pull in (`BuilderCard`, +`NeedsAttentionList`, `BacklogList`, `RecentlyClosedList`, `issueIds`) into a new workspace package. +It is bundled by each host, not npm-published, the way `codev-artifact-canvas` is. The components +take their data and actions from a small host adapter (overview source; decisions read, rule and +image; open builder, new shell, refresh, open file, open external) instead of importing `lib/api.ts`. +A control renders only when the host provides its action. Each host maps the package's theme +tokens: the dashboard to its palette, the extension to `--vscode-*`. `apps/web` keeps thin wrappers +that supply the fetch-based adapter, so the dashboard is unchanged. Dashboard-only pieces +(`FileTree`, `OpenFilesShellsSection`, `TipBanner`) are passed in by the dashboard host as optional +slots rather than moved. + +- Pros: one copy; mirrors an established repo pattern; a clean host/IO boundary that satisfies the + "webviews don't talk to Tower" constraint by construction. +- Cons: a new package with its own build/test wiring. The existing `apps/web` tests move with the + components or retarget the wrappers. +- Risk: medium. + +**B2 — `apps/vscode` imports from `@cluesmith/codev-web`.** `apps/web` exports `"./*": +"./src/*.ts"`, which covers `.ts` modules only, so even its `.tsx` components would need export +changes. + +- Pros: no move. +- Cons: an app depending on an app. The components still hard-import `lib/api.ts` (relative URLs, + `window.__CODEV_TOWER_KEY__`, `localStorage`), so they need the adapter refactor anyway, and the + vsix bundle would trace into dashboard-only modules. +- Risk: medium, worse layering. Not recommended. + +**B3 — Fold into `codev-artifact-canvas`.** That package's charter is rendering and reviewing +markdown artifacts. Work and Decisions are workspace-state surfaces. Not recommended. + +### C. What triggers the split + +- **C1 — First show per window, plus command (recommended).** Auto-arranges the first time the + container is visible in a window session, including on a restore with the container visible. + After that only *Arrange Cockpit* does it, and `codev.cockpit.autoArrange` turns the auto-arrange + off. Predictable: re-showing the sidebar (Cmd+B, switching back from Explorer) never rearranges + tabs the user has since changed. +- **C2 — Every show (idempotent).** Closest to "clicking the button gives you the layout". But VS + Code cannot tell a click from a sidebar toggle, so tabs the user rearranged, or a panel they closed + on purpose, keep coming back. +- **C3 — Command only.** Least surprising, but the button alone would not give the owner the layout + they asked for. + +### D. The right-hand arrangement + +- **D1 — Two stacked editor groups, Work over Decisions (recommended; the issue's assumption).** + Both are visible at once and resizable with VS Code's own sashes. +- **D2 — Two tabs in one group.** Simpler layout, but only one is visible at a time. +- **D3 — One webview holding both.** No group juggling, but no native resize or separation, and it + couples two independent surfaces. + +## Open Questions + +**Ruled at the spec gate (owner, 2026-11-24 UTC, relayed by the architect and recorded on issue +#1963; recorded here, not reopened):** + +- **Trigger:** first show per window session, plus *Arrange Cockpit*, plus + `codev.cockpit.autoArrange`. +- **`terminalPosition: "panel"`:** *Arrange Cockpit* puts the architect in the left editor group + anyway. Every other open path honours the setting. +- **Builder-worktree windows:** no split, Work or Decisions. +- **Shared code:** a new `packages/` workspace package bundled by both hosts (B1). The plan names it. +- **Name, rotation, badge:** "Codev Cockpit"; clockwise; the workspace "needs me" count. +- **Footprint:** the button is present in every window. A dormant window's panel shows *Not + connected to Tower*, not Tower with the fleet (owner's ruling of 2026-11-24, at the PR gate). +- **Builder terminals:** placement over the Work group is left to #1671. +- **Reload persistence:** Work and Decisions panels are restored after a window reload, as specced. +- **Combined panel:** one hierarchy, Tower → workspaces → architects + Decisions → builders. Section + order is therefore moot. + +Scope and nice-to-know questions, ruled at the same gate (owner: "go with your recommendation" +on all four; recorded on issue #1963): + +- **Acting on other workspaces from this window:** not in this spec. Other workspaces' rows show + state and navigate (A1). Acting on them in place (A2, including the Decisions-only middle option) + is follow-up issue #1969. +- **Decisions pending count / file presence:** no count; the entry appears under every active + workspace. The additive overview field that a count would need is follow-up issue #1970. This + spec keeps "no Tower route changes". +- **Dev URLs:** one *Open Dev URL…* context entry on the workspace row, as specced. +- **First auto-arrange notice:** added as a requirement, with a criterion and a test (section 3, + *Triggers*). +- **Nice-to-know defaults stand:** this window's workspace keeps its urgency slot (#1566) and + starts expanded, and the Decisions entry comes after the architects. + +No questions remain open. + +## Test Scenarios + +**Unit / contribution (vitest, existing harness):** + +1. `contributes-*`: + - the new container after `codev`, the rotated icon file, and the combined view with no `when` + (always present); + - the new commands, which stay in the palette everywhere, and the `codev.cockpit.autoArrange` + setting; + - the title-bar entries (*Arrange Cockpit* hidden in worktree and no-workspace windows); + - menu parity, a generated check that every existing source-view entry has its counterpart at + the placement table's position in the combined view, while the existing entries themselves are + unchanged. +2. Rotated SVG: same `d` path as `codev.svg`, wrapped in `rotate(90 400 400)`. +3. Hierarchy provider: + - Tower root, then workspaces in the Tower view's order, labels, *current* marker and Dormant + group, for the same `TowerFleetCache` state; + - this window's workspace: architect rows and builders equal the Agents view's architect-axis + rows for the same `OverviewCache` state (N=0, N=1, N>1 builders; idle siblings rolled up; + builders with no recorded architect under `main`; a non-live recorded architect; an architect + with no builders), then the Decisions entry; + - another workspace: the same shape from its retained fleet overview, with navigate-only commands + and no changed-files expansion; + - each attention signal lands on the row the placement table names; + - `getParent` chains for reveal; id uniqueness with two workspaces that each have `main` and a + shared builder id; + - worktree-window and no-workspace variants; + - `codev.buildersGroupBy` set to stage or area leaves the hierarchy unchanged. +4. `TowerFleetCache`: it keeps each active workspace's overview from the fetch it already makes, + with no additional request, last-known-good on a failed fetch, dropped when a workspace leaves + the list or goes dormant; the Tower view's rendering is unchanged. +5. Generalised tree behaviours: + - accordion, click-expands and reveal act on the view a row belongs to, both for the Agents view + (regression) and the combined view; + - periodic-refresh visibility: with only the combined view (or only the Work panel) visible the + timer runs, and with none visible it stops; + - the badge: the combined view's badge equals the Codev button's for the same data, and is + suppressed in a builder-worktree window and when disconnected; + - Tower root state rows: connecting, then not connected with *Reconnect* (which runs + `codev.reconnect`), then no workspaces; + - workspace rows: clicking an active row expands it rather than opening it, a dormant row opens + on click, and an overview that has not loaded shows *Loading…*. +6. Host message contract: + - every inbound message guard rejects malformed input; + - file-open paths outside the workspace, `..` escapes and symlinks resolving outside are refused; + - external-open accepts only `http:`/`https:`; + - a response landing after its panel is disposed is dropped. +7. Auto-arrange trigger: fires once per window session, including when the view is already visible + at creation; does not fire again on later shows; does not fire with `codev.cockpit.autoArrange` + off, in a worktree window or in a no-workspace window. In those windows the commands explain why + instead of acting. + - First-arrange notice: shown on the first auto-arrange when the global-state flag is unset, and + the flag is then set. Not shown when the flag is set, for a manual *Arrange Cockpit*, or with + auto-arrange off. *Don't arrange automatically* writes `codev.cockpit.autoArrange = false` at + `ConfigurationTarget.Global`, and dismissing the notice leaves the setting unchanged. +8. Host decisions bridge: document, refusal (structured code/message preserved), transport error, + image bytes / not-loaded; not-found maps to the empty state. +9. Arrange: architect resolution delegates to `openResolvedArchitect` (non-live `main` → warning, no + substitute); single-instance panels; idempotent re-run. +10. Shared components: the existing `apps/web` tests pass against the moved components through the + dashboard adapter. New tests run the same components with a fake host adapter, asserting that + dropped affordances are absent and mapped actions call the adapter. + +**Rendered (Playwright against a running extension, isolated from the owner's live IDE):** + +11. Button: rotated icon directly below Codev; the existing Codev container unchanged. +12. Combined hierarchy with two or more active workspaces and N=0, N=1 and N>1 builders: + - this workspace's builder row context menu shows the same entries as in Agents, and approve, + open terminal and view diff work from it; + - the workspace row's actions work (Spawn Builder, New Shell, Add Architect, Open Web + Interface, Start/Stop Dev, Open Dev URL…), and the Decisions entry opens Decisions; + - another workspace's architect or builder row opens that workspace's window; + - a workspace row opens or deactivates as in the Tower view. +13. Arrange on a window with pre-existing editors (one dirty) → the layout appears and the dirty + editor survives with its content. Arrange again → nothing changes, and a typed Decisions draft + persists. +14. `main` not live → warning; Work and Decisions still render. +15. Decisions: rule a pending item → file updated, card shows the ruling, architect notified. A + stale fingerprint gives a refusal with the draft kept. Workspace and http(s) images render; + full-size view opens and closes. +16. No decisions file → empty state. Run `afx decisions init` → items appear. +17. Work: Open / + Shell / Refresh / artifact link / external link each do what the mapping table + says. +18. Light, dark and high-contrast themes, and a live theme switch. +19. Window variants and degraded states: + - builder-worktree window and no-workspace window, including the commands' explanations; + - Codev container hidden, Cockpit visible: a builder change made in the fixture workspace + appears under its architect in the combined hierarchy within one refresh interval. + - Tower unreachable: both panels keep their content under a not-connected notice and recover + when it returns. This is simulated against the isolated instance's own Tower endpoint; the + owner's Tower is never stopped. +20. Dashboard regression: the browser dashboard's Work and Decisions tabs render and rule as before. + +**Non-functional:** + +21. Tower request rate with the combined panel open is unchanged from the source views alone. The + Decisions poll stops while its panel is hidden. +22. Neither webview fetches from or connects to Tower: the CSP has no `connect-src`, and the key + is not present in webview state. Remote item images are the only webview network loads. + +## Risks and Mitigation + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| The layout command closes or discards a user editor | Low | High | Spike the layout primitive first (Assumptions). The invariant is tested with dirty, untitled and modified editors. If the primitive removes groups unsafely, only add or reuse groups | +| Generalising `buildersView`-bound wiring regresses the existing Agents view | Medium | High | Keep the existing Agents view tests as the regression net, add per-view tests for each behaviour, and render both views in verification | +| A menu entry is missed in the combined view (dead or absent action) | Medium | Medium | A generated test cross-checks every source-view `view/item/context` and `view/title` entry against its counterpart at the placement table's position | +| Users expect another workspace's rows to act here and find they navigate | Medium | Low | The rows say so (tooltip names the workspace and that clicking opens its window). Full cross-workspace action (A2) is a gate question / follow-up | +| Tree-id collisions across workspaces (two `main`s, a shared builder id) break reveal or expansion | Medium | Medium | Ids are workspace-qualified, tested with colliding names | +| Keeping every active workspace's overview grows memory | Low | Low | Bounded by active workspaces. The cache already holds their attention, and it drops an overview when its workspace goes dormant or leaves the list | +| Other workspaces' rows lag this workspace's | Medium | Low | They refresh when the Tower view does today (SSE, debounced, plus the 20 s poll); this is stated, not hidden | +| The combined panel goes stale because periodic refresh is gated on the Codev-container views' visibility | High if missed | Medium | The combined view and the Work panel count toward the existing visibility gate (a success criterion and tests) | +| Tests that match `extension.ts` source text (e.g. `worktree-window-1809.test.ts`) break when wiring is generalised, and the breakage is misread as a regression | Medium | Low | Named in Success Criteria: such tests are updated to follow the wiring, with the guarded behaviour unchanged | +| Auto-arrange or the `terminalPosition` override is unwelcome for some users | Medium | Low | `codev.cockpit.autoArrange` turns auto-arrange off, and the one-time first-arrange notice offers that in one click; the override applies only to the arrange action | +| A webview-supplied path or URL is used to open something outside the workspace or a non-web scheme | Low | High | Canonical-path containment, including symlink resolution, and an `http:`/`https:` allowlist, both enforced and tested host-side | +| Moving components changes the dashboard's look or behaviour | Medium | Medium | Thin dashboard wrappers with the current fetch adapter, the existing `apps/web` tests unchanged in intent, and a dashboard render check in verification | +| A Decisions draft is lost by the layout or by hiding the panel | Low | High | `retainContextWhenHidden`; arrangement reuses panels and never recreates them; tested. Loss on explicit panel close or reload is parity with the dashboard and stated | +| The new button does not sit under Codev for an existing profile (VS Code persists activity-bar order) | Medium | Low | Register directly after `codev`. Verify on a fresh profile and an existing one, and note in the PR if VS Code places it elsewhere for existing profiles (the user can drag it) | +| Verification disturbs the owner's live Codev IDE or Tower workspaces | Medium | High | Run the branch build in an isolated extensions dir or server instance and a fixture workspace; no real builder spawns. Ask before anything that would touch the live IDE | +| Image bytes over `postMessage` are slow or memory-heavy | Low | Low | Tower's 10 MB cap bounds them. Fetch on demand per visible item, as the dashboard does | +| SDK boundary violation (new client methods pull Node APIs) | Low | Medium | New methods use the injected `fetchFn` only; the SDK boundary tests run in CI | + +## References + +- Issue #1963 (this spec's source) +- Spec 1819 — Decisions tab; #1828 ruling notice; #1938 decision images +- #1809 — builder-worktree windows attach read-only to the parent +- #1497 — architect resolution invariant (`apps/vscode/src/open-architect.ts`) +- #1566 — Codev Tower view; #1211 single-SSE lesson +- #913, #1066, #1563, #1743 — Agents accordion, active-file reveal, agent cycling, click-expands +- #1049 — contextual panel (webview precedent); #859 — markdown-preview canvas webview +- #1189 — server/client isolation +- Related, not absorbed: #1614 (secondary-sidebar container), #1671 (editor-group placement model), + #1548 (architect-context render target) +- `packages/artifact-canvas/README.md` — host-adapter package precedent +- `codev/resources/testing-guide.md` — Playwright verification; `codev/resources/arch.md` — VS Code + Extension, IDE prefix forward (#1668) diff --git a/codev/state/spir-1963_thread.md b/codev/state/spir-1963_thread.md new file mode 100644 index 0000000000..d01181350a --- /dev/null +++ b/codev/state/spir-1963_thread.md @@ -0,0 +1,1378 @@ +# spir-1963 thread — VS Code alternative layout ("Codev Cockpit") + +## 2026-11-23 — Specify + +No spec existed; wrote `codev/specs/1963-vscode-alternative-layout-seco.md` from the issue. +The issue has no "Baked Decisions" section, but its "Prescribed design choices" are copied into +Constraints as settled. + +Findings that shaped the spec: +- Much Agents-view behaviour is bound to the `codev.agents` TreeView *instance* in `extension.ts` + (click-expands reveal, accordion, active-file reveal, agent-cycle select, badge, title count), and + every menu `when` names the source view id. A combined view needs that wiring generalised to "the + view the row is in" — the main risk on the panel side. +- Work/Decisions components hard-import `apps/web/src/lib/api.ts` (relative URLs, injected key, + localStorage). Sharing them needs a host-adapter seam; recommended a new shared package on the + `codev-artifact-canvas` pattern. +- The SDK `TowerClient` has no decisions methods, and its `request()` drops non-2xx bodies — the + decisions refusal `{ok:false, code, message}` needs preserving. +- `window.open` doesn't work in VS Code webviews (no allow-popups) → Decisions' links/full-size + images need host equivalents. +- Verification must not replace the owner's live IDE extension — isolated instance + fixture + workspace. + +Open points resolved with recommendations, for confirmation at spec-approval: trigger = first show +per window + command; `terminalPosition: panel` overridden for the arrange action; no split/Work/ +Decisions in a builder-worktree window (#1809). + +## 2026-11-23 — Spec consultation (iter 1) → spec-approval + +Codex COMMENT, Claude REQUEST_CHANGES — all points accepted, none disputed (rebuttal in +`codev/projects/1963-*/1963-specify-iter1-rebuttals.md`). Main changes: +- Menus: existing source-view entries left byte-for-byte; the combined view gets mirrored entries + guarded by a generated parity test (widening `when`s would have broken `contributes-tower.test.ts`). +- Freshness: the combined view and the Work panel count toward the existing periodic-overview + visibility gate — otherwise the Cockpit freezes whenever the Codev container is hidden. +- Own provider instances over shared caches (per-view accordion/reveal state). +- Added `codev.cockpit.autoArrange` (default on); defined "window session" (ends at reload); + connection/failure states; canonical-path + http(s)-only host checks; commands stay in the + palette in worktree/no-workspace windows and explain themselves. + +Stopped at spec-approval. + +## 2026-11-24 — Owner revision at the gate: one hierarchy + +Owner: combined panel is ONE hierarchy — "towers -> workspaces -> architects / decisions -> +builders" — not three sections. Spec otherwise approved as drafted ("Other than that spec sounds +good"); porch approve is waiting on the architect's go after checking the revision. + +What the data check found: +- TowerFleetCache already fetches getOverview(path) for every active workspace and discards it + after deriving attention — retaining it gives every workspace's architects + builders + (spawnedByArchitect) with no new requests or routes. +- Overview has nothing about the decisions file → no pending count without an additive Tower field. +- All actions (TerminalManager keys/URLs, #1497 resolution, every builder command, diff cache) are + scoped to the window's own workspace → spec makes other workspaces' rows navigate (open that + workspace's window); fully cross-workspace action is offered as a gate question / follow-up. +- Attention rows fold onto the rows they concern; stage/area grouping stays in the Agents view; + dev URLs move to an "Open Dev URL…" context entry on the workspace row. + +Revision committed; re-consult (codex + claude, manual — porch is at the gate) running. + +## 2026-11-24 — Hierarchy revision re-consult + +Codex REQUEST_CHANGES, Claude COMMENT on 76e1dc498; all accepted (rebuttal: +`1963-specify-revision1-rebuttals.md`). Main changes: remote item images are direct `` loads +(CSP img-src gains `http:`; no connect-src), other workspaces' rows get navigate-only +contextValues, the parity test has a checked-in mapping oracle, an Increments subsection (button + +hierarchy → shared package + panels → arrange), active workspace rows click-expand (Open moves to +the inline action), Tower root shows "Not connected to Tower" + Reconnect after the first failed +attempt (ConnectionManager retries forever, never gives up), Loading… child before an overview. +New owner question offered, not specced: a one-time notice on the first auto-arrange. + +## 2026-11-24 — Spec approved → plan + +Owner approved the spec ("go with your recommendation" on all four): other workspaces navigate-only +(acting in place → #1969), no Decisions pending count (→ #1970), dev URLs as "Open Dev URL…", and +ADD the one-time first-auto-arrange notice. Rulings recorded in the spec (95029fd66); ran +`porch approve 1963 spec-approval` on the architect's relay. + +Plan gate is pre-approved by the owner for a plan that implements the approved spec; I still wait +for the architect's go (after their check) before `porch approve 1963 plan-approval`. + +Plan (9475ca950): 8 phases on the spec's 3 increments — +1 fleet-cache overview retention · 2 `ArchitectTreeBuilder` extracted from BuildersProvider +(scoped ids, act/navigate modes; Agents ids byte-identical) · 3 Cockpit container + hierarchy + +generalised tree wiring · 4 placement-table menus + parity mapping oracle + rendered check · +5 `@cluesmith/codev-workspace-views` (source-exported, host adapter, `--codev-wv-*` tokens), +dashboard on wrappers · 6 SDK decisions methods + Decisions panel + Decisions entry · 7 Work panel · +8 spike then Arrange Cockpit + triggers + notice. +Verification harness: isolated Tower (non-default port, own CODEV_AGENT_FARM_DIR) + `code serve-web` +with isolated data/extension dirs + fixture repos — never :4100 or the owner's /ide/. +Finding while planning: builder rows show no held/queued today, so those counts are Cockpit-only +(an `attentionCounts` option) to keep Agents byte-for-byte. + +## 2026-11-24 — Plan consultation → plan-approval + +Iter 1: Codex REQUEST_CHANGES, Claude COMMENT. Iter 2: both COMMENT. All points accepted (rebuttals +`1963-plan-iter{1,2}-rebuttals.md`). Things the reviews caught that the code confirmed: +- `requestPreservingBody` reads text → decision images need a binary request path. +- `/api/overview` lists only builders with a LIVE builder terminal, and `spawnedByArchitect` comes + only from global.db's `builders` row → the harness spawns fixture builders for real + (`afx spawn --task`, `CODEV_ARCHITECT_NAME`, plain-shell `shell.builder`) against an isolated + Tower; gate asserts attribution before screenshots. +- `removeArchitect` falls back to the display label (`WEB (0)`); Cockpit architect rows need + main/sibling context values. +- Hidden retained webviews still report `visibilityState === 'visible'` → host relays panel + visibility into `useDecisions`' `isActive`. +- Existing webviews use `style-src 'unsafe-inline'`; BuilderCard needs it. +- Windows path cases + windows.yml dispatch for the containment code. + +At plan-approval. Owner pre-approved the plan; waiting on the architect's check and go. + +## 2026-11-24 — Harness revision (architect: "no go yet") + +The architect caught that the plan's `afx spawn --task` "against the isolated Tower" could not have +worked, and the code confirms it: +- `spawn.ts:110` and `spawn-worktree.ts:738` use `getTowerClient()` with no port, so they go to the + literal 4100; +- there is no env override and no `--port`. + +Seeding a ported client in-process doesn't save it either: +- spawn shells out to `porch init` (`spawn-worktree.ts:490`); +- porch's dispatcher then posts `refreshOverview` via `new TowerClient()` to :4100 (`porch/index.ts:1505`). + +Other default-port paths: +- `afx tower start`, `workspace add-architect` and notifications; +- the extension, which shells out to `afx` and `porch` (spawn, approve, cleanup, auto-start); +- the extension reads `~/.agent-farm/local-key` unless `CODEV_TOWER_KEY` is set. + +**Chosen mechanism: harness-only, no product change.** The harness runs no Tower-contacting CLI +command: +- **Tower:** `tower-server.js -p $PORT` directly, with `CODEV_AGENT_FARM_DIR` and + `SHELLPER_SOCKET_DIR` (the default socket dir is the owner's `~/.codev/run`). +- **Fixtures:** + - activation and add-architect over HTTP to the explicit port; + - porch state and `upsertBuilder` in-process, with the db path pinned and checked; + - builder terminals via `POST :$PORT/api/terminals`; + - `afx decisions init`, which is file-only. +- **VS Code:** + - `CODEV_TOWER_KEY`, `codev.towerPort` and `autoStartTower=false`; + - recording PATH stubs for `afx`, `porch` and `codev`, so CLI-shelling actions are verified by + their recorded argv. +- **Safety checks:** a pre-flight that refuses 4100 and checks the listener PID, plus a :4100 + connection tripwire. + +**Re-review:** Codex REQUEST_CHANGES, Claude COMMENT. Changes taken: +- the harness became **Phase 1**, with self-tests proving every refusal and the tripwire; +- the layout spike moved into Phase 1 (Codex wanted it before plan approval; offered to the + architect). b/c/d failures go to the owner, and Phase 9 waits; +- the Cockpit holds the worktree config off `codev-config-updated`, so the request count matches; +- WorkView's `DashboardState` prop leaves the shared surface, and the file-panel slot is the whole + wrapper; +- the package declares its own test devDependencies and the lockfile changes with them; +- the smoke test builds its own bundle, since CI never builds `dist`. + +Phases are now 1–9. Rebuttals are in `1963-plan-harness-rebuttals.md`. + +## 2026-11-24 — Layout spike, run before plan approval (architect: strict reading) + +Setup: an isolated `code serve-web` on :18763, VS Code 1.147.0. The CLI, server, user and +extensions dirs were all in the scratchpad. A throwaway extension was driven by headless Chromium +from the existing Playwright cache, with no install. There was no Tower, and the serve-web tree had +no :4100 connection. All processes were stopped by PID. + +**All four cases held:** +- **(a)** `setEditorLayout` over 5 groups gave 3 (left | top/bottom). Nothing closed, all text was + intact and dirty stayed dirty. It is idempotent. +- **(b)** An editor terminal moved from group 3 to group 1 with the same PID and shell. +- **(c)** A panel terminal went to the editor area (`moveToEditor`) and then to group 1, intact. +- **(d)** A retained webview moved while visible and while hidden, with no reload (same load id). + +**Design fact:** removed groups merge into the LAST group (bottom-right = Decisions). So arrange +reveals Decisions after the layout call. + +**Harness lessons from the first run:** +- web defaults `files.autoSave` to afterDelay, which silently saved the "modified" fixtures; +- Restricted Mode raises a trust modal on terminal creation, which hung case b. + +Both are now in the harness section. A side gotcha: zsh doesn't word-split `$PIDS`, so a +`kill $PIDS` silently did nothing. I killed per PID instead. + +The evidence is in `codev/projects/1963-…/layout-spike/`. + +## 2026-11-24 — Phase 1 (verification_harness): harness built, self-test green + +I told the architect before the first isolated Tower start. Their OK came at 07:02Z, and they +accepted two deviations: +- **Scratch HOME** for every harness child (Tower, driver, serve-web, browser). This is an extra + layer beyond the plan. +- **The socket dir is a short `/tmp/cckp-` symlink** to `/cockpit-harness/run`. + macOS caps a Unix-socket path at 104 bytes, and the scratchpad path alone is 135, so a socket dir + literally under the scratchpad cannot work. + - Gate 2 checks the realpath, and also checks the socket-path length. + - Teardown removes the link even after a failed start (the architect's condition). + - Standing order: if pre-flight or the tripwire fires in a real run, stop and tell the + architect before retrying. + +Findings that shaped the code: +- **Plain-shell fixtures.** A `bash` architect auto-detects the **claude** harness and would be + handed claude's session and role args. So each fixture's `.codev/config.json` names a no-op custom + harness (`roleArgs: []`, `roleScriptFragment: ""`). +- **No adopt.** `launchInstance` runs `npx codev adopt` when `codev/` is missing, so fixtures always + carry `codev/`. The driver fails if activation reports `adopted`. +- **Builder terminals.** `POST /api/terminals` only registers a builder (shellper-backed) with + `persistent: true`, which the plan table omitted. The driver requires `persistent === true` in + the response. +- **Machine settings.** User settings in serve-web live in the browser, so the harness writes + `/Machine/settings.json`. Restricted Mode ignores the `codev.tower*` settings only + from *workspace* settings, so Machine settings still apply. +- **Allowlisted environments.** Child environments are built from an allowlist, so no `CLAUDE_CODE_*`, + `VSCODE_*`, `CODEV_*`, `NODE_ENV` or token variables leak in. + +`harness.mjs selftest` passes all 14 cases: +- gate 1: port 4100, a non-numeric port, and a port that already has a listener; +- gate 2: `~/.agent-farm`, an agent-farm dir outside the scratchpad, `~/.codev/run`, a socket dir + outside the scratchpad, and an over-long socket dir. Each refuses with nothing created; +- gate 3: a `NODE_ENV=test` driver against a real production-mode isolated Tower refuses, and no + `test.db` or fixture is created; +- gate 4: a foreign listener refuses; +- teardown by PID, with the link removed; +- the tripwire ignores a connection from outside the tree, and fires (exit 3) on one from a harness + child. + +**Acceptance run from the committed tree (541d60aa0).** I rebuilt the vsix, then ran selftest +(14/14), start, check (10/10), `seed one-builder` (gate 6 shows `builder-spir-101` spawned by +`main`), check again (10/10), and stop (15 PIDs killed, none left, link removed, no listeners). The +workbench renders Agents (1) → SPECIFY → #101 fixture-one from the isolated Tower. + +Two things the first live checks caught: +- The trust banner and status item render after the Codev activity-bar item, so trust is now + detected by `#status.workspaceTrust` once the Codev status item has appeared. +- In 1.147 the Workspace Trust editor is a *modal* editor that blocks clicks, so it is closed with + Escape. + +Separately, the extension activates `alpha` on the isolated Tower by itself when it loads, so +`main` exists before any seed. That is expected and harmless. + +### Phase 1 review, iteration 1 (2026-11-24) + +- Checks: `porch done` ran the full suite once (build 17.1s, tests 54.0s), and it passed. +- Codex asked for changes. The plan's IDE-server alternative to serve-web was missing. I added + `COCKPIT_VSCODE=ide-server` with `COCKPIT_IDE_SERVER_BIN`. It launches the VS Code Server + binary directly with `ide-server.ts`'s flags, all under the scratchpad. The mode is explicit, + never an automatic fallback, per the fail-fast rule. Verified `start`, `check` 10/10 and + `stop` (10 PIDs, none left) in that mode. +- Claude approved, with non-blocking notes, and I took them all: + - the tripwire now starts before the Tower launch; + - the README now says the tripwire is a detector, not the enforcement; + - the README now says seeding is once per `start`; + - removed an unused import; + - honour `PLAYWRIGHT_BROWSERS_PATH`; + - two new gate-1 self-test cases. +- Re-verified in serve-web mode. Self-test 17/17, `start`, `check` 10/10, `seed one-builder` + (gate 6: `builder-spir-101` spawned by `main`), `check` 10/10, `stop` (15 PIDs, none left). + +### Phase 1 review, iteration 2 (2026-11-24) + +- Both reviewers approved (Codex with no issues). I took Claude's non-blocking notes before + advancing, because one would have broken later phases: + - **vsix freshness.** `check` called any uncommitted input edit stale and missed untracked + files. So every edit, `build-vsix`, `check` cycle in Phases 5, 8 and 9 would have shown a + spurious FAIL. `build-vsix` now records a content digest of every tracked or untracked input + file, and `check` compares it. Verified all four cases: clean build passes; a file added after + the build fails only the vsix item; a change built in passes; removing it fails again. + - **Tripwire cost.** One sample is about 0.3 s of `ps` plus two `lsof` calls, so sampling at + 1 s kept about a third of a core busy. Now it samples every 2 s and runs the machine-wide + `lsof -U` every 5th sample. Shellpers stay covered between scans as descendants of the live + Tower. + - The socket-prefix match now needs a trailing `/`. + - The README now explains why `selftest` needs the web port (its refusal cases run real `start`). +- Full suite: the architect's standing rule (decision ide-1, 07:27Z) allows `porch done`'s suite + without asking when the 1-minute load is under 6 and no other vitest is running, checked right + before. + - Iteration-1 rebuttal run: load 2.55, passed. + - Iteration-2 run: I waited out a load of 8.18; at 4.85 it passed. + +### Phase 2 (`fleet_overviews`), iteration 1 (2026-11-24) + +- `TowerFleetCache` now keeps the overview it already fetched for each active workspace, instead + of discarding it after `deriveAttention`. + - `FleetEntry` gains `overview: OverviewData | null`. + - A new `lastOverview` map holds the last-known-good overview, next to `lastAttention`. + - A new `getOverview(path)` accessor returns it. +- Behaviour: + - A failed (`null`) fetch keeps the previous overview. + - A dormant workspace gets `null` and drops what it had. A reactivated workspace whose first + fetch fails does not get its pre-dormancy overview back. + - A workspace that leaves the list is dropped. + - A transiently empty list keeps everything, as before. +- No new requests: per refresh there is still one `getOverview` call per active workspace. +- I changed two files outside the plan's list, `tower-provider.test.ts` and + `switch-workspace.test.ts`. Their `entry()` helpers build `FleetEntry` literals, and `tsc` + type-checks the tests, so the helpers needed the new required field. It was a one-line change + in each. +- The stale-fan-out test calls the private `fetchFleet` directly. `refresh()` serialises + fan-outs, so through the public API the sequence guard is only a backstop and the race cannot + be reached. +- Mutation-checked: removing the sequence guard, the map rebuild, or the retain-on-null each makes + its matching test fail. +- `check-types` and `lint` are clean, apart from the two pre-existing `curly` warnings. + `test:unit` passed 1293/1293. +- `porch done` checks passed: build 15.6 s, tests 56.4 s, at a 1-minute load of 3.44 with no other + vitest running. +- Review: Codex and Claude both approved with high confidence, and neither raised a blocking issue. + - Taken now: Claude's note that the accessor hands out the cached object by reference. The doc + comments on `FleetEntry.overview` and `getOverview` now say it is read-only. + - Carried into Phase 4, not changed here: + - The window's own workspace is retained twice, in `OverviewCache` and in the fleet cache. The + Cockpit must keep reading `OverviewCache` for it, as the spec says. Reading the fleet copy + would lag. + - The fleet cache keys by Tower's path spelling. Phase 4's current-workspace match must use + the existing `isSameWorkspacePath` (`fleet-order.ts`), as `orderFleet` does, and a test should + assert it. + +### Phase 3 (`architect_tree_builder`), iteration 1 (2026-11-24): row building moved into `ArchitectTreeBuilder` + +- New `apps/vscode/src/views/architect-tree.ts`. `ArchitectTreeBuilder` now owns what + `BuildersProvider` did privately: + - row-id versioning (`AccordionRowIds`, now with a scope prefix) and the builder → group parent + map; + - group, builder, *Idle Architects* and changed-file rows, and their `getParent` reconstruction; + - `findFileItem`, `revealTargetForAgent` and `agentCycleOrder`. +- `BuildersProvider` is a thin provider over one builder with scope `''`, mode `act` and its + active axis. `builders.ts` re-exports every symbol that moved (`orderForDisplay`, + `partitionArchitectGroups`, `findParentNode`, `AccordionRowIds`, `AgentTarget`), so no importer + changed. `agentTargetIsFocused`, `agentCycleAttemptOrder`, `AccordionGate` and + `runBuilderRowClick` stay in `builders.ts`: they are view wiring, not row building. +- The five row classes take an optional trailing `scope` that prefixes their id and is kept as a + property. With `''` every id is the one it was. +- Modes: + - `act` + scope `''` (Agents): unchanged. + - `act` + a scope (this window in the Cockpit): architect rows get `cockpit-architect-main` or + `cockpit-architect-sibling`. Builder, file and folder rows keep the Agents contextValues and + commands. + - `navigate`: builder rows are leaves; architect rows still expand. Every architect and builder + row clicks to `codev.tower.openWorkspace` with the target, and its tooltip names the workspace. + contextValues are `REMOTE_CONTEXT` (`cockpit-remote-architect`, `-builder`, + `-idle-architects`). `findFileItem` and `revealTargetForAgent` answer `undefined`, because the + agent cycle and the active-file reveal are about this window's agents only. + - `attentionCounts`: appends `N held · N queued` to builder-row descriptions, from + `deriveAttention` over the builder's own `getData()`, recomputed when the overview object + changes. It is off for the Agents view. +- Deviations from the plan's wording, behaviour unchanged: + - The stage/area root branch and the lone-`Uncategorized` flatten moved into + `ArchitectTreeBuilder.rootRows()` with the architect branch. The plan said they would stay in + the provider. All three branches depend on the parent-map reset the builder owns, and the + builder already receives the active axis. Leaving them in the provider would have meant a + "reset, then call back in" protocol across two classes. The snapshot covers all three axes. + - Navigate options take no `grouping`: navigate mode is always the architect axis, so the type + rules out the other axes. + - Navigate `target` is a function, read on every render, so a workspace whose label changes + (disambiguation) never shows a stale name or target. + - The *Idle Architects* container in navigate mode has no click command, as in the Agents view: + clicking it toggles it. It carries `cockpit-remote-idle-architects`. +- Three of the tests the plan names live in the Electron suite (`src/test/`), not `__tests__/`: + `builders.test.ts`, `area-grouping.test.ts` and `builder-file-tree-item.test.ts`. `check-types` + compiles them, and their imports and constructor calls are unchanged. They were not run, because + they need the vscode-test Electron harness. +- Tests: `apps/vscode/src/__tests__/architect-tree.test.ts`, 33 tests. + - Equivalence: the walk covers N=0/1/>1 builders × 3 axes × flat/tree file modes (18 cases). It + records every row's id, label, description, contextValue, collapsible state, icon, command and + tooltip, its `getParent` answer, and the agent-cycle roster. The snapshot + (`__snapshots__/architect-tree.test.ts.snap`) was recorded from the **pre-refactor** provider + before any source change, and it matches after. + - Builder tests: scoped ids and disjointness, including two acting scopes and one navigating + scope over shared `main` and builder ids, in both file modes. Also: accordion re-versioning + under a scope, main/sibling contextValues, the null-owner fold, the non-live architect, the idle + roll-up, a childless leaf, `getParent` chains (file → folder → folder → builder → architect, + and idle sibling → container), and agent-cycle targets. + - Navigate tests: leaf shape, the click command, tooltips, labels and glyphs equal to the acting + rows, a target read on every render, and attention counts in both modes. Every `viewItem` + pattern in `package.json` is parsed, and none of them matches a `REMOTE_CONTEXT` value. + - Mutation-checked: unscoping each id kind, a non-leaf navigate builder, a remote contextValue + that a builder menu matches, dropping the cockpit-architect contextValues, a stale counts cache, + and the folder's default scope each fail a test. Giving the Agents view the cockpit contextValue + or an empty description fails the snapshot. +- `check-types` is clean. `lint` shows only the two pre-existing `curly` warnings. `test:unit` + passed 1326/1326 (1293 + 33). `esbuild` bundles. +- Review, iteration 1: Codex and Claude both approved with HIGH confidence, and neither raised a + blocking issue. + - Taken now, from Claude's non-blocking notes: + - `agentCycleOrder()` returns `[]` in navigate mode, as `findFileItem` and + `revealTargetForAgent` already did. The cycle opens terminals through this window's + `TerminalManager`, so another workspace's agents must never enter it. + - `getChildren` and `getParent` throw on a row whose `scope` is another builder's. + `getChildren` also throws on an unrecognised row, where it used to fall through and render + the root again. A Phase 4 routing mistake now fails loudly instead of duplicating rows. + - A new test asserts that two builders' accordion versioning is independent. + - Each of the three was mutation-checked. `test:unit` passed 1329/1329. + - Carried into Phase 4, not changed here: + - Rendering this window's builder rows probes the disk for a review file + (`builderHasReviewFile`). The Cockpit will render on fleet ticks as well as overview changes, + which roughly doubles those probes. Keep that in mind when Phase 4 chooses its re-render + signals. Navigate rows do no fs work. + - `architect-tree.ts` imports `views/tower.ts` for `OPEN_WORKSPACE_COMMAND` and + `WorkspaceTarget`. There is no cycle and nothing touches `vscode` at load time. The import is + cosmetic and stays as it is. + - Snapshot provenance: Claude could not confirm from git that the snapshot predates the refactor, + because both landed in one commit. The order was: test written, snapshot recorded + (`Snapshots 18 written`) against the untouched `BuildersProvider`, then the source changes, + after which the snapshot matched unchanged. The mutation runs also show the snapshot is not + self-confirming: giving the Agents view a cockpit contextValue or a description fails it. + +### Phase 4 (`cockpit_hierarchy`), iteration 1 (2026-11-24): the Cockpit button and its tree + +- The button: `codev-cockpit` sits directly after `codev` in the activity bar, with + `icons/codev-cockpit.svg` (`codev.svg`'s path wrapped in `rotate(90 400 400)`). It holds one + view, `codev.cockpit`, with no `when`, and a title-bar *Refresh* (`codev.cockpit.refresh`, which + refreshes the overview and the fleet). Checked: the whole `contributes` block minus these + additions is byte-identical to the Phase 3 commit's. +- `views/cockpit.ts`, `CockpitProvider`. Tower root → state rows (*Connecting…* until an attempt + fails, then *Not connected* → `codev.reconnect`; *No workspaces registered*) or the workspaces + in the Tower view's order, labels, *current* marker and *Dormant (N)* group. Then one + `ArchitectTreeBuilder` per active workspace, cached by scope `ws:|` and pruned on leave: + this window's workspace acts on `OverviewCache`; every other one navigates on the fleet's + retained overview. *Loading…* until a workspace's overview lands. `getParent` reaches the Tower + root from every row. +- Shared row code: `workspaceRow(ws, 'none' | 'collapsed' | 'expanded')` and `dormantGroupRow` + are extracted from `TowerProvider`, whose output is unchanged (its tests pass unmodified). +- `views/agent-tree-hosts.ts`, `AgentTreeHosts`: the Agents view and the Cockpit are two hosts. + The row click, the per-view accordion (one `AccordionGate` each), the follow-reveals, the + `builder-active` selection hook and the badge act on whichever view a row belongs to, matched by + its `scope`. Another workspace's rows never act. +- `views/overview-refresh-gate.ts`, `OverviewRefreshGate`: the periodic overview refresh, lifted + out of `extension.ts` unchanged, with the Cockpit added to its view list. It is a new module so + the visibility gate is unit-testable; Phase 8 adds the Work panel to the same list. +- `mailbox-indicators.ts`, `workspaceActivityBadge`: the badge computation, lifted out of + `extension.ts` as a pure function. It is assigned to both views. +- Decisions taken here, each small (raise any at review): + - Follow-reveals (active file, agent cycle) land in every *visible* host. When none is visible + they land in the Agents view, exactly as before. Revealing in a hidden view opens its + container, so revealing in both would flip the sidebar between them. + - A navigate row's target always has `isCurrent: false`. In a builder-worktree window the + parent is marked current, and `openOrActivateWorkspace` returns early on `isCurrent`, so the + click would do nothing. Its window is not this one. + - A dormant window (guest mode, no Codev workspace) never connects, so the root says *Not + connected to Tower* with no Reconnect command (the command is a no-op there) instead of + *Connecting…* forever. + - Once the fleet has loaded, a dropped connection keeps listing the last-known workspaces. The + spec puts the state row on the root only "while there is nothing to list". + - The architect rows' attention (Spec 1595 wait text and glyph) lives in `ArchitectTreeBuilder` + behind the Phase 3 option, renamed `attentionCounts` → `attention`. It is off for Agents, so the + Phase 3 snapshot still matches. + - `ArchitectTreeBuilder.getParent` builds the root rows when it does not yet know a builder's + group. The Cockpit asks before its workspace node was ever expanded (the active-file reveal + with collapsed ancestors), and the old answer, "root", broke the chain. The Agents view is + unchanged: its root always renders first. +- Re-render cost, as carried from the Phase 3 review: the Cockpit redraws on every fleet tick as + well as every overview change, so this window's builder rows run `builderHasReviewFile` (one + `readdirSync` each) about twice as often as the Agents view, and an expanded builder row may + re-read its 15 s-TTL diff on a fleet tick. Accepted: it is a handful of small local reads. +- Observation, not changed: an idle sibling at a prompt is folded inside the collapsed *Idle + Architects* container, so its wait text is one click down. The workspace row's summary still + shows it. +- Tests: + - `cockpit-provider.test.ts` (40); + - `cockpit-wiring.test.ts` (21); + - `contributes-cockpit.test.ts` (8), with snapshots of the `codev` views and every non-Cockpit + menu entry, checked against the Phase 3 commit; + - `cockpit-icon.test.ts` (3); + - `worktree-window-1809.test.ts`: its badge match now follows the generalised wiring and asserts + both views, plus a behavioural check on `workspaceActivityBadge`. + - Mutation-checked, 45 mutations across the provider, the hosts, the gate, the badge, the tower + extraction and the `extension.ts` wiring; every one is killed. Three survivors on the first pass + (connected-before-load, pruning, `restart()`) got stronger tests. + +### Phase 4: `porch done` tests check failed (2026-11-24) + +- Ran when load was 5.90 with no vitest running. `build` passed; `tests` (`packages/codev`, 68.5 s) + failed. porch printed only npm warnings as the tail and kept no log, so the failing test names + are unknown. +- Standing order 6: no re-run. Pushed `43f34f0f4` and opened draft PR #1971. Told the architect, + with options: CI names the failures and I run those files alone; one re-run with a reporter; + or a CI-stands-in ruling. +- The branch changes nothing under `packages/`. Every change so far is in `apps/vscode`. + +### Phase 4 review, iteration 1 (2026-11-24) + +- Codex: REQUEST_CHANGES (3). Claude: APPROVE with 5 notes. Answers in + `1963-cockpit_hierarchy-iter1-rebuttals.md`. +- Architect ruling (option A) on dormant windows (guest mode, no Codev workspace). They keep #1144 + inertness: the Cockpit shows *Not connected to Tower* with the reason and *Open Folder*, and never + initialises the connection. This is a deviation from the spec's no-workspace criterion for that one + window type. The architect recorded it on #1963 and will raise it with the owner at the PR gate. + The spec is not edited. **The PR description and the review must state it.** New test: + `cockpit-dormant-1144.test.ts`, with no client, SSE, auto-start or fetch while the Cockpit is shown. +- Fixed in place: + - The badge now follows connection-state changes. **This also changes the existing Codev + button**: during an outage its badge clears instead of keeping the stale count. The PR must say + so ("existing views behave as before" is a criterion). + - `codev.autoConnect: false` no longer shows *Connecting…* forever. The Cockpit's connection mode + is now `auto`, `manual` or `none`. +- Claude's notes: + - `navigateTarget` throws a named error instead of a bare `!`. + - `entryOfRow` keeps its throw. That is my own Phase 3 decision, not an architect ruling; the + architect agrees (fail fast, no silent `[]`). + - An active workspace with an empty roster shows an empty chevron until Phase 7 adds the Decisions + entry. Leave it; don't fix it twice. +- The Phase 4 `porch done` before this used the architect's one-time main-32 tests skip (GitHub + green on `43f34f0f`; `bugfix-1267-launch-loop.test.ts` passed alone, 7/7). The skip was removed + straight afterwards and is noted on PR #1971. + +### Phase 4 review, iteration 2 (2026-11-24): both APPROVE + +- Before the reviews, the iteration-2 `porch done` passed build (15.2 s) and the full local tests + (49.5 s) with no skip, starting at load 3.26. +- Codex APPROVE, no issues. Claude APPROVE. It verified the iteration-1 fixes against + `connection-manager.ts` and `ide-mode.ts` itself, and left non-blocking notes, carried into Phase 5: + 1. **Agent cycle in a Cockpit-only window (decide in Phase 5).** The cycle roster comes from + `buildersProvider.agentCycleOrder()`, which follows `codev.buildersGroupBy`. With the default + `stage` it holds builders only, so Cmd-cycling never lands on an architect, and its order is not + the Cockpit's top-to-bottom order. No Phase 4 criterion is broken: selection does act on Cockpit + rows. Raised with the architect. + 2. **Polish, at the start of Phase 5.** In `cockpit-provider.test.ts`, the parity `shape()` + compares `iconPath`, but the Cockpit deliberately overrides a waiting architect's icon + (`applyArchitectAttention`). Exclude `icon` for `BuilderGroupTreeItem`, as `description` already + is, or comment the fixture, so a future waiting-architect fixture doesn't read as a regression. + 3. **Polish, at the start of Phase 5.** `pruneTrees` runs only from `towerChildren()`, so departed + workspaces' builders survive while the Tower root is collapsed. That is bounded and harmless; + say so in its doc comment. + +### Architect ruling for Phase 5: agent cycle (2026-11-24T08:59Z) + +- **Option (b).** The approved spec already says "tree behaviours follow the view a row is in", so + this needs no owner ruling. +- **Cockpit visible, Agents view not:** the agent cycle runs in the Cockpit's own visible order, + architects and their builders. The roster is **this window's workspace only**; other workspaces' + rows never enter the cycle. +- **Agents view visible, or neither visible:** the existing order from + `buildersProvider.agentCycleOrder()` applies **unchanged**. Not (c): existing behaviour must not + move. +- **To do in Phase 5:** + - tests for all three cases (Cockpit-only visible, Agents visible, neither visible); + - one line in the PR #1971 description. +- Also opening Phase 5, from Claude's iteration-2 notes (see above): + - the parity `shape()` icon boundary; + - the `pruneTrees` doc comment. + +### Phase 5 (`cockpit_actions`), 2026-11-24 + +**Commits.** Three, not the plan's two: +- 5a `43946ed6c`: menus, workspace-row context values, held worktree config, agent cycle; +- 5b-1 `aaefbfd0f`: the menu-parity oracle, the parity test and the handler-argument test; +- 5b-2: the Spawn Builder cwd fix, the harness's rendered verification, docs and evidence. + +**Builder decisions (mine, not the architect's):** +- **Agent cycle, ruling (b).** `agentCycleRoster` follows the Cockpit only while the Cockpit is + visible, Agents is not, *and the Cockpit has acting rows*. The last condition is my reading of + "this window's workspace only". A Cockpit with no acting rows, in a builder-worktree window or + before Tower lists this workspace, falls back to the Agents order, so existing behaviour does not + move there either. +- **Command-argument helpers moved** from `extension.ts` to `commands/command-args.ts`, so the + handler-argument test can import them: `extractBuilderId`, `extractIssueId`, `extractIssueTitle`, + plus the new `architectNameFromArg`. `extractIssueId` now also checks that the id is a string. +- **Icons** added to `codev.spawnBuilder` (`$(rocket)`) and `codev.newShell` (`$(terminal-new)`), + because inline actions need one. Titles are unchanged. +- **`openDevUrl(urlArg?: unknown)`.** Only a non-empty string opens directly. Anything else, such + as the Cockpit row VS Code passes, falls through to the QuickPick. +- **Mutation checks:** 9 mutations of the parity test and 4 of the handler-args test, all caught. + +**Adjacent bug, fixed in place: Spawn Builder's cwd.** +- **How it was found.** The harness's `afx` stub recorded the Cockpit's Spawn Builder running + `afx spawn` in the harness's home directory. `spawnBuilder` passed no `cwd`, and `afx spawn` + resolves its workspace from its cwd. Every entry point was affected: the Workspace view, the + palette, the Backlog row and the Cockpit. +- **The impact.** In the Codev IDE the extension host's cwd is Tower's (`ide-server.ts` spawns the + server with `process.cwd()`), so a window could spawn into another project. +- **The fix.** It now runs in `detectWorkspacePath()`, this window's Tower workspace (the parent + workspace in a builder-worktree window), as Run Worktree Setup and Approve Gate already do. + Without a workspace it errors before prompting. Unit-tested. + +**Plan vs behaviour: Approve Gate.** +- The plan says it is verified as `porch approve` through the stubs. +- Since #1494 it relays to the spawning architect through `POST /api/send`. It runs `porch approve` + itself only when no architect is live. +- The harness asserts the relay: one `/api/send`, no porch call, the "sent … to main" note. + +**Harness: two temp-dir filters in Tower, both by design.** +1. `GET /api/workspaces` drops workspaces under `/tmp`, `/private/tmp` or Tower's `os.tmpdir()` + (`isTempDirectory`). The fixtures lived in the scratchpad under `/private/tmp`, so the fleet + rendered *No workspaces registered*. + - **Fix:** the fixtures now live in a `mkdtemp` `cockpit-fixtures-*` dir under the real + per-user temp dir, and the isolated Tower gets its own `TMPDIR` in the scratchpad. Gate 6 + also asserts the fleet listing. + - The architect accepted this on one condition, implemented with 7 self-test cases: `stop` + deletes that dir only after the realpath, parent, name and per-run marker-token checks pass. +2. Startup reconciliation skips and kills sessions of workspaces under `POSIX_TEMP_ROOTS`, which + include `/var/folders`. So fixture sessions do not survive a restart of the isolated Tower. + `reconnect` runs last, and checks the Cockpit's states and recovery, not session survival. + +**Harness lessons (each one cost a rerun):** +- **VS Code keeps a closed window's extension host alive** for its reconnection grace period, and + those hosts kept polling the isolated Tower. They inflated the first request counts about + fourfold. `vscode-restart` gives each measured layout a fresh server. +- **The first "alone" layouts were not alone.** The close commands' palette titles did not exist + in this VS Code, and `.catch(() => {})` hid it, so the Tower side bar and the Codev panel stayed + open. Now `runCommand` matches exact labels and throws, parts are toggled only when needed, and + every layout asserts the side bar, secondary side bar and panel before measuring. +- **VS Code drops a context-menu click that lands just after the menu opens.** Measured: at once, + dropped; after 500 ms, it runs. That one dropped click left a menu open that blocked every later + check. `contextAction` now waits and asserts the menu closed. A failed check presses Escape so + it cannot cascade. +- **A burst window that holds a fleet poll tick** counts one fan-out more or less, depending on the + poll's phase. The burst now starts 2 s after a tick and lasts 15 s. + +**Rendered results (isolated harness, VS Code 1.147.0 serve-web, fresh `fleet` seed):** +- `render` 5/5: the button directly below Codev; the Codev container unchanged against + `origin/main`; the hierarchy with N=2/1/0 builders across three workspaces; Dormant (1); dark, + then a live switch to light. +- `reveal` 1/1: the diff of #101's `alpha.ts` reveals its row, with the workspace and architect + rows collapsed beforehand. +- `windows` 3/3: + - the worktree window's parent row offers only Open Web Interface, Start Dev (this workspace) and + Open Dev URL; + - the no-workspace tooltip; + - Cockpit-only freshness: #102's gate shown after 56.3 s, against the 60 s default. +- `requests` 4/4, spec scenario 21: + - over a 60 s idle window, the three layouts make identical fleet and overview counts; + - Cockpit alone ⊆ source views alone; + - both at once add only `getWorktreeConfig` (3 vs 2 in the burst); + - none while idle; + - one event stream per window. +- `reconnect` 3/3: content kept with Tower down; a fresh window reads *Not connected to Tower*; + Reconnect restores it. +- `actions` 27/27: + - every builder context action, with the Agents/Cockpit menu parity; + - Approve Gate inline only on the blocked row, relayed to `main`; + - every workspace-row action, including Spawn Builder in alpha's cwd and Open Dev URL picking + Admin; + - Remove Architect: + - offered on siblings only; + - a childless sibling's row goes; + - WEB keeps its header as #103's owner (the Agents rule, "no builder is ever dropped"); + - other workspaces navigate to their windows; + - Open and Deactivate. +- **Totals: 43 checks, 0 failed.** `actions` ran on a fresh seed after the five others, which share one + seed. Each needs its own seed because it mutates state: it removes architects and deactivates gamma. + +Evidence: `codev/projects/1963-vscode-alternative-layout-seco/verification-increment1/`. + +### Architect on Phase 5 (2026-11-24T11:01Z) + +All four points were accepted: +1. **The Spawn Builder cwd fix stays in this PR.** The architect confirmed that main's + `runAfxCommand` passes no cwd, and will flag to the owner that the bug is live on main until + this merges. +2. **The agent-cycle reading is right,** including the worktree window keeping the Agents order. +3. **Asserting the #1494 relay over the plan's `porch approve` wording is right.** Say so in the + review. +4. **The render screenshots read well** in light and dark. + +**Carried to Phase 7:** the increment-2 screenshots must show the Decisions entry under every +active workspace, including one with no decisions file. + +### Phase 5 review, iteration 1 (2026-11-24) + +**Verdicts:** Codex APPROVE (no issues); Claude APPROVE (four non-blocking notes). Responses are in +`1963-cockpit_actions-iter1-rebuttals.md`. + +**Fixed:** +- The parity guard's source-view filter is no longer anchored to the start of the `when` clause. +- New test: the hidden palette entry for `codev.cockpit.openWebInterface`. + +**Kept, as planned:** +- The root listing awaits the held worktree config. The fetch cannot reject: the SDK returns + `null`, with a 10 s timeout. +- *Remove Architect* stays on an owner-only row (the plan's accepted divergence; invoking it fails + visibly). + +**Candidate refinements for the review doc:** +- A row whose architect is not in the overview roster gets its own context value, with no *Remove + Architect*. +- A config fetch that fails while connected holds `null` until the next drop signal. + +### Phase 6: workspace_views_package (2026-11-24) + +**Shape:** new private package `@cluesmith/codev-workspace-views` (`packages/workspace-views`), +source-exported (`.` → `src/index.ts`, `./styles.css`), no build step. It holds the Work view (with +BuilderCard, NeedsAttention, Backlog, RecentlyClosed), the Decisions view, `useDecisions` and the +issue-key grammar. The dashboard keeps thin wrappers with the same names and props, so `App.tsx` is +unchanged. + +**Host contract (`host.ts`), builder decisions:** +- `WorkViewHost.overview` is a value (`OverviewState | null`), not a subscription: each host owns + its own polling. `null` is the loading gate, so the dashboard passes `null` until `useOverview` + has state, exactly as before. +- Every Work action is optional, and its control renders only when the host provides it (Open, + + Shell, Refresh, the spec/plan/review links). `openBuilder` takes the `OverviewBuilder`, not an + id, because the dashboard's tab lookup (`findBuilderTab`) needs `roleId` and `issueId`. +- The dashboard-only pieces are slots: `tip` (TipBanner), `openFilesShells`, and `filePanel` (a + render function given `{open, setOpen}`, so the root's `file-panel-open` class stays with Work). +- An optional `architectCount` prop keeps the dashboard counting registered architects for the + attribution badge. Without it the view counts the overview's live architects. +- Decisions: `read`, `rule`, `image(path, signal)` are required; `openExternal` and `showImage` + are optional. Without them a link or image click does nothing (it never navigates the page). + Work's own http(s) anchors stay native ``, as before. +- The decisions result types moved into the package (they are its contract); `apps/web/lib/api.ts` + re-exports them. + +**Deviations from the plan's host sketch (interface detail; the plan's intent holds):** +- Two host interfaces, `WorkViewHost` and `DecisionsViewHost`, not one `WorkspaceViewsHost` with + a nested `decisions`: each view takes only what it uses. +- `overview` is a value, not a subscribe/refresh source (above). `refresh` is still an action. +- `openBuilder(builder)`, not `openBuilder(id)`; `showImage({src, alt})`, not `showImage(src)`: + the dashboard's full-size page carries the image's alt, as before. +- `architectCount`: the plan says it comes from `OverviewData.architects`. The view does that by + default. The spec's Assumptions accept the live-architect count for **VS Code**, and scenario 20 + requires the dashboard unchanged, so the dashboard wrapper passes its `/api/state` count. + +**CSS:** the moved rules live in the package's `styles.css`, each colour and font a +`var(--codev-wv-*, )` token. The dashboard maps the chrome tokens to its own +vars in `:root`. The tip banner, file panel and PR-row rules stay in `apps/web/src/index.css`. + +**Tests:** the eight moved test files run in the package against fake hosts (same case counts; +the fetch- and `window.open`-level cases moved to a dashboard integration test, +`apps/web/__tests__/DecisionsView.dashboard-host.test.tsx`, which renders the real wrapper, host +and hook with only `fetch` and `window.open` faked). New package tests: import boundary, one +copy of each component, and the Work view against fake hosts (absent actions hide controls, slots +render only when passed). The package's `check-types` covers its tests, which flagged three old +fixtures missing required fields (`area`, `reviewRequests`, `isDraft`); fixed. + +**Environment note:** locally (Node 26) the apps/web suite fails 10 Terminal/VirtualKeyboard/toolbar +files with `localStorage ... getItem`, because Node's experimental `localStorage` global shadows +jsdom's. With `NODE_OPTIONS=--no-experimental-webstorage` all 37 files pass. CI runs Node 20. Not +caused by this branch: `getWebKey` is untouched. + +**Rendered proof (scenario 20):** the harness `dashboard` script, baseline run on the branch base's +build, then on this build with `COCKPIT_BASELINE`. Evidence in +`codev/projects/1963-vscode-alternative-layout-seco/verification-phase6/`. + +### Phase 6 review, iteration 1 (2026-11-24) + +**Verdicts:** Codex REQUEST_CHANGES (two issues); Claude APPROVE (five notes). Responses are in +`1963-workspace_views_package-iter1-rebuttals.md`. + +**Fixed:** +- **Host-owned links (Codex).** VS Code's webview script (`pre/index.html`, `handleInnerClick`) + opens any clicked anchor with an `href` through VS Code's own opener. It listens on the window, + in the bubble phase, and ignores `defaultPrevented`. Work's native issue/PR links would have + bypassed the host's http(s) allowlist, and Decisions' links would have opened twice. Now: + - `WorkViewHost.openExternal?` is new. With it, Work's four external links go to the host, with + default prevented and propagation stopped. + - Without it, they stay plain links, as in the dashboard, which does not pass it. + - Decisions' link clicks stop propagation too. +- **`color: white` (Codex):** two buttons now use `--codev-wv-on-accent`. A new + `styles-tokens.test.ts` forbids any literal colour or font outside a token. +- **`useDecisions` and `host.read` (Claude):** the view calls `host.read()` through the host (keeps + `this`), and the hook keeps the latest `read` in a ref, so a new function per render neither + restarts polling nor re-reads. +- The dashboard's artifact-open handler now catches and logs, like + Shell (parity bug, fixed in + place). Two cosmetic test fixes. + +**For Phase 7:** the VS Code host must pass `openExternal` to both views, with the allowlist +host-side. Pass the Decisions view a stable host object (it keys image loads on it). + +### Phase 6 review, iteration 2 (2026-11-24) + +**Verdicts:** Codex APPROVE (no issues); Claude APPROVE (no blocking issues). + +**Carried to Phase 7/8 (Claude's forward notes):** +- The VS Code webview stylesheet must map **every** `--codev-wv-*` token. The dashboard maps 13 + and leaves the rest on defaults equal to its own values. Add a coverage test that extracts the + token names from `styles.css` and asserts the VS Code stylesheet maps each one, the same shape as + `styles-tokens.test.ts`. +- The webview hosts' tests must assert they provide `openExternal` (Work and Decisions) and + `showImage` (Decisions). Omitting `openExternal` silently reintroduces the link bypass. + +**Left as is:** +- The root's `work-view ` trailing space is parity with the pre-move code, and the snapshot + compares the class string. +- `one-copy.test.ts`'s `statSync` would throw on a dangling symlink: none exist under `apps/` or + `packages/`. + +### Phase 7: decisions_panel, implementation (2026-11-24) + +The Decisions panel in VS Code: the shared `DecisionsView` in an editor-area webview, with every +Tower call made by the extension host. Built: +- **SDK** (`tower-client.ts`): `getDecisions`, `ruleDecision`, `getDecisionImage`. A refusal stays + structured as `{code, message}` and is never flattened. Image bytes come through a new + `requestBinary`, which sets no Content-Type on the GET. +- **Host** (`apps/vscode/src/workspace-views/`): + - `messages.ts`: the requestId contract and guards for untrusted webview messages; + - `security.ts`: realpath + `path.relative` containment, and an http(s)-only allowlist; + - `panel-template.ts`: nonce CSP with no `connect-src`; + - `decisions-bridge.ts`: maps each Tower outcome to the view's result; + - `availability.ts`; + - `decisions-panel.ts`: single instance, serializer, and the visibility relay. +- **Webview** (`webview/`): `WebviewDecisionsHost` (postMessage, never rejects, image abort), + `DecisionsApp` (`isActive` = the relayed visibility, full-size image overlay), and + `vscode-theme.css` mapping all 28 `--codev-wv-*` tokens. +- **Cockpit:** a "Decisions" leaf after the architects under every active workspace. This window's + entry runs `codev.openDecisions`; any other entry (another workspace, a worktree window, a + no-workspace window) navigates via Open Workspace. + +**Builder decisions / deviations (mine, not the architect's):** +- `@cluesmith/codev-workspace-views/host` is a new subpath export. Host-side code imports the view + types from it, because the package index pulls in TSX, which the host tsconfig (no `jsx`) would + then compile. +- The no-I/O rule for webview code: an ESLint `no-restricted-globals/properties` rule on + `src/workspace-views/webview/**`, plus `workspace-views-webview-source.test.ts`, which is what CI + runs. The shared package has no ESLint; its existing `import-boundary.test.ts` already bans + fetch, XHR, WebSocket, EventSource and sendBeacon there. +- The panel opens in `ViewColumn.Active`. +- The "no decisions file" empty state appends the `afx decisions init` hint host-side, as plain + text after Tower's message. +- Vitest compiles TSX with `esbuild: { jsx: 'automatic' }`. Vite reads the host tsconfig.json, + which sets no `jsx`. +- `decisions-webview-bundle.test.ts` builds the real bundle from `esbuild.webview.cjs` and boots + it in its own JSDOM window, from a node-environment test, because esbuild refuses to run inside + vitest's jsdom environment (TextEncoder realm check). +- The Windows workflow's unit job gained a step that runs `workspace-views-security.test.ts` on + Windows. Its directory links are junctions, which need no privilege; a `win32`-only describe + covers drive-letter case and separators on real paths. + +### Phase 7: rendered verification (2026-11-24) + +New harness script, `verify decisions`: 15 checks, each run on its own `start` + `seed fleet`. +It adds `main-2` to alpha's file (an https image served by the browser's route, and an image +outside the workspace) and creates gamma's file. + +**Two bugs found and fixed:** +1. **Reload restore closed the panel** (run 1, 14/15). + - `deserializeWebviewPanel` asked `unavailableReason()`, which read + `connectionManager.getWorkspacePath()`. That is null until the async `initialize()` runs, and + a restore reaches the serializer first, so the restored panel was disposed as "no workspace". + - **Fix:** availability now comes from the window's folders, `detectWorkspacePath()`, the same + thing the CLI preflight already uses for the same reason. + - A source test in `contributes-cockpit.test.ts` pins it. +2. **High contrast hid accent text.** + - I had mapped `--codev-wv-accent` to VS Code's button background. HC Dark makes that black, and + the accent is also text and borders on the page (item ids, links, the selected option), so the + ids vanished on the black page. + - **Fix:** accent → `--vscode-textLink-foreground`, on-accent → `--vscode-editor-background`. + Contrast is symmetric, so text on an accent-filled button keeps the link's contrast. The + shared package is unchanged. + - The theme unit test pins the mapping. The rendered theme check now measures WCAG contrast: + item id on the page, and Submit's text on its fill, both ≥ 4.5 in all four themes (measured + 6.3 to 9). + +**Final run (cycle 3, the committed build): 15/15.** +Evidence: `codev/projects/1963-…/verification-phase7/`. +- Entries: a Decisions entry under alpha, beta and gamma (beta and gamma have no file), none under + dormant delta. Beta's entry opens beta's window. +- Alpha's entry opens one panel; a second click reveals the same panel. +- Images: + - the workspace SVG renders from a `blob:` URL, so **Uint8Array bytes survive + `webview.postMessage` in serve-web**; + - the https image renders; + - the outside image shows "Image not loaded", with Tower's reason. +- The full-size view opens; Escape and Close each close it. +- The link opens after VS Code's own "open external website?" prompt. +- Ruling `main-1`: the file is updated, the card shows the ruling, and Tower logs `Decisions notice + held (no-profile) → main @ alpha`. The notice is persisted to main's mailbox and held, because + the fixture architect is a bash shell, not an agent; the Codev panel shows "1 held". +- A stale fingerprint is refused ("Item main-2 changed since it was shown…"), with the draft and + word kept. +- Polling: 3 reads in 6 s while shown, 0 in 8 s while hidden, and reads resume when shown again. +- Four themes switched live: the webview never reloaded and the draft was kept. +- The panel is restored after a reload. +- Explanations show in a worktree window and a no-workspace window, and the worktree window's + entry navigates to the parent. +- Gamma: the empty state, then the real `afx decisions init` (it only writes the template; I + checked the CLI path: no Tower call), "0 open", then an added item appears. +- The audit: 205 browser requests, none to the Tower port, none carrying the key. Webview frames + loaded only extension resources and the remote item image. + +**Not run:** the `/ide/` (ide-server) mode. It serves the same VS Code web workbench and webview +code as serve-web. + +**Adjacent:** `.vscodeignore` now drops `**/tsconfig.*.json`. The vsix had been shipping +`tsconfig.webview.json` since the markdown preview added it. + +### Phase 7: review, iteration 1 (2026-11-24) + +`porch done` passed (build 17.6 s, tests 49.6 s, no skip). The 2-way review followed: Codex +REQUEST_CHANGES and Claude APPROVE, each with points that held up. + +**Codex: a refused http(s) image was a broken image, not "Image not loaded".** +- The spec requires the note for an http(s) image the browser refuses (mixed content, a Tower + URL's 401). The shared view only handled failures of host-loaded images, and my harness only + tested Tower's refusal. +- **Fix (in the shared package):** an error listener on every direct http(s) image, removed on + cleanup through the effect's abort signal. Package tests cover the refusal, and that a late + error on a detached image does nothing; that test fails without the signal. +- The harness now adds a remote image the route answers 404 for, and checks that its note is + rendered. +- **This changes the dashboard too:** a refused remote image there now shows the note instead of + a broken image, as the spec describes. No fixture of Phase 6's dashboard snapshot has a remote + image, so that comparison is unaffected. + +**Claude: the option words looked faint in Light High Contrast. They were invisible.** +- **Cause:** VS Code's webview stylesheet colours every `code` with its preformat foreground. + `.decisions-option-word` is a `code` that paints its own background but set no colour, so in + HC Light it drew near-white text on a light background. +- **Fix (in the package):** that rule sets `color: inherit`. It is a no-op in a browser, so the + dashboard is unchanged. +- **Wider check:** following Claude's "coverage is not contrast", the theme check now measures + every visible text element in the panel (62) in all four themes, against its composited + background. It fails below 3:1, requires 4.5:1 for the item id, Submit and the option word, + and lists every text under 4.5:1 in the evidence. That found three more mappings of mine that + were wrong for text: + - `fg-muted` → `disabledForeground`, a disabled-control colour that Light Modern draws at half + alpha: section labels measured 2.1:1. It is now `input.placeholderForeground`, VS Code's + readable muted grey. + - The error colour: VS Code's `errorForeground` is `#F85149` in Light Modern, and the refusal + measured 2.8:1. + - The waiting colour: `charts.yellow`, "Image not loaded" measured 2.9:1. + + The error and waiting colours now take `list.errorForeground` / `list.warningForeground`, + VS Code's colours for text. High-contrast themes leave those unset, so the fallbacks apply. + The tints follow the same colours. +- **Result:** every text is at least 4.1:1 in all four themes. Under 4.5:1, only in Light + Modern: the section labels at 4.3 (VS Code's own placeholder grey) and the Recommended badge + at 4.1 (`charts.green`), left as they are and recorded. +- **Not yet measured:** the Work view's status colours (implementing orange, the tags). That + panel is Phase 8, whose rendered check should run the same scan. + +**Claude's minor notes:** +- The ruling guard's `word`/`comment` are unbounded on purpose: Tower caps the body and refuses + an over-long comment with a reason the panel shows, whereas a host cap would drop it silently. + This is now said in the guard's comment. +- The "leak" on an aborted image is not one: once the resolver leaves `pending`, nothing + references the inner promise and it is collected. A comment now says so. +- The Windows run: dispatched and linked in the PR (run 45394199925). + +**Final harness run (cycle 7): 15/15.** Evidence in `verification-phase7/` is replaced by that +run. + +**Windows run on `36f7c4acd`:** the new path-containment step failed 4 of 39, all on the test side. +- **Three:** the test canonicalized its temp dir with the JS `realpathSync`, which on Windows keeps + the runner's 8.3 short name (`RUNNER~1`). The code uses `fs.promises.realpath`, the native one, + which gives the long name. The test now uses `realpathSync.native`. +- **One:** the "absolute path outside" case used `/etc/hosts`, which does not exist on Windows, so + `not-found` was correct. It now names the fixture's own outside file. +- The code under test is unchanged, and `resolveWorkspaceFile` has no production caller yet. +- The other suites, CLI tests, probes and install verification passed. The run is re-dispatched + after this commit. + +### Phase 7: review, iteration 2: approved (2026-11-24) + +- `porch done` (iteration 2) passed: build 15.4 s and tests 47.8 s, no skip, run once the load + was back under 6 (it spiked to 14.9). +- **Codex APPROVE:** both iteration-1 issues are addressed. +- **Claude APPROVE.** Two non-blocking notes, carried to Phase 8: + - the Light Modern Recommended badge is 4.1:1 at 10 px; give it a small bump if Phase 8 + touches badge styling; + - `resolveWorkspaceFile` gets its first caller in Phase 8. +- **Windows on `b758f8ffb`:** the containment step passes on Node 22 and 24, 39/39. Node 22 + passed everything. +- **Node 24 failed one test outside this branch's code:** `ide-server-stub.windows.test.ts` > + 'npm-style shim': "IDE server on port … was not stopped: the port query failed". + - This branch changes nothing in packages/codev except `issue-id-parity.test.ts`. The test + passed on Node 22 in the same run, and on main's run that morning. + - I re-ran only the failed job (attempt 2) to tell a flake from a failure. +- **Carried to Phase 8 (Work panel):** + - run the full-panel contrast scan on the Work view: implementing orange and the tag colours + are unmeasured; + - `resolveWorkspaceFile` gets its caller there. +- **Windows attempt 2 (Node 24):** `ide-server-stub` 'npm-style shim' passed. A different test + failed: `pir-1233-session-launch-loop.test.ts` > "resumes the spawn-pinned session after an + unnatural exit…" (start.sh command failed). It passed in attempt 1, and the same file failed on + spir-1940's Windows run. + - Both are pre-existing flakes in code this branch does not touch. They are left running, named + under "Flaky tests" in PR #1971, and reported to the architect. + - **The review file's `## Flaky Tests` section must carry both.** + +### Phase 8: Work panel (2026-11-24) + +- **Feature commit `d96d9c00b`.** `WorkPanels` (`workspace-views/work-panel.ts`): one retained + editor-area panel per window, restored after reload, pushing `OverviewCache` data and the + connection state. `workOverviewState` gives loading until the first overview, then the last + overview under "Not connected to Tower." while not connected. The mapped actions: + - Open → `openBuilderByRoleOrId(id, true)`, only for a builder the overview shows; + - + Shell → `codev.newShell`; + - Refresh → `client.refreshOverview()` (machine-wide POST) then `overviewCache.refresh()`; + - spec/plan/review → `resolveWorkspaceFile` (its first production caller) → `vscode.open`; + a refusal or a missing file warns the user, since they clicked; + - issue/PR links → `openExternal`, http(s) only. + + No dashboard slots are passed, so the dropped affordances are absent. +- **A builder decision, not a plan instruction:** `single-panel.ts` now holds what Work and + Decisions share (single instance, serializer, reveal, observable visibility, the session's + post-after-dispose drop and the http(s) gate). `DecisionsPanels` moved onto it. Its 13 tests + pass unchanged apart from an `EventEmitter` in the `vscode` mock. Phase 9's arrange needs + both panels to take a view column, so one place to add it. +- **Refresh gate:** `workPanels` is a `GatedView`. An existing source-text test + (`cockpit-wiring.test.ts`) pinned the gate's view list and was updated to include it (the + spec allows that for wiring tests when the guarded behaviour is unchanged). +- **Verified:** apps/vscode 130 files / 1764 tests, `tsc` host + webview clean, lint only the 2 + existing `curly` warnings. +- **Harness:** a `verify work` script (scenarios 17, 18, 19 Tower-down part, 22, reload + restore, the unavailable windows, and an increment-2 shot of the Cockpit's Decisions entries + beside both panels). Implementing orange (only `.attention-kind--dev`, a PIR gate the fixture + has no builder for) and the spike tag are measured by drawing a probe element in the real + webview; project and bug tags are in the fixture's rows. +- **What rendering found (fixed in `f03eade1b`).** The first `verify work` run passed 12 of 14: + - Light Modern's chart orange (implementing, a PIR dev-approval row) measured 2.9:1 as + text. `--codev-wv-status-implementing` is now mixed 50/50 from the error and waiting text + colours (VS Code's list colours, made to be read): it stays between red and yellow, as the + dashboard's gate progression has it, and measured 6.7:1 on Dark Modern. + - The Tower-down check expected the fixture's 3 builders back after the restart. A restarted + Tower does not keep fixture sessions (harness README), so the check now compares with + the restarted Tower's own overview. + - The increment-2 shot showed Work broken in a half-width group (~470 px): every *Open* cut + off, backlog reviewer/assignee labels over the spec/plan links. VS Code-only container + queries in `vscode-theme.css` now drop Elapsed and the labels under 760 px, and Progress + under 600 px; row labels clip. The dashboard's layout is untouched. The side-by-side check + now fails on sideways scroll, a cut *Open*, or a label over its links. + - Scenario 19 says *both* panels keep their content under a not-connected notice; the check + covered only Work. It now also holds Decisions to its cards under "Not connected to Tower. + Showing the last version read." and to the notice clearing on recovery. It passed first time. +- **A test race of my own:** the four real-filesystem containment tests in `work-panel.test.ts` + waited one `setTimeout(0)` for `fs.promises.realpath`; two failed under the loaded full suite + (harness running alongside) and passed alone. They now `vi.waitFor` the outcome. Not a + pre-existing flake, so not named as one. +- **One more from looking at the shots (`b9e5af0f6`):** in Light Modern the progress bar's + track vanished (its tertiary background is the row's own colour there), so a bar read as a + dash. VS Code's stylesheet now draws the track as an 18% mix of the text colour, and the + theme check fails if a track does not show on its row (≥ 1.2:1), reporting the fill's + contrast on it. +- **Architect review of the increment-2 shots (13:47Z), all taken (`b3aa8873b`):** + 1. *(change)* Decisions' no-file state was the amber `.decisions-notice` — a warning look + for an empty state. The shared view now gives it a `decisions-notice--no-file` modifier; + VS Code draws it in `descriptionForeground` on no fill. The dashboard has no rule for the + modifier, so it keeps the amber. Scenario 16 now measures it (rgb(59,59,59), the + description colour, on no fill, in Light Modern). + 2. Work's State wrapped to three lines in the half-width group: under 600 px the state now + stays on one line and the title gives way (it ellipsizes); only under 400 px does the state + wrap. The half-width check holds each state to one line. + 3. Panel text read larger than the workbench: every `font-size` in the shared stylesheet is now + a `--codev-wv-font-size-{xxl..xxs}` token whose default is the dashboard's px size; VS Code + maps xl/lg to `--vscode-font-size` and the smaller steps 1–3px below it, headings +4px. + Both headings share one size. `styles-tokens.test.ts` fails on a literal px font size. + 4. A "More Actions…" tooltip covered work-09/10: `R.shot` now parks the pointer on the title + bar and waits for hover tooltips to close, for every script's shots. + Re-rendered at b3aa8873: verify work 14/14, verify decisions 15/15. +- **apps/web locally:** 10 terminal/toolbar test files fail on this machine with `localStorage` + undefined in `getWebKey` (Node 26's global `localStorage` shadows jsdom's); CI runs Node 20. + None of them touch the shared views; the 27 other files, including the dashboard's Work and + Decisions, pass. An environment issue, not a flake. +- **The dashboard keeps its look (scenario 20, proven):** `verify dashboard` on the pre-change + build (b9e5af0f's apps/web) kept a snapshot; after rebuilding `packages/codev` with the type + scale, `verify dashboard` with `COCKPIT_BASELINE` found all 138 Work and 83 Decisions elements + identical in computed style and DOM. Evidence in `verification-phase8/dashboard/`. +- **Review round, iteration 1 (`695870167`).** Codex REQUEST_CHANGES, claude APPROVE; responses in + `1963-work_panel-iter1-rebuttals.md`. + - *Codex:* before any overview, the not-connected notice sat over "No active builders" etc., + claiming an empty workspace. With an error and no overview, `WorkView` now shows *Loading...* + in each section. This also fixes the dashboard's failed-first-read case (same misleading + empty sections; adjacent bug, named in the PR). A first read in flight keeps the + dashboard's empty sections as before. + - *Claude (nits taken):* a rejected `onMessage` is logged at the dispatch site, for both + panels. An artifact refusal that lands after close shows no toast. + - *Architect (14:00Z), correcting suggestion 2:* one-line state had cut titles to four + characters at half width. Under 600 px a builder row is now a two-line grid: issue, title + and Open, then the state under the title. The check requires 20+ characters of a typical + 44-character title; it shows 42 at 473 px. + - Rendered at 69587016: work 14/14, decisions 15/15, dashboard 6/6 (138 + 83 elements identical + to the pre-change snapshot). +- **Iteration 2: codex APPROVE, claude APPROVE.** I took claude's one actionable nit: the + `work-section-loading` class had no rule anywhere, so it is dropped (no rendering change). It + left two notes for the owner: the "Failed to load overview:" wording before any load (the + dashboard's template), and the two Light Modern texts at 4.3:1. Both go in the PR body. +- **Phase 8 closed (`abeff3c7e`); porch advanced to `arrange_cockpit`.** The PR #1971 body has a + Phase 8 section, including the adjacent dashboard fix and the owner notes. apps/web passes 37/459 + with `NODE_OPTIONS=--no-experimental-webstorage`, the known Node 26 workaround already in the PR + body, so the earlier local failures were only that. +- **Process note:** porch's `arrange_cockpit` refresh boundary was recorded as acknowledged when I + called `porch next` a second time, before I had refreshed. I am running the builder-refresh + procedure now, at that boundary, before starting Phase 9. + +## Phase 9: arrange_cockpit (2026-11-24) + +- **What it is.** *Codev: Arrange Cockpit* (`codev.cockpit.arrange`, palette and the Cockpit's + title bar) arranges the editor area as `main` | (Work over Decisions). The first Cockpit show in a + window does it automatically (`codev.cockpit.autoArrange`, default on). The first automatic one + shows a one-time notice whose *Don't arrange automatically* turns the setting off at the user + level. Not offered in builder-worktree or no-workspace windows (the command says why, and the + title-bar entry is hidden). +- **How (`cockpit/arrange.ts`).** On the layout spike: place the architect in group 1, Work in 2, + Decisions in 3 *before* `vscode.setEditorLayout`. Moving a group's only editor closes the group + and renumbers the rest, so this order matters. With no architect and only the panels in group 1, + an empty left group is opened first. Every move is awaited against the tab model with a 5 s bound; + a move that does not happen stops the arrange with an error naming it. The architect resolves + through `openResolvedArchitect` (main only, #1497 warning). `terminalPosition: panel` is + overridden for this path only (a `position` argument to `openArchitect`). +- **Auto-arrange (`cockpit/auto-arrange.ts`)** waits for the window's first connection attempt + (`ready()` in `initialize()`'s `finally`), so a reload with the Cockpit showing can resolve the + architect. +- **What rendering found, fixed here:** + 1. *Preview tabs.* `WebviewPanel.reveal(column)` into another group lands the panel there as a + **preview** tab (1.147.0's `revealWebview` does not pin; `createWebviewPanel` does). The next + file opened in that group would replace it, closing the panel and its draft. Arrange now keeps + a panel left as a preview (`workbench.action.keepEditor`, the panel focused and confirmed + first), before the architect takes focus. + 2. *A second Work panel after a reload.* VS Code revives a restored webview only when its tab is + shown, so `show()` with no live panel created a second one beside the restored tab. That was + Phase 7/8 code; arrange made it routine. `show()` now opens the live panel in the restored + tab's group (or the placement) and closes the restored tab after it. + `TabInputWebview.viewType` carries the internal `mainThreadWebview-` prefix. +- **Adjacent changes:** the availability text says "Use it from the parent workspace's window" + (it read wrong for a command); `readArchitectRoster` is shared by *Open Architect* and arrange; + the menu-parity oracle has a fifth record kind for the Cockpit's own entries. +- **Harness:** `verify arrange` (scenarios 7, 9, 13, 14, 19). `profile-seed` / `profile-existing` + cover the spec's existing-profile risk: `COCKPIT_PRE_COCKPIT=1 vscode-restart` strips the Cockpit + container from the install (checked against origin/main's package.json), a new browser profile + uses Codev on it, then the branch's install loads that profile. +- **Rendered (isolated harness, VS Code 1.147.0 serve-web):** `verify arrange` 15/15, + `profile-seed` 1/1, `profile-existing` 1/1; evidence in `verification-phase9/`. Work at the + split's width is 473 px; a typical 44-character title shows 42 characters (architect's 14:00Z + ruling: 20+). On a profile that used Codev before the Cockpit existed, VS Code places the Cockpit + button directly below Codev, as on a fresh profile, so the PR needs no activity-bar caveat. +- **Harness findings on 1.147.0** (verify script only, not product): `settings.json` opens in a + modal editor that takes clicks and F1; a tab's aria-label keeps ", preview" after the tab is + kept, so preview is read from the italic label; a terminal takes focus a moment after its tab is + clicked and would swallow the palette's typing; a reload right after a layout command can + restore the previous layout. +- **Phase 9 review, iteration 1:** codex REQUEST_CHANGES, claude APPROVE. + - Codex: the architect's tab is found by label, and names are not unique. Accepted. The tab API + gives a terminal tab no identity, and showing a panel terminal leaves the active editor tab as + it was, so activation tracking (codex's suggestion) cannot cover the panel case. + `Terminal.name` does follow renames (1.147.0's `$acceptTerminalTitleChange` sets it), so arrange + now refuses, before moving an editor, when another terminal has the architect's name. + - Claude note 1: the automatic arrange with Tower down showed an error toast nobody asked for. It + now reads the roster quietly and logs. Note 2: the empty-left-group branch is named in the PR + as unit-tested only. Note 4 (25 ms polling): kept. +- **Phase 9 review, iteration 2:** codex APPROVE, claude APPROVE with two non-blocking findings. + Both were real and are fixed in place after the approvals, so the PR review is the first to see + them. Each new test fails on the previous `arrange.ts`. + - A namesake terminal still being closed (the stale-session path disposes and reopens under the + same name; 1.147.0 drops it from `window.terminals` only on `$acceptTerminalClosed`) is now + waited out within the settle bound before arrange refuses. + - `keepLeftColumn` counts the Cockpit's *tabs* (live or restored), not live panels. A restored, + unrevived Work tab alone in group 1 used to let group 1 close and time the arrange out. + - Disputed, with the 1.147.0 bundle as evidence: a column beyond the last group opens every + missing group up to it (under 9), so the fake's `groupAt()` is right. + +## 2026-11-24, review phase (after the context refresh) + +- **Architect (15:35Z):** re-run `verify arrange` on the final head before the PR gate; the PR + should not say "unit-tested only" for arrange fixes the harness can render. There is a standing OK + for runs of the same harness. +- **New rendered checks in `verify arrange`:** + - the namesake refusal, and arranging once that terminal is closed; + - a reload with Tower down and the Cockpit showing: automatic arrange, no error toast; + - a restored, never-shown panel tab: *Arrange Cockpit* keeps an empty left column. + + The last two began as one check. It failed three runs, because VS Code 1.147.0 reopens its + Welcome page on a reload even with "show on startup" unticked. I read the bundle: it comes from + the startup editor and from walkthroughs. Split in two, the restored-tab check closes the Welcome + page and then runs the command, with the Cockpit hidden so nothing arranges first. + + A scenario 13 setup flake (keys typed before the editor took focus) now waits for the tab to turn + dirty. +- **Screenshot privacy:** + - **Found:** the panel shell's prompt `host:dir user$` showed in 12 committed shots. It is + macOS's `/etc/bashrc` prompt; the harness HOME had no profile. + - **Ruled (architect, 16:09Z):** option B. `start` writes `PS1='$ '` into the harness HOME, and + every `verify` run ends with an OCR check (`tesseract`) that fails on such a prompt. It flagged + exactly those 12 of the 110 committed shots. + - **Replaced:** the ten `verification-increment1` actions/reconnect shots, by final-code runs. + - **Not done:** no history rewrite. That is the owner's call, and the architect has told them. +- **PR consultation, iteration 1:** codex REQUEST_CHANGES, claude APPROVE. + - The architect's rulings (16:39Z): + - **Electron suite = A.** It is pre-existing and untouched, no workflow runs it, and #1765 + says it cannot launch recent VS Code on macOS. The vitest suite meets the criterion. + - **Merge main:** a merge commit, no rebase. + - **Claude's three code points:** fixed in place. + - **Dormant rebuttal:** agreed. + - **Evidence out of the tree.** + - Fixed in `69aa91e3d`: + - the Decisions bridge no longer forwards a raw transport error, which can name Tower's port; + - arrange throws when there is no terminal manager; + - `SingleWebviewPanel.dispose()` drops the panel's listeners. + - Merge commit `f331978a7`: main at 3.3.8. CHANGELOG and lessons-learned conflicts kept both + sides. + - After the merge, apps/vscode has 1820 tests passing, with 1 skip. The one failure was a + wiring source test that pinned the old optional call; it was updated in `98a7c2c17`. +- **Evidence branch:** + - `evidence/spir-1963` is an orphan commit `1d5cc1e40`, built with plumbing from HEAD's blobs + (temp index, `commit-tree`; no checkout or worktree) and pushed. + - The PR branch drops the five `verification-*/` folders and the six spike PNGs. It gains + `verification.md`, generated from the results JSON: 127/127 checks, with SHA permalinks. + - From here, no evidence binaries go to `builder/spir-1963`. The final `verify arrange` goes + only to the evidence branch. +- **Integration review (16:58Z): asks 2-4 and the confirmations**, at `20d2ce91f`: + - the `isPanelTab` canary; + - the CHANGELOG badge line; + - the WorkView dashboard-host test; + - the CI syntax check of the harness; + - the review's Owner Decisions section. +- **Tripwire incident (ask 1, 1.138.0 via ide-server mode):** + - **What happened.** The harness wrote `codev.towerPort` under `--user-data-dir`. A VS Code + server ignores that flag and reads `/data/Machine/settings.json`, so the + extension host used port 4100, the owner's Tower. + - **What the owner's Tower log shows** (read by the architect, not me): + - requests from 16:56:19Z to 17:21:05Z, 25 minutes, about 9,100 in all, every one a 401; + - GET `/api/overview`, `/api/events`, `/api/worktree-config`, `/api/activity-hooks` and + `/workspace//api/state`, plus about 1,500 POST `/api/workspace//activate`; + - nothing read or changed, no fixture workspace registered, and the same 12 active workspaces. + - **Why it lasted 25 minutes.** The tripwire detected the connection at 16:56:20Z, wrote its marker + and exited. The run went on until the verify script finished, and only then did teardown kill + the extension host. My first report implied it had stopped at detection; it had not. + - **Ruled (architect, 17:24Z):** + - no ide-server run, 1.138 or 1.128, until the owner says so; + - fix the harness now (the tripwire stops the run, the settings path, a prevention layer); + - serve-web resumes only after the tripwire fix and its self-test. + - **Fixed:** + - **The tripwire stops the run.** On a hit it writes its marker, then freezes and kills the + whole harness tree, then reports. It trusts a pid file only while that pid's command still + carries the file's markers. + - **Gate 5 confirms the server's settings path from its bundle** (`out/server-main.js`) and + refuses a server where that fails. The two real servers were checked read-only. + - **ide-server runs inside a `sandbox-exec` profile** that denies outbound TCP to :4100. A + launch canary on a throwaway port proves the profile applies. + - **Self-tests:** `selftest tripwire settings sandbox` passed 17/17, with no Tower and no IDE + server. The tripwire killed a stand-in tree, including a detached grandchild, in 463 ms. +- **Final head before the owner (17:45Z):** `c79b1c7e1`. + - `verify arrange` passed 19/19 on 1.147.0 serve-web. + - Windows run 45450646100 succeeded, and CI's 8 checks passed. + - **Evidence slip.** My glob put 11 stale `arrange-*` shots, five of them showing the host + prompt, into evidence commit `af31122e6`. Corrective commit: `871ed5a5e`. Evidence files are + now picked by the names in the run's JSON. +- **Owner rulings at the PR gate (relayed 18:19Z; the gate is NOT approved):** + - **Accepted as built:** the dormant window, the "Failed to load overview" wording, and the + Light Modern 4.3:1 texts. The spec's no-workspace criterion and its footprint lines now state + the dormant behaviour. + - **History scrub approved by the owner.** It follows the architect's procedure: + - the evidence branch is rewound to `a749cdd67`, with one clean commit on top; + - a backup bundle of both tips is kept, local only; + - `builder/spir-1963` is rewritten in a fresh clone, removing only the evidence paths; + - every check passes before `--force-with-lease`; + - the worktree moves onto the new history with `reset --soft`. +- **Test-then-merge (owner ruling ide-2, relayed 20:51Z; the pr gate is NOT approved):** one + fenced ide-server run on 1.138.0, then one on 1.128. Merge only if both pass and checks are + green. + - Waited for PR #1957 (named architects), which merged at 21:18Z. Merged `origin/main` + (`707e0e904`) as `b164e4898`. The one conflict, the codev-types import in + `packages/sdk/src/tower-client.ts`, was resolved as the union. The types and sdk build clean. + - `porch done` (plain, main-39) at 21:20Z, load 13.6: passed. At the review phase it runs + `pr_exists` and the two review-section checks, and `e2e_tests` is skipped by the repo config. + There is no tests check in this phase, so no local suite ran. + - The isolated Tower (`packages/codev` dist) and the vsix were rebuilt from `b164e4898`. + - Each version runs `verify arrange`, `work` and `decisions`, each on its own `start` and + `seed fleet`. Every start has the sandbox, its canary and the tripwire, and the run stops at + the first failure or trip. + - **1.138.0, 21:21Z: FAILED, and stopped as ordered.** `arrange` passed 14/19. All 5 failures + are the Work and Decisions webviews staying blank; every layout behaviour passed. + - The server reported commit `50cad256`, and the tripwire stayed clean. + - Load: 14.9 at the start, 11.5 at the failure, 32.1 at the end (the Tower rebuild). + - `work`, `decisions` and 1.128 were not run. + - **Cause (read-only diagnosis): a webview-protocol mismatch in Codev IDE 1.138's + `product.json`.** Its `webviewContentExternalBaseUrlTemplate` is pinned to an older insider + build's host page (`ef65ac1b`), instead of `{{quality}}/{{commit}}`. + - The 1.138 workbench sends webview resources as a transferred stream, or as chunk messages. + - That host page and its service worker read only `data.data`. + - So the panel HTML arrives (the host page fetched `fake.html`), but its scripts never do. + - The same blank panels appeared in the 16:56Z incident run, before the sandbox and before + the merge. + - Reported to the architect by 21:30Z. No new launch without their word. + - **Diagnostic, authorised 21:31Z.** `verify webviews` (harness-only commit `8cad56b2d`). + - 1.147 serve-web baseline: 6/6. The built-in Markdown preview, the Codev contextual panel, the + Codev Markdown preview and Work all render. + - 1.138.0: all four are blank, VS Code's own Markdown preview included. Every webview + resource stays pending. + - All 28 page errors are `DataCloneError: ... A ReadableStream could not be cloned because it + was not transferred`, thrown at line 447 of the CDN host page (`ef65ac1b`). + - So the defect is product-wide, in the Codev IDE 1.138 packaging, not in this PR. + - **1.128.0, 21:42Z: `arrange` 16/19, stopped as ordered.** Webviews render on 1.128, and + every Cockpit step on the first profile passed. + - The 3 failures are on the extra fresh browser profiles. 1.128 opens its Workspace Trust + editor as a modal (`workbench.editor.useModal` defaults to `some`), and the harness does not + close it, so it intercepts the Cockpit click. + - Load was 13.4 at the start, 23.1 at the first failure and 17.7 at the end. The tripwire + stayed clean. + - Reported 21:48Z. A harness-only fix and a 1.128 rerun await the architect's word. + - **1.128 rerun with the trust fix (`10f4d9cce`), pre-change build: `arrange` 19/19, `work` 15/15, + `decisions` 8/16.** + - The `decisions` failures are the harness's: `activeEditorTab()` read the first `.tab.active` in + the page. Since Phase 9 the window is arranged into three groups (`codev.cockpit.autoArrange` + defaults to true), so that tab was the left group's. + - The panel rendered. The `decisions` script had not run since Phase 8 on any version: my gap. + - The architect approved the helper fix (the active group's active tab), and widened step d: + every verify script, on the final head, on 1.147 serve-web. + - **Owner ruling ide-3 (21:54Z), "workaround".** Work and Decisions carry their bundle inline, on + every version. The ruling's order: + - merge main; + - make the change and run the unit tests; + - push, and send the architect the commit range; + - only after the architect's word: 1.147 baseline (every script), fenced 1.138, fenced 1.128. + - **What I found while building it:** + - The panel style policy was `${cspSource} 'unsafe-inline'`, not nonce-only as the ruling + assumed. I built nonce-only as ordered. + - Measured in Chromium: + - React `style` props still apply, through the CSSOM; + - a `style` attribute parsed from markup is refused, so a decision item's aligned table + columns and raw-HTML inline styles lose those styles; + - VS Code's default styles and API script sit before our CSP meta, so the policy does not + apply to them. + - The bundles fetch nothing else: no `url()`, `@import`, fonts, dynamic `import()` or + workers. Dev source maps are now inline. + - Both bundles hold `