From 5c3664b34c9a15a9f497ea2f99c42eb68e1d5898 Mon Sep 17 00:00:00 2001 From: Ashot Petrosian Date: Sat, 28 Nov 2026 20:23:39 -0500 Subject: [PATCH 01/71] feat(web): codecast multi-platform build --- docs/architecture/code-editor.md | 151 +++- .../__fixtures__/install-golden/stub/check.md | 10 +- packages/cli/src/blame.test.ts | 7 + packages/cli/src/blame.ts | 27 +- packages/cli/src/browser/cloudHost.test.ts | 20 +- packages/cli/src/browser/sharedHost.test.ts | 2 +- packages/cli/src/ciPoolHost.test.ts | 154 +++++ packages/cli/src/ciRun/command.ts | 312 +++++++++ packages/cli/src/ciRun/executor.ts | 441 ++++++++++++ packages/cli/src/ciRun/run.test.ts | 235 +++++++ packages/cli/src/ciRun/run.ts | 652 ++++++++++++++++++ packages/cli/src/code/codeBlame.ts | 2 + packages/cli/src/hostWorkTicks.ts | 29 + packages/cli/src/momentsHost.test.ts | 34 +- packages/cli/src/momentsHost.ts | 19 +- .../cli/src/terminal/terminalServer.test.ts | 6 + packages/cli/src/terminal/terminalServer.ts | 17 +- packages/cli/src/test-helpers/loopHold.ts | 8 + packages/cli/src/vault/vaultServer.test.ts | 4 + packages/cli/src/vault/vaultServer.ts | 4 + packages/convex/convex/_generated/api.d.ts | 22 + packages/convex/convex/accountPool.test.ts | 15 + .../convex/changeApprovals.landing.test.ts | 212 ++++++ .../convex/convex/changeApprovals.test.ts | 18 +- packages/convex/convex/changeApprovals.ts | 399 +++++------ packages/convex/convex/ciPool.test.ts | 182 +++++ packages/convex/convex/githubWebhooks.ts | 10 +- packages/convex/convex/http.ts | 7 +- .../convex/convex/lib/changeApprovalReads.ts | 219 ++++++ .../lib/changeApprovalRecordValidator.ts | 31 + packages/convex/convex/lib/ciRoutes.ts | 14 + packages/convex/convex/lib/deletionPlans.ts | 2 + packages/convex/convex/schema.ts | 46 +- packages/convex/convex/users.ts | 45 +- packages/electron/installedApps/e2e/run.mjs | 34 +- packages/mobile/app/session/[id].tsx | 36 +- packages/shared/blame/index.ts | 12 + packages/shared/blame/sessionTrailer.test.ts | 11 +- packages/shared/contracts/ciWorkflow.test.ts | 124 ++++ packages/shared/contracts/ciWorkflow.ts | 566 +++++++++++++++ packages/shared/contracts/codeProtocol.ts | 5 + packages/shared/contracts/shortcutCatalog.ts | 5 + .../blog/agents-in-your-own-chrome/page.tsx | 234 ------- .../blog/claude-code-cursor-codex/page.tsx | 237 ------- .../blog/claude-code-from-your-phone/page.tsx | 289 -------- .../claude-code-history-on-day-one/page.tsx | 189 ----- .../blog/claude-code-sessions/page.tsx | 217 ------ .../blog/codecast-in-the-cloud/page.tsx | 476 ------------- .../blog/fewer-bigger-jumps/page.tsx | 210 ------ .../one-repository-twenty-checkouts/page.tsx | 204 ------ .../blog/the-chart-in-the-reply/page.tsx | 229 ------ .../page.tsx | 232 ------- .../the-task-your-agent-reports-to/page.tsx | 193 ------ .../page.tsx | 271 -------- .../blog/undo-with-a-history/page.tsx | 226 ------ .../documentation/guides/content/decisions.md | 12 +- .../app/commit/[owner]/[repo]/[sha]/page.tsx | 9 +- packages/web/app/tasks/[id]/page.tsx | 7 +- packages/web/components/ConversationView.tsx | 68 +- packages/web/components/InlineDiff.tsx | 8 +- .../web/components/OpenInEditorButton.tsx | 5 +- packages/web/components/PaletteRows.tsx | 3 +- packages/web/components/PlanDetailPanel.tsx | 11 +- .../__tests__/collabComposerPresence.test.tsx | 19 +- .../__tests__/phoneCallStrip.mount.test.tsx | 5 +- packages/web/components/code/CodeEditor.tsx | 14 +- packages/web/components/code/CodeFileBar.tsx | 130 +++- packages/web/components/code/CodeFileView.tsx | 201 +++++- .../vaultFileViewRead.mount.test.tsx | 72 +- .../web/components/code/agent/AgentLayer.tsx | 76 +- .../components/code/agent/SessionPicker.tsx | 99 ++- .../__tests__/SessionPicker.mount.test.tsx | 31 +- .../components/code/blame/BlameHoverCard.tsx | 17 +- .../code/workspace/CodeWorkspace.tsx | 438 +++++++++--- .../components/code/workspace/EditorGroup.tsx | 93 ++- .../web/components/code/workspace/TabBar.tsx | 173 ++++- .../components/code/workspace/TabSwitcher.tsx | 33 +- .../conversation/blocks/toolBlocks.tsx | 25 +- packages/web/components/pr/PRThread.tsx | 4 + packages/web/components/repo/BlobContent.tsx | 23 +- .../components/repo/RepoCompareContent.tsx | 6 +- .../web/components/sidebar/navPrimitives.tsx | 5 +- .../web/components/stage/StageSplitView.tsx | 7 +- .../web/components/tasks/TaskInlineThread.tsx | 7 +- .../terminal/ConversationTerminal.tsx | 1 + .../web/components/vault/VaultFileView.tsx | 99 ++- .../web/components/vault/VaultScopeLine.tsx | 2 +- .../web/components/vault/useVaultSidePanel.ts | 9 +- .../__tests__/editorPaletteCommands.test.ts | 9 +- packages/web/lib/__tests__/filesPane.test.ts | 28 + .../web/lib/__tests__/inboxRouting.test.ts | 23 +- packages/web/lib/__tests__/stage.test.ts | 23 +- .../standaloneBootGraph.guard.test.ts | 57 +- packages/web/lib/castDiff.ts | 14 + .../web/lib/code/__tests__/buffers.test.ts | 25 + .../web/lib/code/__tests__/fileSync.test.ts | 152 +++- packages/web/lib/code/__tests__/merge.test.ts | 12 +- .../web/lib/code/__tests__/statusBar.test.ts | 22 +- .../__tests__/statusBarVault.mount.test.ts | 44 ++ packages/web/lib/code/__tests__/theme.test.ts | 24 +- .../agent/__tests__/editorMarks.mount.test.ts | 65 +- .../agent/__tests__/feature.mount.test.ts | 71 +- .../lib/code/agent/__tests__/sessions.test.ts | 48 +- packages/web/lib/code/agent/agentStore.ts | 31 + packages/web/lib/code/agent/editorMarks.ts | 161 ++++- packages/web/lib/code/agent/feature.ts | 144 +++- packages/web/lib/code/agent/live.ts | 4 +- packages/web/lib/code/agent/sessions.ts | 67 +- .../lib/code/blame/__tests__/actions.test.ts | 33 +- .../blame/__tests__/feature.mount.test.ts | 53 +- .../lib/code/blame/__tests__/model.test.ts | 13 +- packages/web/lib/code/blame/actions.ts | 17 +- packages/web/lib/code/blame/gutter.ts | 58 +- packages/web/lib/code/blame/index.ts | 13 +- packages/web/lib/code/blame/model.ts | 25 +- packages/web/lib/code/buffers.ts | 33 +- packages/web/lib/code/commands.ts | 39 +- packages/web/lib/code/editorHost.ts | 24 +- packages/web/lib/code/features.ts | 8 + packages/web/lib/code/fileSync.ts | 189 +++-- .../code/git/__tests__/feature.mount.test.ts | 42 +- .../code/git/__tests__/gutter.mount.test.ts | 47 ++ packages/web/lib/code/git/gitTheme.ts | 16 +- packages/web/lib/code/git/gutter.ts | 95 ++- packages/web/lib/code/git/index.ts | 78 ++- packages/web/lib/code/git/split.ts | 25 +- packages/web/lib/code/git/status.ts | 18 +- packages/web/lib/code/gutterSlots.ts | 19 +- packages/web/lib/code/idle.ts | 18 + packages/web/lib/code/languages.ts | 13 +- .../web/lib/code/lsp/__tests__/lsp.test.ts | 2 +- packages/web/lib/code/lsp/feature.ts | 32 +- packages/web/lib/code/lsp/host.ts | 12 +- packages/web/lib/code/lsp/navigation.ts | 141 +++- packages/web/lib/code/lsp/register.ts | 22 +- packages/web/lib/code/lsp/symbols.ts | 73 +- packages/web/lib/code/lsp/ui/list.ts | 10 + packages/web/lib/code/lsp/ui/peek.ts | 10 +- packages/web/lib/code/lsp/ui/quickPick.ts | 28 +- packages/web/lib/code/lsp/ui/status.ts | 20 +- packages/web/lib/code/lsp/ui/theme.ts | 12 +- packages/web/lib/code/merge.ts | 120 +++- .../code/search/__tests__/controller.test.ts | 14 + packages/web/lib/code/search/controller.ts | 13 +- packages/web/lib/code/search/multibuffer.ts | 9 +- packages/web/lib/code/setup.ts | 21 +- packages/web/lib/code/statusBar.ts | 152 +++- packages/web/lib/code/theme.ts | 317 ++++++--- .../web/lib/code/vim/__tests__/engine.test.ts | 162 +++++ packages/web/lib/code/vim/apply.ts | 4 + packages/web/lib/code/vim/exAdapters.ts | 138 ++-- packages/web/lib/code/vim/index.ts | 35 +- packages/web/lib/code/vim/keyLayer.ts | 17 +- packages/web/lib/code/vim/mode.ts | 14 +- packages/web/lib/code/vim/options.ts | 4 +- packages/web/lib/code/vim/plugins.ts | 43 +- packages/web/lib/code/vim/theme.ts | 24 +- packages/web/lib/code/vim/translate.ts | 58 +- packages/web/lib/code/vim/types.ts | 2 +- packages/web/lib/code/vimFeature.ts | 38 +- packages/web/lib/code/workspace/controller.ts | 10 +- .../web/lib/code/workspace/editorWorkspace.ts | 37 +- .../lib/code/workspace/followFiles.test.ts | 80 ++- .../web/lib/code/workspace/followFiles.ts | 136 +++- .../web/lib/code/workspace/groupRegistry.ts | 9 + packages/web/lib/code/workspace/model.test.ts | 116 +++- packages/web/lib/code/workspace/model.ts | 380 +++++++++- .../web/lib/code/workspace/navHistory.test.ts | 22 +- packages/web/lib/code/workspace/navHistory.ts | 24 +- packages/web/lib/code/workspace/persist.ts | 2 +- .../web/lib/code/workspace/quickOpen.test.ts | 70 +- packages/web/lib/code/workspace/quickOpen.ts | 197 +++++- packages/web/lib/code/workspace/symbolPath.ts | 92 +-- packages/web/lib/editorPaletteCommands.ts | 107 ++- packages/web/lib/filePathLinks.ts | 21 +- packages/web/lib/filesPane.ts | 109 ++- packages/web/lib/remarkEntityCards.test.tsx | 6 +- packages/web/lib/stage.ts | 36 +- packages/web/lib/terminal/endpoint.ts | 34 +- packages/web/lib/terminal/termRegistry.ts | 3 + packages/web/lib/terminal/termSessions.ts | 42 ++ packages/web/lib/vault/client.ts | 41 +- .../web/lib/vault/hosts/VaultMachineBar.tsx | 27 +- packages/web/lib/vault/vaultHref.ts | 9 + packages/web/perf/README.md | 52 ++ packages/web/plugins/contentOnlyHmr.test.ts | 112 ++- packages/web/plugins/contentOnlyHmr.ts | 109 +-- packages/web/plugins/tailwindWorker.test.ts | 23 +- packages/web/plugins/tailwindWorker.ts | 49 +- packages/web/scripts/perf-budgets.sh | 3 + packages/web/shortcuts/keyOwnership.ts | 1 + .../web/store/__tests__/sim/windowSlots.ts | 4 + .../store/__tests__/stubAudiencePick.test.ts | 82 +++ .../web/store/__tests__/stubTeamPick.test.ts | 76 -- packages/web/store/codeStore.ts | 14 +- packages/web/store/criticalUiPrefs.ts | 44 ++ packages/web/store/inboxStore.ts | 124 ++-- packages/web/store/vaultStore.ts | 262 +++---- packages/web/store/vaultTypes.ts | 24 +- scripts/ci/local.ts | 45 +- 200 files changed, 9835 insertions(+), 5314 deletions(-) create mode 100644 packages/cli/src/ciPoolHost.test.ts create mode 100644 packages/cli/src/ciRun/command.ts create mode 100644 packages/cli/src/ciRun/executor.ts create mode 100644 packages/cli/src/ciRun/run.test.ts create mode 100644 packages/cli/src/ciRun/run.ts create mode 100644 packages/cli/src/hostWorkTicks.ts create mode 100644 packages/convex/convex/changeApprovals.landing.test.ts create mode 100644 packages/convex/convex/ciPool.test.ts create mode 100644 packages/convex/convex/lib/changeApprovalReads.ts create mode 100644 packages/convex/convex/lib/changeApprovalRecordValidator.ts create mode 100644 packages/convex/convex/lib/ciRoutes.ts create mode 100644 packages/shared/contracts/ciWorkflow.test.ts create mode 100644 packages/shared/contracts/ciWorkflow.ts delete mode 100644 packages/web/app/(marketing)/blog/agents-in-your-own-chrome/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-cursor-codex/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-from-your-phone/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-history-on-day-one/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/claude-code-sessions/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/codecast-in-the-cloud/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/fewer-bigger-jumps/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/one-repository-twenty-checkouts/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-chart-in-the-reply/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-questions-your-agents-save-for-you/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-task-your-agent-reports-to/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/the-tree-at-the-end-of-every-turn/page.tsx delete mode 100644 packages/web/app/(marketing)/blog/undo-with-a-history/page.tsx create mode 100644 packages/web/store/__tests__/stubAudiencePick.test.ts delete mode 100644 packages/web/store/__tests__/stubTeamPick.test.ts create mode 100644 packages/web/store/criticalUiPrefs.ts diff --git a/docs/architecture/code-editor.md b/docs/architecture/code-editor.md index 024298c868..a01c0ac71c 100644 --- a/docs/architecture/code-editor.md +++ b/docs/architecture/code-editor.md @@ -34,7 +34,8 @@ conversation the person is steering. The editor shows those facts in place. default) would hand half-typed code to watchers, typecheckers and agents reading the disk. A setting turns autosave on. - **Vim is on when a vimrc is found**, off otherwise, toggled from the status - bar mode chip and in Settings > Editor. + bar mode chip (on screen while off too, as a dim "Vim") and in Settings > + Editor. - **The daemon is the backend.** Reads, writes, search (ripgrep), git, blame, vimrc and language servers all run on the machine that holds the files, behind the loopback bridge's existing envelope (`authorizeLocalRequest`). @@ -56,7 +57,8 @@ packages/shared/contracts/codeProtocol.ts every request/response type above packages/web/lib/code/ editor engine, no React buffers.ts open buffers: EditorState cache, base etag, dirty, hot exit languages.ts lazy language loading (@codemirror/language-data) - theme.ts sol token theme + highlight style (shared with VaultEditor) + theme.ts sol token theme, highlight roles, overlay look; syntax colors + match Prism's (codeHighlightParity.test.ts) vim/ vim setup, vimrc parser + translator, ex adapters, plugins lsp/ transport over /lsp/ws, client pool git/ gutter + diff-vs-HEAD extensions @@ -110,6 +112,43 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv 9. **One "editor the person was in".** Commands run without a view (the palette, a chip) act on `focusedEditorView()` from features.ts, never a tracker of their own. +10. **Idle costs what is on screen.** Agents save files all day, so an open + editor pays per save only for what it shows: watcher events land in + batches, the daemon is asked once per burst, one request per kind is in + flight, a hidden page asks nothing until it is shown (`whenVisible`, + idle.ts), and a file no buffer holds is not read again. The budgets and + their numbers are in packages/web/perf/README.md ("Editor"). + +## When disk and the daemon disagree + +Every state below is a strip over the editor and a mark on the file's tab +(the dot's slot: yellow waits on the person, red is deleted or refused), the +same mark in the tab switcher and quick open (`FileStateMark`). Nothing in +any of them drops text: hot exit holds every dirty buffer. + +- **Read-only mode (0444).** The daemon's read sends `X-Vault-Writable: 0` + and the mode, so the status bar's lock shows the mode before any save; the + file stays editable, as in vim. A save the daemon refuses (403 read-only) + opens the "Read-only on disk" strip; its Overwrite, the lock itself and + `:w!` go through the shared confirm, then resend with `force=1`, still on + the buffer's etag, the mode bits kept. +- **Read-only in the editor.** The lock names why: `mirror` (another + machine's vault), `offline` (held text shown while the daemon + reconnects; the lock reconnects), `encoding` (text that did not decode). A + save that writes nothing flashes the lock. +- **Daemon unreachable.** A save that got no answer (no endpoint, a refused + connection, a timeout) is "Not saved · Reconnecting", and runs again when + Files reconnects; any answer from the daemon is a refusal ("Save failed" + with its reason word). After a reconnect's rescan, open code files whose + mtime moved are read again. +- **Deleted under the app.** An agent's `rm`, a branch switch or a stash + keeps the tab, struck through, with Recreate; the file returning drops + back into it. Only the person's own delete in the tree closes clean tabs. +- **Renamed under the app.** The watcher's removed plus add is followed as a + rename when the added file has the same size and its etag is the buffer's + base: tabs, unsaved text, hot exit and history move to the new path. +- **Large files** (past `LARGE_FILE_BYTES`) say "Large file" in the status + bar; language servers, word completion and selection matches are off. ## Vim @@ -132,13 +171,22 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv its body is a plain ex command. macOS option-key glyphs (`˙`, `∆`) map as the characters they are. - **Ex adapters.** Ex commands that name editor or plugin features run the - codecast equivalent: `:w :q :wq :x :e :sp :vs :bn :bp :bd :tabnew`, `` - window moves to split groups, NERDTree/netrw/Explore to the file tree, + codecast equivalent: `:w :q :wq :x :e :sp :vs :bn :bp :bd :tabnew`, `:b#`, + `:e#` and `` to the alternate tab, every `` key to split groups + (moves, `w`/`W`/`p`/`t`/`b` focus, `x`/`r` swap, `H J K L` to an edge, + `=`, `_`, `|` and counted `+ - < >` sizes; a key with no counterpart is + spent with a note, never passed to the engine as a command), NERDTree/netrw/Explore to the file tree, CtrlP/FZF/Files/Telescope find_files to quick open, CtrlPBuffer/Buffers to the tab switcher, grep/Rg/Ag/Ack/Telescope live_grep to project search, Gdiffsplit/Gvdiffsplit/DiffviewOpen to diff vs HEAD, Git blame to the session blame gutter. A map whose right side calls an adapted command works through the adapter. +- **Command line.** gdefault flips `:s`'s `g` flag on the way into the + engine (vim/gdefault.ts), which has no such option. Tab completes command + names, paths for `:e :sp :vs :tabe` and open tabs for `:b`, wildmenu style + (vim/complete.ts). While vim runs, ``/`` stops are the engine's + own jumps (G, gg, /, n, *, %, marks) plus file switches, never a line + distance. - **Plugins built in.** commentary (`gc`, `gcc`), surround (`ys`, `cs`, `ds`, visual `S`), `ae`/`ie` and `ii`/`ai` text objects, and LSP motions (`gd`, `gr`, `K`, `[d`/`]d`). @@ -160,12 +208,14 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv the file at those lines. Cmd-K asks for an instruction inline and sends it to the linked session with the range; the agent's edit then streams into the buffer. A vimrc's own Cmd maps win over both (vim takes the key first), so - each has vim ways in that never collide: `:Ask [instruction]` opens the box - on the line, a typed range or the visual selection (prefilled with the - argument), `:Quote` quotes it, and `k` / `l` (normal and + each has vim ways in that never collide: `:Ask instruction` sends it about + the line, a typed range or the visual selection to the linked session at + once (bare `:Ask`, or no linked session, opens the box instead, prefilled), + `:Quote` quotes it, and `k` / `l` (normal and visual) are bound unless the vimrc maps those keys or keys that start with them. -- **Which session.** A session the person picks for the folder wins, then the +- **Which session.** A session the person picks for the folder wins (kept per + vault in localStorage beside the code workspace), then the conversation beside this editor's Files pane (the one it was opened from, `AppTab.editorOpenedFrom`, while it is on stage; when the active tab holds Files only that tab counts, and a conversation on another tab counts only @@ -186,20 +236,81 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv for presence dots, and used to name the writer of a change only when no other open tab in the vault shares the name. An edit no working session names takes a neutral color, never a guessed name. -- **Sent marker.** After a Cmd-K send the range says "sent to " - until the file changes under it or the turn that read the message ends: +- **Sent marker.** After a Cmd-K send the range says "sent to ", + with a dot that is hollow while the message waits and filled in the + session's color once its turn runs, until that range's lines change (typed, + or written on disk; a write elsewhere only maps it) or the turn that read + the message ends: keyed by the message's client id, it waits for the message to reach the transcript before a turn end counts, so an instruction queued behind a running turn keeps its marker past that turn. - **Agent edits, live.** When a session writes an open file, the changed - ranges flash in that session's color and stay marked until the person moves - on; the tab shows which session is editing the file now. + ranges flash in that session's color (the fade starts when the buffer is + first on screen) and keep a bar and a scrollbar tick until the cursor + enters them (the bar is drawn over the git bar's place, so it takes no + column, and a session's color is never git's green, red or blue), the bar is clicked, or `:AgentClear` / the status item's × + clears them; Escape never does. The status bar counts them in the writer's + color, and a press on the count, `]a`/`[a` or Alt-F6/Shift-Alt-F6 (beside the git hunk pair on Alt-F5; Cmd-Alt-arrows move between groups) steps through + them. Over unsaved edits the write merges at once: lines only disk changed + land (marked the same way) and the person's own stay unsaved; a region both + wrote opens the merge view, its conflicts red-barred, counted apart from the + person's clean edits and stepped to first. Keep mine writes the person's + text over that disk version on its etag; Take disk drops theirs. The tab + shows which session is editing the file now. - **Session blame.** A gutter names the session that wrote each line (git - trailer for committed lines, content match for uncommitted ones); a click - opens that conversation. -- **Review.** Diff vs HEAD (and vs a session's base) opens as a merge view - with per-hunk revert. -- **Elsewhere.** The command palette opens any file and runs editor commands; - the repo blob page opens a local checkout in the editor; the terminal dock - opens at the editor's root. Mobile is out of scope (phones read code in - transcripts and diffs). + trailer for committed lines, content match for uncommitted ones), in the + same color the session takes everywhere in the editor (sessionColor); a + click opens that conversation beside, scrolled to the message that made + the edit (`/conversation/#msg-` as a stage leaf). +- **Review.** Diff vs HEAD or any ref (the picker: previous commit, + upstream, merge base, and each session's base, in its color) opens inline + or side by side, with Revert as the one per-hunk action. A session's base + is read off its own commits (`sessionGitRefs`, lib/code/agent/sessions.ts): + the parent of its first commit, HEAD while it has committed nothing, never + the branch's merge base, which on a trunk checkout holds other sessions' + commits. The conversation diff's Edit opens the same refs (Session, Commit + as the session's last commit, Branch as the merge base), and the picker + offers the linked session's and every blamed writer's. A PR, commit or + compare diff gives each file an Edit into this machine's checkout, with the + diff against the PR base, the commit's parent or the compare base when the + checkout holds that revision. A new file (untracked or added) has no gutter + and diffs against nothing ("New file") or an older ref. The side-by-side + pane's commands (vim's `]c`, Alt-F5) act on its diff. An edit tool card + opens at the edit's text where it is now, with its old lines peeked. +- **Terminals.** A path in terminal output (the dock's shells, a + conversation's attached pane, a host's relayed pane) is a link: `x.ts:12:4`, + tsc's `x.ts(12,4)`, a grep hit, a `git status` line (lib/terminal/fileLinks.ts, + the prose grammar of filePathLinks plus the `(line,col)` suffix). A relative + path resolves where the shell is now: the daemon's `/term/sessions` carries + tmux's `pane_current_path` as `cwd`, read at the click with a 400 ms cap + and without touching the panel's probe state (most shells never report a + `cd`), else what OSC 7 last reported, else the start directory. In + an agent's pane it resolves in the conversation's project. It opens on the + pane's machine. +- **Messages.** A ```cast-diff fence's file cards carry Edit, at the file's + first changed line, the path resolved from the session's checkout root + (a git diff names files from there). Outside a conversation nothing + resolves it and the card has none. A plain code fence carries no path the + agents write, so it has no Edit. +- **Tasks and plans.** Paths cited in a task's comments, an inline task + thread's description and a plan's doc resolve in the task's or plan's + `project_path` (useFolderPathContext), so `lib/x.ts:38` opens that + project's file; a row with no project keeps the context around it (a + thread inside a conversation keeps the conversation's). Task and plan rows + name no machine, so the folder opens on the editor's default vault, which + is wrong when the row came from another machine. The task description is a rich-text editor and does not link paths. +- **Review threads.** A PR line thread on the new side carries Edit: its lines, + where the thread sits now, in this machine's worktree on the head branch. + With no worktree on that branch the thread has no Edit: another tree's + lines at those numbers are different lines. +- **The conversation.** The header menu's Open project in editor opens the + session's project folder on the session's machine and links the + conversation; the palette's Open project files on a session row opens it on + that session's machine. +- **Elsewhere.** The command palette opens any file (code files of a local + vault rank beside notes) and runs editor commands; the repo blob page opens + a local checkout in the editor; the terminal dock opens at the editor's + root; the desktop app's Go menu has Files; a `codecast://open/files?path=&l=` + link opens the editor at that line (deep links carry any in-app path); the + keyboard shortcuts panel has an Editor section. Mobile is out of scope + (phones read code in transcripts and diffs). diff --git a/packages/cli/src/__fixtures__/install-golden/stub/check.md b/packages/cli/src/__fixtures__/install-golden/stub/check.md index e8e9b066f0..91ec0cc619 100644 --- a/packages/cli/src/__fixtures__/install-golden/stub/check.md +++ b/packages/cli/src/__fixtures__/install-golden/stub/check.md @@ -1,14 +1,8 @@ ## Typechecking -Typecheck TypeScript with `cast check`, never `tsc --noEmit`. One `tsc --watch` per tree and project rechecks only changed files, so answers take seconds and ten sessions asking cost the same as one; fresh `tsc` runs rebuild everything and push the machine into swap. +Typecheck through one shared tsc watcher per project (cast check). Adds `cast check` so agents typecheck through one shared `tsc --watch` per tree and project instead of each running its own `tsc --noEmit`. The watcher keeps the program in memory and re-checks only what changed, so a check answers in seconds however many sessions ask, and a machine full of agents stops building the same program dozens of times over. A repo names its programs in a tracked .codecast/check.toml; without one, the tsconfig nearest the agent's directory is checked. -```bash -cast check # the projects your changes reach (--all: every one in .codecast/check.toml) -cast check web # one project by name, or any directory or tsconfig path -cast check --fresh # restart a watcher that lost track, then ask -``` - -If a pass is running or queued, wait on it rather than run your own `tsc`. A worktree holds a program of its own (gigabytes per project), so give worktrees only to the agents whose edits would collide. When a check is red with errors nobody wrote, suspect the `.codecast/check.toml` entry before the code. `cast guide check` covers that file. +Run `cast guide check` for the commands and flags. The guide ships inside the binary you run, so it always matches the `cast` that will execute them. diff --git a/packages/cli/src/blame.test.ts b/packages/cli/src/blame.test.ts index 99eb34bf08..cefa0446ae 100644 --- a/packages/cli/src/blame.test.ts +++ b/packages/cli/src/blame.test.ts @@ -388,6 +388,13 @@ describe("readSessionTrailers", () => { // More shas than fit on a command line (ARG_MAX is 1 MiB on macOS). const many = [...Array.from({ length: 30_000 }, (_, i) => i.toString(16).padStart(40, "0")), trailed]; expect([...(await readSessionTrailers(many, dir))]).toEqual([[trailed, id]]); + // A sweep (several sessions' work in one commit) names no one session. + fs.writeFileSync(path.join(dir, "a.txt"), "three\n"); + git("commit", "-q", "-am", "sweep", "--trailer", `Codecast-Session: ${id}`, "--trailer", "Codecast-Session: jx70e0f"); + const sweep = git("rev-parse", "HEAD"); + const sweeps = new Map(); + expect([...(await readSessionTrailers([trailed, sweep], dir, sweeps))]).toEqual([[trailed, id]]); + expect([...sweeps]).toEqual([[sweep, 2]]); } finally { fs.rmSync(dir, { recursive: true, force: true }); } diff --git a/packages/cli/src/blame.ts b/packages/cli/src/blame.ts index ff28e36bca..6d47d5fd75 100644 --- a/packages/cli/src/blame.ts +++ b/packages/cli/src/blame.ts @@ -13,7 +13,7 @@ import * as fs from "node:fs"; import * as path from "node:path"; import open from "open"; import { cliFetchRead } from "./cliHttp.js"; -import { contentLinesToMatch as selectContentLines, extractSessionTrailer, overlapLinesBySha, type ContentLine } from "@codecast/shared/blame"; +import { contentLinesToMatch as selectContentLines, extractSessionTrailer, overlapLinesBySha, sessionTrailerCount, type ContentLine } from "@codecast/shared/blame"; import { git } from "./code/codeGit.js"; import { defaultConfigDir } from "./config/configDir.js"; import { webBaseUrl } from "./config/readLocalConfig.js"; @@ -71,6 +71,11 @@ export interface BlameResolution { // is a bot organizing other sessions' work — the authoring session is the // one whose reasoning you want to read. byLine: Map; + // sha → how many sessions a sweep commit names in its Codecast-Session + // trailers. Such a commit carries several sessions' work, so the session + // that ran `git commit` (found by hash, commit row or subject) wrote none + // of it in particular and is never the answer for its lines. + sweeps?: Map; } export const EMPTY_RESOLUTION: BlameResolution = { @@ -298,7 +303,7 @@ export interface CommitDescriptor { // commit objects in one `git cat-file --batch`. The shas go in on stdin, so a // file with any number of blamed commits fits, and a commit git cannot read (a // shallow clone missing it) answers "missing" and costs only itself. -export async function readSessionTrailers(shas: string[], cwd: string): Promise> { +export async function readSessionTrailers(shas: string[], cwd: string, sweeps?: Map): Promise> { const found = new Map(); const wanted = [...new Set(shas)].filter((sha) => /^[0-9a-f]{4,64}$/i.test(sha)); if (wanted.length === 0) return found; @@ -321,7 +326,13 @@ export async function readSessionTrailers(shas: string[], cwd: string): Promise< if (type !== "commit") continue; const text = body.toString("utf-8"); const headerEnd = text.indexOf("\n\n"); - const session = extractSessionTrailer(headerEnd < 0 ? "" : text.slice(headerEnd + 2)); + const message = headerEnd < 0 ? "" : text.slice(headerEnd + 2); + const count = sessionTrailerCount(message); + if (count > 1) { + sweeps?.set(sha, count); + continue; + } + const session = extractSessionTrailer(message); if (session) found.set(sha, session); } return found; @@ -395,7 +406,8 @@ export async function resolveFromParsed( ): Promise { if (!config.auth_token || !config.convex_url) return EMPTY_RESOLUTION; const shas = [...new Set(parsed.lines.map((l) => l.sha))].filter((s) => s !== ZERO_SHA); - const trailers = await readSessionTrailers(shas, path.dirname(absFilePath)); + const sweeps = new Map(); + const trailers = await readSessionTrailers(shas, path.dirname(absFilePath), sweeps); const overlapLines = overlapLinesBySha( parsed.lines .filter((line) => line.sha !== ZERO_SHA && !trailers.has(line.sha)) @@ -415,7 +427,12 @@ export async function resolveFromParsed( const contentLines = contentLinesToMatch(parsed, Date.now()); const siteUrl = config.convex_url.replace(".cloud", ".site"); try { - return await resolveSessions(siteUrl, config.auth_token, commits, absFilePath, contentLines); + const resolution = await resolveSessions(siteUrl, config.auth_token, commits, absFilePath, contentLines); + if (sweeps.size === 0) return resolution; + // A sweep's lines belong to whoever wrote them: keep an overlap match, + // drop an answer that only found the session that committed the sweep. + const bySha = new Map([...resolution.bySha].filter(([sha, ref]) => !sweeps.has(sha) || ref.via === "overlap")); + return { ...resolution, bySha, sweeps }; } catch (error) { console.error( `cast blame: session resolution unavailable (${error instanceof Error ? error.message : error})`, diff --git a/packages/cli/src/browser/cloudHost.test.ts b/packages/cli/src/browser/cloudHost.test.ts index b170098994..a790ccc87a 100644 --- a/packages/cli/src/browser/cloudHost.test.ts +++ b/packages/cli/src/browser/cloudHost.test.ts @@ -4,7 +4,7 @@ import { promisify } from "node:util"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -import { instanceNameTag, NEW_HOST_LOGINS, patchHost, readHosts, registryLockPath, resolveCloudHost, toRemoteHost, upsertHost, writeHosts, type CloudHost } from "./cloudHost"; +import { credentialPushHosts, instanceNameTag, NEW_HOST_LOGINS, reachableRemoteHosts, patchHost, readHosts, registryLockPath, resolveCloudHost, toRemoteHost, upsertHost, writeHosts, type CloudHost } from "./cloudHost"; let dir: string, prev: string | undefined; const base: CloudHost = { id: "i-1", provider: "aws", region: "us-west-2", user: "ubuntu", keyPath: "/k", address: "1.1.1.1", forwardAgent: true, idleStopMinutes: 20 }; @@ -147,3 +147,21 @@ describe("resolveCloudHost — the default skips a host reserved for one job", ( expect(() => resolveCloudHost()).toThrow("every registered cloud host is reserved for one job (i-1: Acme line, i-2: evals)"); }); }); + +describe("credential pushes skip CI machines", () => { + const h = (id: string, address: string, reservedFor?: string): CloudHost => + ({ id, provider: "aws", region: "us-west-2", user: "ubuntu", keyPath: "/k", address, platform: "linux", ...(reservedFor ? { reservedFor } : {}) }); + const hosts = [h("i-dev", "10.0.0.1"), h("i-ci", "10.0.0.2", "ci: codecast-sh/codecast pool"), h("i-evals", "10.0.0.3", "evals")]; + + test("only a ci: reservation is left out", () => { + expect(credentialPushHosts(hosts).map((x) => x.id)).toEqual(["i-dev", "i-evals"]); + }); + + test("the reachable set a push walks never reaches a CI host", async () => { + const probed: string[] = []; + const reach = async (r: { address: string }) => { probed.push(r.address); return true; }; + const out = await reachableRemoteHosts([], reach, credentialPushHosts(hosts)); + expect(out.map((r) => r.address).sort()).toEqual(["10.0.0.1", "10.0.0.3"]); + expect(probed).not.toContain("10.0.0.2"); + }); +}); diff --git a/packages/cli/src/browser/sharedHost.test.ts b/packages/cli/src/browser/sharedHost.test.ts index 3016af85fb..e413d0befd 100644 --- a/packages/cli/src/browser/sharedHost.test.ts +++ b/packages/cli/src/browser/sharedHost.test.ts @@ -148,7 +148,7 @@ describe("binaries outside private homes", () => { test("a member runs the box's own cast bundle when it has one, on their own bun", () => { const s = addUserSelfScript({}); expect(s).toContain("if [ -f /usr/local/lib/codecast/index.js ]"); - expect(s).toContain('exec "$HOME/.bun/bin/bun" /usr/local/lib/codecast/index.js "$@"'); + expect(s).toContain('exec "$HOME/.bun/bin/bun" --no-env-file /usr/local/lib/codecast/index.js "$@"'); }); test("a new user's installs run with their own PATH, so a tool linked for the owner is never taken as theirs", () => { diff --git a/packages/cli/src/ciPoolHost.test.ts b/packages/cli/src/ciPoolHost.test.ts new file mode 100644 index 0000000000..191822ed73 --- /dev/null +++ b/packages/cli/src/ciPoolHost.test.ts @@ -0,0 +1,154 @@ +// The CI pool's daemon tick against a real bare mirror whose origin moves: it queues each first-parent commit main +// gained, claims queued shas only into free slots, starts `cast ci run --lease`, and frees a slot when its run's +// process is gone. The lease rules themselves (one winner, takeover after 2 minutes) are ciLeases.test.ts's. +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { castArgv, readPoolMarker, tickCiPool, type PoolMarker } from "./ciPoolHost.js"; +import { sh } from "./ciRun/executor.js"; + +const tmp = mkdtempSync(path.join(os.tmpdir(), "castci-pool-")); +const HOME = process.env.HOME; +beforeAll(() => { process.env.HOME = path.join(tmp, "home"); mkdirSync(process.env.HOME, { recursive: true }); }); +afterAll(() => { process.env.HOME = HOME; rmSync(tmp, { recursive: true, force: true }); }); + +const g = (dir: string, ...a: string[]) => { + const r = sh("git", ["-C", dir, "-c", "user.name=t", "-c", "user.email=t@t", ...a]); + if (r.code !== 0) throw new Error(r.err); + return r.out; +}; + +function world() { + const origin = path.join(tmp, "origin"); + mkdirSync(origin, { recursive: true }); + g(origin, "init", "-q", "-b", "main"); + const commit = (m: string) => { writeFileSync(path.join(origin, `${m}.txt`), m); g(origin, "add", "."); g(origin, "commit", "-qm", m); return g(origin, "rev-parse", "HEAD"); }; + const c1 = commit("one"); + const mirror = path.join(tmp, "mirror.git"); + sh("git", ["clone", "-q", "--bare", origin, mirror]); + return { origin, mirror, commit, c1 }; +} + +/** A lease server's routes as the tick calls them, holding what a test needs to see. */ +function fakeServer() { + const queue: Array<{ sha: string; before?: string }> = []; + const claimed: string[] = []; + const calls: string[] = []; + const post = async (route: string, body: any) => { + calls.push(route); + if (route.endsWith("/enqueue")) { for (const c of body.commits) if (!queue.some((q) => q.sha === c.sha)) queue.push(c); return { added: body.commits.length }; } + if (route.endsWith("/pending")) return { leases: queue.filter((q) => !claimed.includes(q.sha)).map((q) => ({ ...q, event: "push", before: q.before ?? null })) }; + if (route.endsWith("/claim")) { claimed.push(body.sha); return { claimed: true }; } + if (route.endsWith("/register-pool")) { calls.push(`register ${body.repository} ${body.lanes.join(",")}`); return { registered: true }; } + throw new Error(`unexpected ${route}`); + }; + return { queue, claimed, calls, post }; +} + +describe("the CI pool's daemon tick", () => { + test("queues what main gained, oldest first, and claims into free slots only", async () => { + const w = world(); + const marker: PoolMarker = { role: "ci", pool: "p", repo: "o/r", host: "codecast-ci-1", slots: 1, mirror: w.mirror, lanes: ["linux"] }; + const server = fakeServer(); + const started: string[][] = []; + // A run's process that is still alive: this test's own pid. + const spawnRun = (argv: string[]) => { started.push(argv); return process.pid; }; + await tickCiPool({ marker, post: server.post, log: () => {}, spawnRun }); + expect(server.queue.map((q) => q.sha)).toEqual([w.c1]); + expect(server.calls).toContain("register o/r linux"); + expect(started).toHaveLength(1); + const argv = started[0]!; + expect(argv.slice(argv.indexOf("ci"), argv.indexOf("--lease"))).toEqual(["ci", "run", w.c1]); + expect(argv.slice(argv.indexOf("--os"))).toEqual(["--os", "linux", "--repository", "o/r"]); + expect(started[0]).toContain("--repository"); + expect(started[0]![started[0]!.indexOf("--lease") + 1]).toMatch(new RegExp(`^${w.c1.slice(0, 12)}-[0-9a-z]+$`)); + + // Two pushes land; the one slot is busy, so they are queued and none is claimed. + const c2 = w.commit("two"); + const c3 = w.commit("three"); + await tickCiPool({ marker, post: server.post, log: () => {}, spawnRun }); + expect(server.queue.map((q) => q.sha)).toEqual([w.c1, c2, c3]); + expect(server.queue[2]).toEqual({ sha: c3, before: c2 }); + expect(started).toHaveLength(1); + + // The run's process is gone (a pid that cannot be alive): its slot frees, and the oldest waiting sha goes next. + const dead = { ...marker }; + const state = path.join(process.env.HOME!, ".codecast", "ci-pool", "state.json"); + const s = JSON.parse(await Bun.file(state).text()); + s.runs[0].pid = 2 ** 22 + 12345; + writeFileSync(state, JSON.stringify(s)); + await tickCiPool({ marker: dead, post: server.post, log: () => {}, spawnRun }); + expect(started).toHaveLength(2); + expect(started[1]).toContain(c2); + expect(started[1]!.slice(started[1]!.indexOf("--before"), started[1]!.indexOf("--before") + 2)).toEqual(["--before", w.c1]); + }); + + test("a queued push that is not on the pool's branch is refused, and a run that never started gives its lease back", async () => { + const dir = mkdtempSync(path.join(tmp, "refuse-")); + const origin = path.join(dir, "origin"); + mkdirSync(origin); + g(origin, "init", "-q", "-b", "main"); + writeFileSync(path.join(origin, "a.txt"), "a"); + g(origin, "add", "."); + g(origin, "commit", "-qm", "a"); + const onMain = g(origin, "rev-parse", "HEAD"); + const mirror = path.join(dir, "mirror.git"); + sh("git", ["clone", "-q", "--bare", origin, mirror]); + // A sha that never landed on main (a fork's pull request head, say) sitting in the queue as a push. + const elsewhere = "ab".repeat(20); + const finished: Array<{ sha: string; conclusion: string }> = []; + const released: string[] = []; + const post = async (route: string, body: any) => { + if (route.endsWith("/enqueue") || route.endsWith("/register-pool")) return {}; + if (route.endsWith("/pending")) return { leases: [{ sha: elsewhere, event: "push" }, { sha: onMain, event: "push" }] }; + if (route.endsWith("/claim")) return { claimed: true }; + if (route.endsWith("/finish")) { finished.push({ sha: body.sha, conclusion: body.conclusion }); return { finished: true }; } + if (route.endsWith("/release")) { released.push(body.sha); return { released: true }; } + throw new Error(`unexpected ${route}`); + }; + const marker: PoolMarker = { role: "ci", pool: "p", repo: "o/r", host: "codecast-ci-1", slots: 50, mirror, lanes: ["linux"] }; + const started: string[][] = []; + await tickCiPool({ marker, post, log: () => {}, spawnRun: (argv) => { started.push(argv); return null; } }); + expect(finished).toEqual([{ sha: elsewhere, conclusion: "refused" }]); + expect(started.map((a) => a[a.indexOf("run") + 1])).toEqual([onMain]); + expect(released).toEqual([onMain]); + }); + + test("a post that throws after a run started still records that run, so the next tick counts its slot", async () => { + const dir = mkdtempSync(path.join(tmp, "throw-")); + const origin = path.join(dir, "origin"); + mkdirSync(origin); + g(origin, "init", "-q", "-b", "main"); + const shas: string[] = []; + for (const m of ["a", "b"]) { writeFileSync(path.join(origin, `${m}.txt`), m); g(origin, "add", "."); g(origin, "commit", "-qm", m); shas.push(g(origin, "rev-parse", "HEAD")); } + const mirror = path.join(dir, "mirror.git"); + sh("git", ["clone", "-q", "--bare", origin, mirror]); + let claims = 0; + const post = async (route: string) => { + if (route.endsWith("/enqueue") || route.endsWith("/register-pool")) return {}; + if (route.endsWith("/pending")) return { leases: shas.map((sha) => ({ sha, event: "push" })) }; + if (route.endsWith("/claim")) { if (++claims > 1) throw new Error("network down"); return { claimed: true }; } + throw new Error(`unexpected ${route}`); + }; + const marker: PoolMarker = { role: "ci", pool: "p", repo: "o/r", host: "codecast-ci-1", slots: 50, mirror, lanes: ["linux"] }; + const prevHome = process.env.HOME; + process.env.HOME = path.join(dir, "home"); + try { + await expect(tickCiPool({ marker, post, log: () => {}, spawnRun: () => process.pid })).rejects.toThrow("network down"); + const state = JSON.parse(await Bun.file(path.join(process.env.HOME, ".codecast", "ci-pool", "state.json")).text()); + expect(state.runs.map((r: { sha: string }) => r.sha)).toEqual([shas[0]]); + } finally { + process.env.HOME = prevHome; + } + }); + + test("a machine without the role marker is not in a pool; a daemon run from source starts the CLI's entry", () => { + expect(readPoolMarker(path.join(tmp, "nope.json"))).toBeNull(); + const f = path.join(tmp, "pool.json"); + writeFileSync(f, JSON.stringify({ role: "ci", pool: "codecast-ci", repo: "codecast-sh/codecast", host: "codecast-ci-1", slots: 1 })); + expect(readPoolMarker(f)).toMatchObject({ repo: "codecast-sh/codecast", host: "codecast-ci-1", slots: 1 }); + expect(castArgv("/usr/local/bin/cast", "/whatever")).toEqual(["/usr/local/bin/cast"]); + expect(castArgv("/x/bun", path.join(import.meta.dir, "daemon.ts"))).toEqual(["/x/bun", path.join(import.meta.dir, "index.ts")]); + }); +}); diff --git a/packages/cli/src/ciRun/command.ts b/packages/cli/src/ciRun/command.ts new file mode 100644 index 0000000000..999097f0a2 --- /dev/null +++ b/packages/cli/src/ciRun/command.ts @@ -0,0 +1,312 @@ +// `cast ci run `: codecast's own CI for one commit of any repository, on this machine. +// +// On a CI pool host (Linux) it runs in two halves. This process, as the host's own user (the daemon's), fetches the +// sha into the host's bare mirror under its lock, reads the repository's .codecast/ci.toml from a trusted tree (the +// commit itself for a push to main, main's tip for a pull request: a branch cannot grant its own jobs secrets), reads +// the vault secrets ci.toml names, and starts `cast ci run-inner` as root in the transient unit `ownci-.service` +// inside the per-run slice `ownci-.slice` (a child of ownci.slice, whose MemoryMax caps all CI on the host; +// cancel: `systemctl stop ownci-.slice`). The inner half takes one of the host's run slots (ci.toml +// runs_per_host, default 1), checks the slot's walls, wipes the slot user's home and runs the commit (run.ts). This +// half records the verdict with `cast ci record` as it goes: the in-progress verdict at least every 4 minutes (the +// pool controller counts a host busy by it), and the finished one with its job logs. +// +// `--unsandboxed` runs it all in this process, as this user, in a temp HOME: for trying a ci.toml on a laptop and +// for the macOS lane until the pool's macOS slot exists. + +import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { parseCiConfig, type CiConfig } from "@codecast/shared/contracts/ciConfig"; +import type { JobOs } from "@codecast/shared/contracts/ciWorkflow"; +import type { RunnerVerdict } from "@codecast/shared/contracts/ciVerdict"; +import { LocalExecutor, sh, SlotExecutor } from "./executor.js"; +import { Masker } from "./mask.js"; +import { runCommit, type RunInput } from "./run.js"; + +export type RunOptions = { + repo?: string; + event?: "push" | "pull_request"; + before?: string; + base?: string; + landing?: string; + only?: string; + os?: JobOs; + unsandboxed?: boolean; + out?: string; + record?: boolean; + /** The repository (owner/name) when ci.toml does not name it and --repo is not a checkout of it. */ + repository?: string; + /** A ci.toml file to use instead of the repository's (a repo that has not committed one yet). */ + config?: string; + /** A lease this run holds (ciLeases.ts, its run id): heartbeat it, and finish it with the conclusion. */ + lease?: string; +}; + +/** The exit codes: 0 green (or nothing to run), 1 red, 2 infra (the runner's failure, not the commit's). */ +export const RUN_EXIT = { success: 0, failure: 1, infra: 2 } as const; + +/** How to start this same cast: the compiled binary, or bun with the entry script when run from source. */ +export function selfArgv(): string[] { + const script = process.argv[1]; + return script && /\.(ts|js|mjs)$/.test(script) && existsSync(script) ? [process.execPath, path.resolve(script)] : [process.execPath]; +} + +const git = (dir: string, args: string[], timeoutMs = 120_000) => sh("git", ["-C", dir, ...args], { timeoutMs }); + +/** ci.toml at a ref of the source, parsed; absent is the default config. */ +export function configAt(source: string, ref: string): CiConfig { + const r = git(source, ["show", `${ref}:.codecast/ci.toml`]); + const raw = r.code === 0 ? Bun.TOML.parse(r.out) : {}; + const parsed = parseCiConfig(raw); + if ("problems" in parsed) throw new Error(`.codecast/ci.toml at ${ref.slice(0, 12)} is wrong:\n ${parsed.problems.join("\n ")}`); + return parsed.config; +} + +/** A ci.toml given on the command line, parsed. */ +export function configFile(file: string): CiConfig { + const parsed = parseCiConfig(Bun.TOML.parse(readFileSync(file, "utf-8"))); + if ("problems" in parsed) throw new Error(`${file} is wrong:\n ${parsed.problems.join("\n ")}`); + return parsed.config; +} + +/** The name this host goes by in verdicts: the pool's role marker (the EC2 Name tag), else its hostname. */ +export function hostName(config: CiConfig): string { + try { + const pool = JSON.parse(readFileSync(config.host.pool_file, "utf-8")) as { host?: string }; + if (pool.host) return pool.host; + } catch {} + return os.hostname().split(".")[0]!; +} + +/** Fetch what a run needs into the host's bare mirror, under its lock: main, and the sha when it is not there. */ +function fetchMirror(mirror: string, branch: string, sha: string): void { + const lock = `${mirror}.lock`; + const r = sh("flock", [lock, "sh", "-c", `git -C "$1" fetch -q origin "+refs/heads/$2:refs/heads/$2" && { git -C "$1" cat-file -e "$3^{commit}" 2>/dev/null || git -C "$1" fetch -q origin "$3"; } && git -C "$1" update-ref "refs/ownci/keep/$3" "$3"`, "_", mirror, branch, sha], { timeoutMs: 10 * 60_000 }); + if (r.code !== 0) throw new Error(`fetching ${sha.slice(0, 12)} into ${mirror}: ${r.err}`); +} + +type Deps = { + /** A codecast CLI route (the lease's heartbeat and finish). */ + post?: (route: string, body: Record) => Promise; + readVault: (names: string[]) => Promise>; + record: (file: string, o: { logs: boolean }) => Promise<{ written: boolean }>; + repositoryOf: (dir: string) => string | null; + log: (line: string) => void; +}; + +export async function runCi(shaArg: string, opts: RunOptions, deps: Deps): Promise { + if (!opts.lease) return runCiOnce(shaArg, opts, deps); + const lease = { lost: false, key: null as null | Record }; + let code: number = RUN_EXIT.infra; + let conclusion = "infra"; + try { + code = await runCiOnce(shaArg, opts, deps, lease, (c) => { conclusion = c; }); + } finally { + // A run that lost its lease leaves the sha to the host that took it over. + if (lease.key && !lease.lost) await deps.post?.("/cli/ci/lease/finish", { ...lease.key, conclusion }).catch((err) => deps.log(`lease finish failed: ${err instanceof Error ? err.message : String(err)}`)); + } + return code; +} + +async function runCiOnce(shaArg: string, opts: RunOptions, deps: Deps, lease?: { lost: boolean; key: null | Record }, concluded: (c: string) => void = () => {}): Promise { + const repoDir = path.resolve(opts.repo ?? process.env.CODECAST_CWD ?? process.cwd()); + const lane: JobOs = opts.os ?? (process.platform === "darwin" ? "darwin" : "linux"); + const event = opts.event ?? (opts.landing ? "pull_request" : "push"); + if (!opts.unsandboxed && process.platform !== "linux") throw new Error("A sandboxed run needs a Linux CI host; on this machine pass --unsandboxed (steps then run as you, in a temp HOME)."); + + // The source checkouts clone from, and the trusted tree ci.toml is read from. + const local = git(repoDir, ["rev-parse", "--path-format=absolute", "--git-common-dir"]); + if (local.code !== 0 && opts.unsandboxed) throw new Error(`${repoDir} is not a git checkout`); + // The mirror and branch come from the given ci.toml, else this checkout's, else the default layout. + const bootstrap = opts.config ? configFile(opts.config) : local.code === 0 ? configAt(local.out, "HEAD") : parseConfigOrDefault(); + const source = opts.unsandboxed ? local.out : bootstrap.host.mirror; + const branch = bootstrap.branch; + let sha = git(source, ["rev-parse", "--verify", "-q", `${shaArg}^{commit}`]).out; + if (!opts.unsandboxed) { + fetchMirror(source, branch, /^[0-9a-f]{40}$/.test(shaArg) ? shaArg : sha || shaArg); + sha = git(source, ["rev-parse", "--verify", "-q", `${shaArg}^{commit}`]).out; + } + if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error(`${shaArg} is not a commit in ${source}`); + const mainRef = opts.unsandboxed ? (git(source, ["rev-parse", "--verify", "-q", `refs/remotes/origin/${branch}`]).out ? `refs/remotes/origin/${branch}` : `refs/heads/${branch}`) : `refs/heads/${branch}`; + const base = event === "pull_request" ? (opts.base ?? git(source, ["rev-parse", mainRef]).out) : undefined; + const config = opts.config ? configFile(opts.config) : configAt(source, event === "push" ? sha : base!); + const repository = opts.repository ?? config.repository ?? deps.repositoryOf(repoDir); + if (!repository) throw new Error("No repository: set repository in .codecast/ci.toml or run from a checkout with an origin remote."); + const host = hostName(config); + if (opts.lease && !(new RegExp(`^${sha.slice(0, 12)}-[0-9a-z]+$`).test(opts.lease))) throw new Error(`--lease ${opts.lease} is not a run id of ${sha.slice(0, 12)}`); + const id = opts.lease ?? `${sha.slice(0, 12)}-${Date.now().toString(36)}`; + let leaseTimer: ReturnType | null = null; + let stopRun = () => {}; + if (lease && deps.post) { + lease.key = { repository, sha, lane, event, host, run_id: id }; + // Every 30 seconds, against the lease's 2-minute expiry: a run whose lease another host took over stops. + leaseTimer = setInterval(() => { + void deps.post!("/cli/ci/lease/heartbeat", lease.key!).then((r) => { + if (r?.held === false && !lease.lost) { + lease.lost = true; + deps.log(`lease lost: ${r.holder ?? "another host"} holds ${sha.slice(0, 12)} now; stopping this run`); + stopRun(); + } + }).catch((err) => deps.log(`lease heartbeat failed: ${err instanceof Error ? err.message : String(err)}`)); + }, 30_000); + } + try { + const out = path.resolve(opts.out ?? (opts.unsandboxed ? path.join(os.tmpdir(), "castci", id) : path.join(os.homedir(), "ci", "runs", `${sha}-${lane}`))); + // A sha run again here (a retry, a lease taken back) starts from an empty verdict directory: job logs append, and + // the last run's lines would read as this run's failures. + for (const stale of ["jobs", "runner.log", "verdict.json", "not-triggered.txt"]) rmSync(path.join(out, stale), { recursive: true, force: true }); + mkdirSync(path.join(out, "jobs"), { recursive: true }); + const only = opts.only?.split(",").map((s) => s.trim()).filter(Boolean); + const vaultNames = Object.entries(config.secrets).filter(([, s]) => s.vault).map(([n]) => n); + const vault = vaultNames.length ? await deps.readVault(vaultNames.map((n) => config.secrets[n]!.vault!)) : {}; + // A vault secret is read by its vault name; the job sees it by its ci.toml name. + const secrets = Object.fromEntries(vaultNames.filter((n) => vault[config.secrets[n]!.vault!] !== undefined).map((n) => [n, vault[config.secrets[n]!.vault!]!])); + deps.log(`${repository} ${sha.slice(0, 12)} (${event}, ${lane} lane) on ${host} as castci-${id}; verdict in ${out}`); + + const base_: Omit = { + repository, sha, event, ...(opts.before ? { before: opts.before } : {}), ...(base ? { base } : {}), ...(opts.landing ? { headRef: opts.landing } : {}), + source, out, id, host, lane, config, ...(only ? { only } : {}), + }; + + let lastBeat = 0; + const beat = async (force = false) => { + if (opts.record === false || only) return; + if (!force && Date.now() - lastBeat < 4 * 60_000) return; + lastBeat = Date.now(); + try { await deps.record(path.join(out, "verdict.json"), { logs: false }); } catch (err) { deps.log(`heartbeat record failed: ${err instanceof Error ? err.message : String(err)}`); } + }; + + let verdict: RunnerVerdict | null = null; + if (opts.unsandboxed) { + const masker = new Masker((n) => !!config.secrets[n]?.public); + const merged = { ...envSecrets(config), ...secrets }; + masker.addAll(merged); + const r = await runCommit({ ...base_, secrets: merged, executor: new LocalExecutor(config), masker, say: deps.log, onVerdict: () => void beat() }); + if (!r.triggered) { deps.log(`not run: ${r.why} (GitHub runs no CI for it either)`); rmSync(out, { recursive: true, force: true }); concluded("not_triggered"); return 0; } + verdict = r.verdict; + } else { + // The inner half's job, root-only: its vault values never touch argv, a log or a file anyone else reads. + const state = config.host.state; + const jobFile = path.join(state, `${id}.job.json`); + const payload = JSON.stringify({ input: base_, secrets, uid: process.getuid?.(), gid: process.getgid?.() }); + const put = sh("sudo", ["-n", "sh", "-c", 'mkdir -p -m 755 "$1" && install -m 600 -o root -g root /dev/stdin "$2"', "_", state, jobFile], { input: payload }); + if (put.code !== 0) throw new Error(`could not hand the run to root (sudo): ${put.err}`); + const unit = `ownci-${id}`; + const start = sh("sudo", ["-n", "systemd-run", "--quiet", "--collect", `--unit=${unit}`, `--slice=ownci-${id.replace("-", "_")}.slice`, + "-p", "RuntimeMaxSec=21600", "-p", "WorkingDirectory=/", "-p", `StandardOutput=append:${out}/runner.log`, "-p", `StandardError=append:${out}/runner.log`, + "--setenv=HOME=/root", "--setenv=PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", + ...selfArgv(), "ci", "run-inner", jobFile]); + if (start.code !== 0) throw new Error(`could not start ${unit}: ${start.err}`); + stopRun = () => { sh("sudo", ["-n", "systemctl", "stop", `ownci-${id.replace("-", "_")}.slice`]); }; + const active = () => ["active", "activating", "deactivating"].includes(sh("systemctl", ["is-active", `${unit}.service`]).out); + while (active()) { + await Bun.sleep(15_000); + if (existsSync(path.join(out, "verdict.json"))) await beat(); + } + sh("sudo", ["-n", "systemctl", "stop", `ownci-${id.replace("-", "_")}.slice`]); + if (existsSync(path.join(out, "not-triggered.txt"))) { deps.log(`not run: ${readFileSync(path.join(out, "not-triggered.txt"), "utf-8").trim()}`); concluded("not_triggered"); return 0; } + if (lease?.lost) { deps.log("stopped: the lease went to another host, which records this sha"); return RUN_EXIT.infra; } + try { + verdict = JSON.parse(readFileSync(path.join(out, "verdict.json"), "utf-8")) as RunnerVerdict; + } catch { + verdict = null; + } + if (!verdict || verdict.status !== "completed") { + // The unit ended without finishing its verdict (killed, OOM, the host restarted): the runner broke. + verdict = { ...(verdict ?? { version: 1, repository, sha, name: config.name, kind: event === "push" ? "main" : "landing", host, run_id: `castci-${id}`, started_at: Date.now(), jobs: [] }), status: "completed", conclusion: "infra", finished_at: Date.now() } as RunnerVerdict; + writeFileSync(path.join(out, "verdict.json"), `${JSON.stringify(verdict, null, 2)}\n`); + } + } + for (const j of verdict.jobs) deps.log(` ${j.name.padEnd(28)} ${j.conclusion.padEnd(8)} ${String(j.seconds).padStart(5)}s${j.counts ? "" : " (does not count)"}${j.note ? ` ${j.note}` : ""}`); + deps.log(`${sha.slice(0, 12)}: ${verdict.conclusion}`); + if (opts.record !== false && !only) { + const r = await deps.record(path.join(out, "verdict.json"), { logs: true }); + deps.log(r.written ? "recorded" : "not recorded: a newer run of this sha is stored"); + } else if (only) deps.log("partial run (--only): not recorded"); + concluded(verdict.conclusion ?? "infra"); + return RUN_EXIT[verdict.conclusion ?? "infra"]; + } finally { + if (leaseTimer) clearInterval(leaseTimer); + } +} + +function parseConfigOrDefault(): CiConfig { + const p = parseCiConfig({}); + if ("problems" in p) throw new Error(p.problems.join("; ")); + return p.config; +} + +/** The host's secrets file (root 0600, `NAME=value` lines), when this process may read it. */ +function readEnvFile(file: string): Record { + const out: Record = {}; + let text = ""; + try { text = readFileSync(file, "utf-8"); } catch { return out; } + for (const line of text.split("\n")) { + const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim()); + if (m) out[m[1]!] = m[2]!.replace(/^(['"])(.*)\1$/, "$2"); + } + return out; +} + +/** An unsandboxed run's non-vault secrets: from this process's environment, as `cast vault run` would set them. */ +function envSecrets(config: CiConfig): Record { + const out: Record = {}; + for (const name of Object.keys(config.secrets)) if (process.env[name]) out[name] = process.env[name]!; + for (const s of Object.values(config.secrets)) if (s.github_app && process.env[s.github_app.key_secret]) out[s.github_app.key_secret] = process.env[s.github_app.key_secret]!; + return out; +} + +/** Hold one of `slots` run slots in `dir` (a file per slot naming its holder's pid), waiting as long as it takes. */ +export async function holdSlot(dir: string, slots: number, say: (l: string) => void): Promise<{ slot: number; release: () => void }> { + mkdirSync(dir, { recursive: true, mode: 0o755 }); + let told = false; + for (;;) { + for (let i = 0; i < slots; i++) { + const f = path.join(dir, `slot-${i}`); + try { + writeFileSync(f, String(process.pid), { flag: "wx" }); + return { slot: i, release: () => { try { if (readFileSync(f, "utf-8").trim() === String(process.pid)) rmSync(f); } catch {} } }; + } catch { + const holder = Number(readFileSync(f, "utf-8").trim()); + let alive = false; + try { process.kill(holder, 0); alive = true; } catch {} + if (!alive) { rmSync(f, { force: true }); i--; continue; } + } + } + if (!told) { say(`every run slot on this host is taken (${slots}); waiting`); told = true; } + await Bun.sleep(5_000); + } +} + +/** `cast ci run-inner `: the root half on a CI host. */ +export async function runInner(jobFile: string): Promise { + if (process.getuid?.() !== 0) { console.error("run-inner runs as root (cast ci run starts it)"); return 2; } + const st = statSync(jobFile); + if (st.uid !== 0 || (st.mode & 0o077) !== 0) { console.error(`${jobFile} must be root's and 0600`); return 2; } + const job = JSON.parse(readFileSync(jobFile, "utf-8")) as { input: Omit; secrets: Record; uid?: number; gid?: number }; + rmSync(jobFile, { force: true }); + const { input } = job; + const config = input.config; + const masker = new Masker((n) => !!config.secrets[n]?.public); + const secrets = { ...readEnvFile(config.host.env_file), ...job.secrets }; + masker.addAll(secrets); + const say = (l: string) => console.log(masker.apply(`${new Date().toISOString()} castci: ${l}`)); + const { slot, release } = await holdSlot(path.join(config.host.state, "ci-slot"), config.runs_per_host, say); + const chownOut = () => job.uid !== undefined && sh("chown", ["-R", `${job.uid}:${job.gid ?? job.uid}`, input.out]); + try { + const ex = new SlotExecutor(config, slot, input.id, `ownci-${input.id.replace("-", "_")}.slice`, (n, v) => masker.add(n, v)); + const walls = ex.wallsMissing(); + if (walls) throw new Error(`slot ${slot}'s isolation is not in place (${walls}): the CI pool's host setup provisions it`); + ex.freshHome(); + const r = await runCommit({ ...input, secrets, executor: ex, masker, say }); + if (!r.triggered) writeFileSync(path.join(input.out, "not-triggered.txt"), `${r.why}\n`); + } catch (err) { + say(`the runner broke before the run: ${err instanceof Error ? err.message : String(err)}`); + const v: RunnerVerdict = { version: 1, repository: input.repository, sha: input.sha, name: config.name, kind: input.event === "push" ? "main" : "landing", host: input.host, run_id: `castci-${input.id}`, started_at: Date.now(), finished_at: Date.now(), status: "completed", conclusion: "infra", jobs: [] }; + writeFileSync(path.join(input.out, "verdict.json"), `${masker.apply(JSON.stringify(v, null, 2))}\n`); + } finally { + release(); + chownOut(); + } + return 0; +} diff --git a/packages/cli/src/ciRun/executor.ts b/packages/cli/src/ciRun/executor.ts new file mode 100644 index 0000000000..75aecbc624 --- /dev/null +++ b/packages/cli/src/ciRun/executor.ts @@ -0,0 +1,441 @@ +// Where a CI run's steps execute. The rule both executors hold (from Union's runner, ct-102083): a commit's code +// may see its own run's secrets, never the host, another run, or anything left for the next run. +// +// SlotExecutor (Linux CI hosts, run as root): each step is a transient systemd unit inside the run's slice, run as +// the slot's user `` (no sudo, home wiped at every run start), in the slot's network namespace (its +// own loopback, the internet through NAT, of the host only the CI Postgres; IPv6 off), with its own /tmp, IPC and +// /dev/shm, the file system read-only outside its home, other users' processes hidden, and an environment file +// only root reads. Every read of a file a run wrote happens as the slot user: a regular file only, size-capped, +// with a timeout. The host layout (users, namespaces, cluster, mirror, pinned git) is provisioned by the pool +// (ct-103162) to the names in ciConfig.ts's DEFAULT_HOST_LAYOUT. +// +// LocalExecutor (`--unsandboxed`): steps run as the person running cast, in a fresh temp HOME with a runner's +// environment and nothing of theirs. No walls: for trying a repo's ci.toml on a laptop and for the macOS lane until +// the pool's macOS slot exists. + +import { spawn, spawnSync } from "../proc.js"; +import { createWriteStream, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { randomBytes } from "node:crypto"; +import type { CiConfig } from "@codecast/shared/contracts/ciConfig"; +import type { JobOs } from "@codecast/shared/contracts/ciWorkflow"; + +export type Sh = { code: number; out: string; err: string }; + +export function sh(cmd: string, args: string[], opts: { input?: string; timeoutMs?: number; env?: NodeJS.ProcessEnv; cwd?: string } = {}): Sh { + const r = spawnSync(cmd, args, { encoding: "utf-8", input: opts.input, cwd: opts.cwd, timeout: opts.timeoutMs ?? 120_000, maxBuffer: 64 * 1024 * 1024, env: opts.env ?? process.env }); + return { code: r.status ?? 1, out: (r.stdout ?? "").trim(), err: ((r.stderr ?? "") + (r.error ? r.error.message : "")).trim() }; +} + +export type StepSpec = { + /** Unique within the run: names the step's unit and its env file. */ + key: string; + script: string; + shell: "bash" | "sh"; + cwd: string; + env: Record; + deadline: number; + onLine: (line: string) => void; + /** The cores the step may use (AllowedCPUs syntax), when its runner shares the host with others. */ + cpus?: string; +}; +export type StepOutcome = { code: number; timedOut: boolean }; + +export interface Executor { + readonly os: JobOs; + readonly sandboxed: boolean; + readonly slot: number; + /** The run user's home; checkouts and scratch live under it. */ + readonly home: string; + readonly user: string; + /** Root-owned tool directory (/git, /bun/, /node/), or null when the host's own tools serve. */ + readonly opt: string | null; + /** The PATH every step starts from. */ + basePath(): string; + /** git as the run user, reading no config of its own. */ + git(args: string[], cwd: string, timeoutMs?: number): Sh; + mkdirs(dirs: string[]): void; + /** A file a step wrote: a regular file only, at most maxBytes, null when absent or anything else. */ + readRunFile(file: string, maxBytes?: number): string | null; + /** The regular files directly in a directory a step wrote, matching a glob. */ + listRunFiles(dir: string, pattern: string): string[]; + runStep(s: StepSpec): Promise; + /** The bin directory of a pinned bun (installed once per version), or null to use the host's. */ + bunBin(version: string): string; + nodeBin(major: string): string; + /** + * A tool directory as the job's own: a copy owned by the run user under dest, as GitHub's setup actions install + * into the runner user's home (code that treats a root-owned runtime as an MDM install sees what it would there). + */ + ownCopy(bin: string, dest: string): string; + /** A Postgres database of its own for one job runner, as a URL only the run's environment holds. */ + postgres?(port: number, db: string): string; + /** End every process the run left, drop its Postgres role, remove its work tree. */ + cleanup(workDir: string): void; +} + +/** git as root or as a run user reads only this, and no system config: a run cannot plant hooks or aliases for the next. */ +const gitEnv = (config: CiConfig) => ({ GIT_CONFIG_GLOBAL: config.host.gitconfig, GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0" }); + +// A step's git: its global config is the job's own ~/.gitconfig (empty, as on GitHub), and code that reads +// GIT_CONFIG_GLOBAL as the person's config finds nothing; the root-owned mirror stays trusted through the env. +const stepGitEnv = (config: CiConfig) => ({ GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "safe.directory", GIT_CONFIG_VALUE_0: config.host.mirror }); + +/** + * Checkout-local git config keys that make git run a command. A step can write the checkout's .git/config, and the + * runner's own git (a later `actions/checkout` ref move) runs outside the step's walls, so a planted fsmonitor, filter + * driver, alias or include would run there. The runner sets none of these, so finding one refuses the git call. + */ +const COMMAND_CONFIG = /^(core\.(fsmonitor|sshcommand|pager|editor|askpass|hookspath|gitproxy|alternaterefscommand)|filter\..+|diff\..+\.(command|textconv)|merge\..+\.driver|alias\..+|include\.path|includeif\..+|credential\..*|uploadpack\..+|sequence\.editor|gpg\..*program|.+\.helper)$/i; + +export function plantedGitConfig(localKeys: string[]): string[] { + return localKeys.map((k) => k.trim()).filter((k) => k && COMMAND_CONFIG.test(k)); +} + +/** The runner's git: no hooks and no fsmonitor, whatever the checkout's config says. */ +const RUNNER_GIT = ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false"]; + +/** Runs `git` through `run` after checking the checkout's own config for anything that would execute. */ +function guardedGit(run: (argv: string[]) => Sh, args: string[]): Sh { + // Reading config runs nothing; an absent or unreadable local config lists nothing. + const listed = run(["git", ...RUNNER_GIT, "config", "--local", "--name-only", "--list"]); + const planted = listed.code === 0 ? plantedGitConfig(listed.out.split("\n")) : []; + if (planted.length) return { code: 1, out: "", err: `refused: the checkout's git config sets ${planted.join(", ")}, which a step must have written` }; + return run(["git", ...RUNNER_GIT, ...args]); +} + +/** A value for a systemd EnvironmentFile line: double-quoted, with `\` and `"` escaped (systemd expands nothing). */ +const envLine = (k: string, v: string) => `${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`; + +function pump(stream: NodeJS.ReadableStream, onLine: (l: string) => void) { + let buf = ""; + stream.on("data", (d: Buffer) => { + buf += d.toString("utf-8"); + const parts = buf.split("\n"); + buf = parts.pop() ?? ""; + for (const p of parts) onLine(p); + }); + stream.on("end", () => buf && onLine(buf)); +} + +const RUN_ROLE = /^[a-z_]+\d+_[0-9a-f]{12}_[0-9a-z]+$/; + +export class SlotExecutor implements Executor { + readonly os = "linux" as const; + readonly sandboxed = true; + readonly user: string; + readonly home: string; + readonly opt: string; + private stepSeq = 0; + private pgRole: { role: string; password: string } | null = null; + constructor(readonly config: CiConfig, readonly slot: number, readonly runId: string, readonly slice: string, private onSecret: (name: string, value: string) => void) { + this.user = `${config.host.slot_user}${slot}`; + this.home = `/home/${this.user}`; + this.opt = config.host.opt; + } + private get netns() { return this.user; } + private get state() { return path.join(this.config.host.state, this.runId); } + + basePath() { + return `${this.opt}/git/bin:${this.opt}/node/default/bin:/usr/local/bin:/usr/bin:/bin`; + } + + /** A command as the slot's user, outside any step (the checkout, reading what a step wrote). */ + private asSlot(args: string[], opts: { cwd?: string; timeoutMs?: number } = {}): Sh { + const env = ["env", "-i", `HOME=${this.home}`, `PATH=${this.basePath()}`, ...Object.entries(gitEnv(this.config)).map(([k, v]) => `${k}=${v}`)]; + return sh("runuser", ["-u", this.user, "--", ...env, ...(opts.cwd ? ["sh", "-c", 'cd "$0" && exec "$@"', opts.cwd] : []), ...args], { timeoutMs: opts.timeoutMs }); + } + + git(args: string[], cwd: string, timeoutMs?: number) { + return guardedGit((argv) => this.asSlot(argv, { cwd, timeoutMs }), args); + } + + mkdirs(dirs: string[]) { + this.asSlot(["mkdir", "-p", ...dirs]); + } + + readRunFile(file: string, maxBytes = 8 * 1024 * 1024): string | null { + const r = spawnSync("runuser", ["-u", this.user, "--", "sh", "-c", '[ -f "$1" ] && [ ! -L "$1" ] && exec head -c "$2" -- "$1"', "_", file, String(maxBytes)], { encoding: "utf-8", timeout: 30_000, maxBuffer: maxBytes + 1024 }); + return r.status === 0 ? (r.stdout ?? "") : null; + } + + listRunFiles(dir: string, pattern: string): string[] { + const r = this.asSlot(["find", dir, "-maxdepth", "1", "-type", "f", "-name", pattern, "-printf", "%f\\n"], { timeoutMs: 30_000 }); + return r.code === 0 ? r.out.split("\n").filter((f) => f && !f.includes("/")) : []; + } + + /** Every process of the slot's user, ended by pid (the slot's user runs nothing between runs). */ + private endProcesses() { + for (const p of sh("pgrep", ["-u", this.user]).out.split("\n").filter((x) => /^\d+$/.test(x))) { + try { process.kill(Number(p), "SIGKILL"); } catch {} + } + } + + /** + * The slot's walls, checked before a run: its namespace, the host rules that let it reach only Postgres, the rule + * that keeps its user off the host's own network, and IPv6 off on both ends. A missing one makes the run infra. + */ + wallsMissing(): string | null { + const s = this.slot; + const iface = `ownci-h${s}`; + const peer = `ownci-p${s}`; + if (sh("ip", ["netns", "exec", this.netns, "true"]).code !== 0) return `no network namespace ${this.netns}`; + const rules: Array<[string, string[]]> = [ + ["iptables", ["-C", "INPUT", "-i", iface, "-j", `OWNCI-IN-${s}`]], + ["iptables", ["-C", "FORWARD", "-i", iface, "-j", `OWNCI-FWD-${s}`]], + ["ip6tables", ["-C", "INPUT", "-i", iface, "-j", "REJECT"]], + ["ip6tables", ["-C", "FORWARD", "-i", iface, "-j", "REJECT"]], + ["iptables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.user, "-j", "REJECT"]], + ["ip6tables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.user, "-j", "REJECT"]], + ]; + if (Object.keys(this.config.services).length) { + rules.push(["iptables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.config.host.pg_admin, "-j", "OWNCI-PG-OUT"]]); + rules.push(["ip6tables", ["-C", "OUTPUT", "-m", "owner", "--uid-owner", this.config.host.pg_admin, "-j", "OWNCI-PG-OUT"]]); + } + for (const [tool, rule] of rules) if (sh(tool, rule).code !== 0) return `${tool} rule missing: ${rule.join(" ")}`; + if (sh("cat", [`/proc/sys/net/ipv6/conf/${iface}/disable_ipv6`]).out !== "1") return `IPv6 is on for ${iface}`; + if (sh("ip", ["netns", "exec", this.netns, "cat", `/proc/sys/net/ipv6/conf/${peer}/disable_ipv6`]).out !== "1") return `IPv6 is on for ${peer}`; + if (!existsSync(path.join(this.opt, "git", "bin", "git"))) return `no pinned git at ${this.opt}/git`; + return null; + } + + /** The slot user's home, emptied and made anew (700, owned by the user). */ + freshHome() { + this.endProcesses(); + rmSync(this.home, { recursive: true, force: true }); + mkdirSync(this.home, { mode: 0o700 }); + sh("chown", [`${this.user}:${this.user}`, this.home]); + } + + private psqlAdmin(sql: string, db = "postgres", port = 5440) { + return sh("runuser", ["-u", this.config.host.pg_admin, "--", "psql", "-h", this.config.host.pg_socket, "-p", String(port), "-d", db, "-v", "ON_ERROR_STOP=1", "-Atq", "-f", "-"], { input: sql, timeoutMs: 90_000 }); + } + + /** A run's role and everything it holds: its sessions, its databases, what it owns elsewhere, then the role. */ + dropRole(role: string, port: number) { + if (!RUN_ROLE.test(role)) throw new Error(`not a run role: ${role}`); + this.psqlAdmin(`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename = '${role}'`, "postgres", port); + const owned = this.psqlAdmin(`SELECT d.datname FROM pg_database d JOIN pg_roles r ON r.oid = d.datdba WHERE r.rolname = '${role}'`, "postgres", port); + for (const db of owned.code === 0 ? owned.out.split("\n").filter(Boolean) : []) this.psqlAdmin(`DROP DATABASE IF EXISTS "${db.replace(/"/g, '""')}" WITH (FORCE)`, "postgres", port); + for (const db of ["postgres", "template1"]) this.psqlAdmin(`DO $$ BEGIN IF EXISTS (SELECT FROM pg_roles WHERE rolname = '${role}') THEN EXECUTE 'DROP OWNED BY ${role}'; END IF; END $$`, db, port); + const dropped = this.psqlAdmin(`DROP ROLE IF EXISTS ${role}`, "postgres", port); + if (dropped.code !== 0) throw new Error(`could not drop the run role ${role}: ${dropped.err}`); + } + + /** + * A fresh login role for this run in its slot's group (which pg_hba admits only from the slot's namespace): + * CREATEDB, no superuser, GitHub's 97 connections, a password made now that exists only in this run. The group is + * reset first, and a group that keeps a setting makes the run infra. + */ + private runRole(port: number): { role: string; password: string } { + if (this.pgRole) return this.pgRole; + const group = `${this.config.host.pg_group}${this.slot}`; + this.psqlAdmin(`ALTER ROLE ${group} RESET ALL`, "postgres", port); + const kept = this.psqlAdmin(`SELECT count(*) FROM pg_db_role_setting s JOIN pg_roles r ON r.oid = s.setrole WHERE r.rolname = '${group}'`, "postgres", port); + if (kept.code !== 0 || kept.out.trim() !== "0") throw new Error(`the slot group ${group} keeps settings after RESET ALL (${kept.out || kept.err})`); + const role = `${group}_${this.runId.replace("-", "_")}`; + this.dropRole(role, port); + const password = randomBytes(24).toString("hex"); + this.onSecret("CASTCI_PG_PASSWORD", password); + const made = this.psqlAdmin(`CREATE ROLE ${role} LOGIN CREATEDB NOSUPERUSER NOCREATEROLE NOREPLICATION NOBYPASSRLS CONNECTION LIMIT 97 IN ROLE ${group} PASSWORD '${password}'`, "postgres", port); + if (made.code !== 0) throw new Error(`could not make the run role ${role}: ${made.err.split(password).join("***")}`); + this.pgRole = { role, password }; + return this.pgRole; + } + + postgres(port: number, db: string): string { + if (!/^[a-z0-9_]+$/.test(db)) throw new Error(`not a database name: ${db}`); + const { role, password } = this.runRole(port); + const made = this.psqlAdmin(`CREATE DATABASE "${db}" OWNER ${role}`, "postgres", port); + if (made.code !== 0 && !/already exists/.test(made.err)) throw new Error(`could not make database ${db}: ${made.err}`); + // 127.0.0.1: inside the slot's namespace is forwarded to the CI cluster. + return `postgresql://${role}:${password}@127.0.0.1:${port}/${db}?sslmode=disable`; + } + + bunBin(version: string): string { + return installedTool(path.join(this.opt, "bun"), version, /^[0-9]+\.[0-9]+\.[0-9]+$/, "bun", (tmp) => + sh("bash", ["-c", 'curl -fsSL https://bun.sh/install | BUN_INSTALL="$1" bash -s "bun-v$2" >/dev/null 2>&1', "_", tmp, version], { timeoutMs: 5 * 60_000 })); + } + + nodeBin(major: string): string { + const bin = path.join(this.opt, "node", major, "bin"); + if (!existsSync(path.join(bin, "node"))) throw new Error(`the host has no node ${major} at ${bin}: the CI pool's image provisions it`); + return bin; + } + + ownCopy(bin: string, dest: string): string { + const r = this.asSlot(["sh", "-c", 'mkdir -p "$1" && cp -a "$2"/. "$1"/', "_", dest, bin], { timeoutMs: 120_000 }); + if (r.code !== 0) throw new Error(`could not copy ${bin} for the job: ${r.err}`); + return dest; + } + + runStep(s: StepSpec): Promise { + const n = ++this.stepSeq; + const unit = `ownci-step-${this.runId}-${n}`; + const envFile = path.join(this.state, `${s.key}-${n}.env`); + mkdirSync(path.dirname(envFile), { recursive: true, mode: 0o700 }); + writeFileSync(envFile, `${Object.entries({ ...s.env, ...stepGitEnv(this.config) }).map(([k, v]) => envLine(k, v)).join("\n")}\n`, { mode: 0o600 }); + const left = Math.max(5, Math.ceil((s.deadline - Date.now()) / 1000)); + const h = this.config.host; + // A step's result is its shell's, as on GitHub: what it leaves running is KILLed when the shell exits (KillMode=mixed), + // where systemd's default TERMs it and, when it ignores TERM (a test's leaked daemon), waits 90s and fails the unit. + // systemd ignores SIGPIPE in a unit by default; a GitHub step does not, and a pipeline's writer must die with it. + // A step's /tmp is a tmpfs of its own (GitHub's runners each have a disk; here every runner shares one EBS volume, + // and the tests' scratch repos in /tmp held its IOPS at the cap, stalling workers on the ext4 journal). + const args = [ + "--wait", "--pipe", "--collect", "--quiet", `--unit=${unit}`, `--slice=${this.slice}`, + `--uid=${this.user}`, `--gid=${this.user}`, + "-p", `NetworkNamespacePath=/run/netns/${this.netns}`, + "-p", `BindReadOnlyPaths=${h.resolv}:/run/systemd/resolve/stub-resolv.conf`, + "-p", "TemporaryFileSystem=/tmp:mode=1777,size=12G", "-p", "TemporaryFileSystem=/var/tmp:mode=1777,size=4G", "-p", "PrivateIPC=yes", "-p", "TemporaryFileSystem=/dev/shm:mode=1777", "-p", "TemporaryFileSystem=/run/lock:mode=1777", + "-p", "ProtectHome=tmpfs", "-p", `BindPaths=${this.home}`, + "-p", "ProtectSystem=strict", "-p", `ReadWritePaths=${this.home}`, + "-p", "ProtectProc=invisible", "-p", "NoNewPrivileges=yes", "-p", "IgnoreSIGPIPE=no", "-p", "KillMode=mixed", + "-p", "InaccessiblePaths=-/run/postgresql", "-p", `InaccessiblePaths=-${h.pg_socket}`, "-p", `InaccessiblePaths=-${path.dirname(h.env_file)}`, "-p", `InaccessiblePaths=-${h.state}`, + "-p", "InaccessiblePaths=-/run/dbus", "-p", "InaccessiblePaths=-/run/snapd.socket", "-p", "InaccessiblePaths=-/run/snapd-snap.socket", + "-p", "InaccessiblePaths=-/run/systemd/journal", + "-p", `EnvironmentFile=${envFile}`, "-p", `WorkingDirectory=${s.cwd}`, + "-p", `RuntimeMaxSec=${left + 60}`, + ...(s.cpus ? ["-p", `AllowedCPUs=${s.cpus}`] : []), + ...(s.shell === "bash" ? ["/bin/bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", s.script] : ["/bin/sh", "-e", "-c", s.script]), + ]; + return new Promise((resolve) => { + const child = spawn("systemd-run", args, { stdio: ["ignore", "pipe", "pipe"] }); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + sh("systemctl", ["stop", `${unit}.service`]); + }, left * 1000); + pump(child.stdout!, s.onLine); + pump(child.stderr!, s.onLine); + const done = (code: number) => { + clearTimeout(timer); + rmSync(envFile, { force: true }); + resolve({ code: timedOut ? 124 : code, timedOut }); + }; + child.on("close", (code) => done(code ?? 1)); + child.on("error", (err) => { s.onLine(`##[error]${err.message}`); done(127); }); + }); + } + + cleanup(workDir: string) { + this.endProcesses(); + rmSync(workDir, { recursive: true, force: true }); + const pg = Object.values(this.config.services)[0]; + if (this.pgRole && pg) this.dropRole(this.pgRole.role, pg.port); + rmSync(this.state, { recursive: true, force: true }); + } +} + +/** A tool pinned by version under `root//bin`, installed once (root-owned, readable) and shared by runs. */ +function installedTool(root: string, version: string, valid: RegExp, binName: string, install: (tmp: string) => Sh): string { + if (!valid.test(version)) throw new Error(`not a ${binName} version: ${version.slice(0, 40)}`); + const dir = path.join(root, version); + const bin = path.join(dir, "bin"); + const linkBunx = (b: string) => binName === "bun" && sh("ln", ["-sfn", "bun", path.join(b, "bunx")]); + if (existsSync(path.join(bin, binName))) { + if (binName === "bun" && !existsSync(path.join(bin, "bunx"))) linkBunx(bin); + return bin; + } + const tmp = `${dir}.tmp-${process.pid}`; + rmSync(tmp, { recursive: true, force: true }); + mkdirSync(root, { recursive: true }); + const r = install(tmp); + if (r.code !== 0 || !existsSync(path.join(tmp, "bin", binName))) throw new Error(`could not install ${binName} ${version}: ${r.err.slice(-300)}`); + linkBunx(path.join(tmp, "bin")); + sh("chmod", ["-R", "a+rX", tmp]); + try { renameSync(tmp, dir); } catch { rmSync(tmp, { recursive: true, force: true }); } + return bin; +} + +/** A runner's environment on the person's own machine: a temp HOME, no walls. */ +export class LocalExecutor implements Executor { + readonly sandboxed = false; + readonly slot = 0; + readonly user = os.userInfo().username; + readonly home: string; + readonly opt = null; + readonly os: JobOs; + constructor(readonly config: CiConfig, root?: string) { + this.home = root ?? mkdtempSync(path.join(os.tmpdir(), "castci-home-")); + this.os = process.platform === "darwin" ? "darwin" : "linux"; + } + basePath() { + return ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(":"); + } + git(args: string[], cwd: string, timeoutMs?: number) { + const env = { HOME: this.home, PATH: this.basePath(), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0" }; + return guardedGit(([cmd, ...rest]) => sh(cmd!, rest, { cwd, timeoutMs, env }), args); + } + mkdirs(dirs: string[]) { + for (const d of dirs) mkdirSync(d, { recursive: true }); + } + readRunFile(file: string, maxBytes = 8 * 1024 * 1024): string | null { + try { + const st = statSync(file, { throwIfNoEntry: false } as any); + if (!st || !st.isFile()) return null; + return readFileSync(file).subarray(0, maxBytes).toString("utf-8"); + } catch { + return null; + } + } + listRunFiles(dir: string, pattern: string): string[] { + const re = new RegExp(`^${pattern.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`); + try { + return readdirSync(dir).filter((f) => re.test(f) && statSync(path.join(dir, f)).isFile()); + } catch { + return []; + } + } + bunBin(version: string): string { + if (version === Bun.version) return path.dirname(process.execPath.endsWith("/bun") ? process.execPath : sh("which", ["bun"]).out || "/usr/local/bin/bun"); + return installedTool(path.join(os.homedir(), ".cache", "castci", "bun"), version, /^[0-9]+\.[0-9]+\.[0-9]+$/, "bun", (tmp) => + sh("bash", ["-c", 'curl -fsSL https://bun.sh/install | BUN_INSTALL="$1" bash -s "bun-v$2" >/dev/null 2>&1', "_", tmp, version], { timeoutMs: 5 * 60_000 })); + } + nodeBin(major: string): string { + const node = sh("node", ["--version"]).out.replace(/^v/, ""); + if (node.split(".")[0] !== major) throw new Error(`this machine has node ${node || "(none)"}, the job pins ${major}`); + return path.dirname(sh("which", ["node"]).out); + } + ownCopy(bin: string): string { + return bin; + } + runStep(s: StepSpec): Promise { + const left = Math.max(5, Math.ceil((s.deadline - Date.now()) / 1000)); + return new Promise((resolve) => { + const argv = s.shell === "bash" ? ["--noprofile", "--norc", "-e", "-o", "pipefail", "-c", s.script] : ["-e", "-c", s.script]; + const child = spawn(s.shell === "bash" ? "/bin/bash" : "/bin/sh", argv, { cwd: s.cwd, env: s.env, stdio: ["ignore", "pipe", "pipe"], detached: true }); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + try { process.kill(-child.pid!, "SIGKILL"); } catch {} + }, left * 1000); + pump(child.stdout!, s.onLine); + pump(child.stderr!, s.onLine); + child.on("close", (code) => { clearTimeout(timer); resolve({ code: timedOut ? 124 : (code ?? 1), timedOut }); }); + child.on("error", (err) => { clearTimeout(timer); s.onLine(`##[error]${err.message}`); resolve({ code: 127, timedOut: false }); }); + }); + } + cleanup(workDir: string) { + rmSync(workDir, { recursive: true, force: true }); + } +} + +/** A step's log, each line stamped and workflow commands shown the way a GitHub job log shows them. */ +export class JobLog { + private out: ReturnType; + constructor(readonly file: string, private masker: (t: string) => string) { + mkdirSync(path.dirname(file), { recursive: true }); + this.out = createWriteStream(file, { flags: "a" }); + } + line(text: string) { + for (const l of this.masker(text).split(/\r?\n/)) { + const m = /^::(group|endgroup|error|warning|notice|debug)(?: [^:]*)?::(.*)$/.exec(l); + this.out.write(`${new Date().toISOString()} ${m ? `##[${m[1]}]${m[2]}` : l}\n`); + } + } + close(): Promise { + return new Promise((resolve) => this.out.end(resolve)); + } +} diff --git a/packages/cli/src/ciRun/run.test.ts b/packages/cli/src/ciRun/run.test.ts new file mode 100644 index 0000000000..51f2086a7b --- /dev/null +++ b/packages/cli/src/ciRun/run.test.ts @@ -0,0 +1,235 @@ +// The runner end to end on this machine (LocalExecutor, no sandbox): a fixture repository whose ci.yml uses what +// codecast's and Union's do (needs, job outputs feeding an `if:`, a matrix, a local composite action, event and +// matrix conditions, a darwin job, a secret, verify reading needs.*.result), run for a push and for a pull request. +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { parseCiConfig, type CiConfig } from "@codecast/shared/contracts/ciConfig"; +import { runCi } from "./command.js"; +import { LocalExecutor, sh } from "./executor.js"; +import { Masker, maskForms, mask } from "./mask.js"; +import { jobHash, parseCommandFile, runCommit, runConclusion, runnerCpus, runnerName } from "./run.js"; + +const tmp = mkdtempSync(path.join(os.tmpdir(), "castci-test-")); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +const CI_YML = ` +name: CI +on: + push: { branches: [main] } + pull_request: { branches: [main] } +env: + TOP: top +jobs: + gate: + runs-on: ubuntu-latest + outputs: + go: \${{ steps.g.outputs.go }} + steps: + - uses: actions/checkout@v4 + - id: g + run: echo "go=true" >> "$GITHUB_OUTPUT" + work: + needs: gate + if: needs.gate.outputs.go == 'true' + runs-on: ubuntu-latest + strategy: + matrix: + n: [1, 2] + name: work (\${{ matrix.n }}) + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/hello + with: + who: \${{ matrix.n }} + - name: Env and secret + run: test "$TOP" = top && test "$FROM_ACTION" = "hi-\${{ matrix.n }}" && echo "secret=$TOKEN" && echo "b64=$(printf %s "$TOKEN" | base64)" + env: + TOKEN: \${{ secrets.TOKEN }} + - name: Install tmux + run: exit 9 + - name: Fail on two + if: matrix.n == 2 + run: exit 3 + - name: After a failure + run: echo should-not-run + pr-only: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - run: test "$(git rev-parse HEAD~1)" = "$BASE" + env: + BASE: \${{ github.event.pull_request.base.sha }} + mac: + runs-on: macos-15 + steps: + - run: "true" + verify: + needs: [gate, work] + if: always() + runs-on: ubuntu-latest + steps: + - run: '[ "\${{ needs.work.result }}" = failure ] && [ "\${{ needs.gate.result }}" = success ]' +`; + +const ACTION = ` +name: hello +inputs: + who: + default: nobody +runs: + using: composite + steps: + - shell: bash + run: echo "FROM_ACTION=hi-\${{ inputs.who }}" >> "$GITHUB_ENV" +`; + +const SECRET = "s3cr3t-value-for-the-test"; + +function fixture(name = "repo"): { dir: string; base: string; head: string } { + const dir = path.join(tmp, name); + mkdirSync(path.join(dir, ".github", "workflows"), { recursive: true }); + mkdirSync(path.join(dir, ".github", "actions", "hello"), { recursive: true }); + const g = (...a: string[]) => { + const r = sh("git", ["-C", dir, "-c", "user.name=t", "-c", "user.email=t@t", ...a]); + if (r.code !== 0) throw new Error(r.err); + return r.out; + }; + g("init", "-q", "-b", "main"); + writeFileSync(path.join(dir, "README.md"), "x\n"); + g("add", "."); + g("commit", "-qm", "base"); + const base = g("rev-parse", "HEAD"); + writeFileSync(path.join(dir, ".github", "workflows", "ci.yml"), CI_YML); + writeFileSync(path.join(dir, ".github", "actions", "hello", "action.yml"), ACTION); + g("add", "."); + g("commit", "-qm", "ci"); + return { dir, base, head: g("rev-parse", "HEAD") }; +} + +const config = (): CiConfig => { + const p = parseCiConfig({ repository: "o/fixture", secrets: { TOKEN: { jobs: ["work"] } }, skip_steps: { "Install tmux": "the host has it" }, parallel_jobs: 2 }); + if ("problems" in p) throw new Error(p.problems.join("; ")); + return p.config; +}; + +async function run(event: "push" | "pull_request", f: ReturnType) { + const masker = new Masker(); + masker.add("TOKEN", SECRET); + const out = path.join(tmp, `out-${event}`); + const r = await runCommit({ + repository: "o/fixture", sha: f.head, event, ...(event === "pull_request" ? { base: f.base, headRef: "feature" } : {}), + source: path.join(f.dir, ".git"), out, id: `${f.head.slice(0, 12)}-${event === "push" ? "a1" : "b2"}`, host: "test-host", lane: "linux", + config: config(), secrets: { TOKEN: SECRET }, executor: new LocalExecutor(config(), path.join(tmp, `home-${event}`)), masker, + }); + return { r, out }; +} + +describe("a commit's CI, run from its own ci.yml", () => { + const f = fixture(); + + test("a push runs the lane's jobs in needs order, with outputs, matrix, composite actions and verify", async () => { + // The PR job has no base on a push, so give the push its own fixture's first parent as before. + const { r, out } = await run("push", f); + if (!r.triggered) throw new Error(r.why); + const v = r.verdict; + expect(v.jobs.map((j) => [j.name, j.conclusion])).toEqual([ + ["gate", "success"], + ["work.1", "success"], + ["work.2", "failure"], + ["pr-only", "skipped"], + ["verify", "success"], + ]); + expect(v.status).toBe("completed"); + expect(v.conclusion).toBe("failure"); + expect(v.jobs.find((j) => j.name === "work.2")!.note).toBe("Fail on two: failed"); + const log = readFileSync(path.join(out, "jobs", "work.1.log"), "utf-8"); + expect(log).toContain("secret=***"); + expect(log).not.toContain(SECRET); + expect(log).not.toContain(Buffer.from(SECRET).toString("base64").slice(4, 20)); + expect(log).toContain("Install tmux: left out (the host has it)"); + expect(readFileSync(path.join(out, "jobs", "work.2.log"), "utf-8")).not.toContain("should-not-run"); + // The darwin job belongs to the darwin lane's verdict, not this one. + expect(v.jobs.some((j) => j.name === "mac")).toBe(false); + expect(JSON.parse(readFileSync(path.join(out, "verdict.json"), "utf-8")).conclusion).toBe("failure"); + }, 60_000); + + test("a pull request runs on the merge of the head onto the base, and runs its PR-only job", async () => { + const { r } = await run("pull_request", f); + if (!r.triggered) throw new Error(r.why); + expect(r.verdict.kind).toBe("landing"); + expect(r.verdict.jobs.find((j) => j.name === "pr-only")!.conclusion).toBe("success"); + }, 60_000); +}); + +describe("the pieces", () => { + test("GITHUB_OUTPUT and GITHUB_ENV files, heredocs included", () => { + expect(parseCommandFile("a=1\nb< { + const j = (job: string, conclusion: any, counts = true) => ({ job, name: job, counts, conclusion, seconds: 0, failing: [] }); + expect(runConclusion([j("a", "infra"), j("verify", "failure")], (job) => job === "verify")).toBe("infra"); + expect(runConclusion([j("a", "failure"), j("verify", "failure")], () => false)).toBe("failure"); + expect(runConclusion([j("a", "failure", false), j("verify", "success")], () => false)).toBe("success"); + }); + + test("verdict job names keep the contract's characters", () => { + expect(runnerName("test-cli", { part: "1/3" }, true)).toBe("test-cli.1-3"); + expect(runnerName("typecheck", { key: "web", programs: "web" }, true)).toBe("typecheck.web-web"); + expect(runnerName("lint", {}, false)).toBe("lint"); + }); + + test("a secret is masked in its parts and encodings", () => { + const url = "postgresql://role:pa55word-xyz@127.0.0.1:5440/db?sslmode=disable"; + const forms = maskForms({ DATABASE_URL: url, KEY: SECRET }); + expect(mask(`u=${url} pw=pa55word-xyz enc=${encodeURIComponent(SECRET)} hex=${Buffer.from(SECRET).toString("hex")}`, forms)).toBe("u=*** pw=*** enc=*** hex=***"); + expect(maskForms({ REGION: "us-west-2" }, (n) => n === "REGION")).toEqual([]); + }); + + test("a mirrored job's hash is Union's: its definition with keys sorted", () => { + expect(jobHash({ b: 1, a: { d: 2, c: 3 } })).toBe(jobHash({ a: { c: 3, d: 2 }, b: 1 })); + expect(jobHash({ a: 1 })).toMatch(/^[0-9a-f]{12}$/); + }); +}); + +describe("runnerCpus", () => { + test("splits the host's cores evenly between a run's concurrent runners, none shared", () => { + expect([0, 1, 2, 3].map((r) => runnerCpus(r, 4, 16))).toEqual(["0-3", "4-7", "8-11", "12-15"]); + expect(runnerCpus(2, 3, 16)).toBe("10-14"); + }); + test("a single runner, or more runners than cores, keeps the whole host", () => { + expect(runnerCpus(0, 1, 16)).toBeUndefined(); + expect(runnerCpus(0, 8, 4)).toBeUndefined(); + }); +}); + +describe("cast ci run into a verdict directory a run already used", () => { + test("the second run's logs hold only its own lines", async () => { + const f = fixture("repo-again"); + const toml = path.join(tmp, "ci.toml"); + writeFileSync(toml, 'repository = "o/fixture"\nparallel_jobs = 2\n[skip_steps]\n"Install tmux" = "the host has it"\n[secrets.TOKEN]\njobs = ["work"]\n'); + const out = path.join(tmp, "out-again"); + const deps = { readVault: async () => ({}), record: async () => ({ written: false }), repositoryOf: () => "o/fixture", log: () => {} }; + const opts = { repo: f.dir, unsandboxed: true, out, record: false, config: toml, os: "linux" as const }; + await runCi(f.head, opts, deps); + await runCi(f.head, opts, deps); + const log = readFileSync(path.join(out, "jobs", "work.1.log"), "utf-8"); + expect(log.match(/##\[group\]codecast CI:/g)?.length).toBe(1); + }, 120_000); +}); + +describe("what a run will not trust from the commit", () => { + test("a job id outside GitHub's rule (one that could reach outside the log directory) is refused", async () => { + const { badJobIds } = await import("./run.js"); + expect(badJobIds(["test", "test-web", "_x", "a_b-2"])).toEqual([]); + expect(badJobIds(["../etc/passwd", "a/b", "1job", "", "x y"])).toEqual(["../etc/passwd", "a/b", "1job", "", "x y"]); + }); + + test("checkout config that would make the runner's git run a command is found", async () => { + const { plantedGitConfig } = await import("./executor.js"); + expect(plantedGitConfig(["core.repositoryformatversion", "core.bare", "remote.origin.url", "remote.origin.fetch", "extensions.worktreeconfig"])).toEqual([]); + expect(plantedGitConfig(["core.fsmonitor", "filter.x.smudge", "diff.y.textconv", "alias.st", "include.path", "includeIf.gitdir:/x.path", "credential.helper", "core.sshCommand"]).length).toBe(8); + }); +}); diff --git a/packages/cli/src/ciRun/run.ts b/packages/cli/src/ciRun/run.ts new file mode 100644 index 0000000000..c2b379fb0a --- /dev/null +++ b/packages/cli/src/ciRun/run.ts @@ -0,0 +1,652 @@ +// One commit's CI on one host: the jobs the commit's own ci.yml runs for its push or pull_request event, on this +// host's OS lane, with what .codecast/ci.toml adds. The result is one verdict directory (`verdict.json` and +// `jobs/.log`, contract v1 in shared/contracts/ciVerdict.ts) that `cast ci record` stores. +// +// Jobs run in `needs` order, as GitHub runs them: a job starts when what it needs has finished and its `if:` holds +// (ciWorkflow.jobStarts); its matrix runners start up to ci.toml's parallel_jobs at once, each in a checkout of its +// own; a job's `outputs` (code_paths' flags) feed the conditions of what comes after; `verify`'s `needs.*.result` +// sees what GitHub's would. Steps come from the commit's ci.yml, `uses:` resolved here: checkout is ours, setup-bun +// and setup-node pin tools, local composite actions expand into their steps, caches and artifact uploads are left +// out (a cache only saves time), and any other action is infra unless ci.toml says how to run or skip it. A job +// ci.toml mirrors by hand runs its listed steps and carries a hash of its ci.yml definition: when the commit's +// definition hashes differently the verdict says so on that job. + +import { createHash } from "node:crypto"; +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { gzipSync } from "node:zlib"; +import { canonicalJson, jobSecrets, type CiConfig } from "@codecast/shared/contracts/ciConfig"; +import { parseFailures, type CiFailure } from "@codecast/shared/contracts/ciFailures"; +import type { RunnerJobConclusion, RunnerVerdict, RunnerVerdictJob } from "@codecast/shared/contracts/ciVerdict"; +import { + baseContext, condition, expandMatrix, ExprError, foldResults, jobDisplayName, jobOrder, jobStarts, needsContext, needsOf, + resolveValue, interpolate, runnerOs, truthy, workflowTriggers, + type ExprContext, type JobOs, type JobResult, type Matrix, type NeedsState, type RunFacts, type Workflow, type WorkflowJob, type WorkflowStep, +} from "@codecast/shared/contracts/ciWorkflow"; +import { JobLog, type Executor } from "./executor.js"; +import type { Masker } from "./mask.js"; +import { mintAppToken } from "./githubApp.js"; + +export type RunInput = { + repository: string; + sha: string; + event: "push" | "pull_request"; + /** A push's previous head (github.event.before); its first parent when not given. */ + before?: string; + /** A pull request's base (main's tip it merges onto). */ + base?: string; + /** A landing candidate's branch name (github.head_ref). */ + headRef?: string; + /** Where checkouts clone from: the host's bare mirror, or a local repository. */ + source: string; + out: string; + id: string; + host: string; + lane: JobOs; + config: CiConfig; + /** Every secret value the runner may hand out; each job gets only those ci.toml grants it. */ + secrets: Record; + executor: Executor; + masker: Masker; + /** Only these jobs (and what they need); the verdict is then partial and never recorded as the sha's. */ + only?: string[]; + say?: (line: string) => void; + /** Called whenever the verdict changes (a heartbeat records it). */ + onVerdict?: (v: RunnerVerdict) => void; +}; + +export type RunOutcome = { triggered: false; why: string } | { triggered: true; verdict: RunnerVerdict }; + +const ZERO = "0000000000000000000000000000000000000000"; +const repoName = (repository: string) => repository.split("/")[1]!; + +/** A verdict job name (contract: [\w.-]+) for one runner: the job id, then its matrix values. */ +export function runnerName(job: string, matrix: Matrix, many: boolean): string { + if (!many) return job; + const flat = (v: unknown): string => (v && typeof v === "object" ? Object.values(v).map(flat).join("-") : String(v)); + return `${job}.${Object.values(matrix).map(flat).join("-").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "")}`; +} + +/** $GITHUB_OUTPUT / $GITHUB_ENV text: `k=v` lines and `k< { + const out: Record = {}; + const lines = text.split("\n"); + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!; + const heredoc = /^([^=<\s]+)<<(.+)$/.exec(line); + if (heredoc) { + const body: string[] = []; + for (i++; i < lines.length && lines[i] !== heredoc[2]; i++) body.push(lines[i]!); + out[heredoc[1]!] = body.join("\n"); + continue; + } + const eq = line.indexOf("="); + if (eq > 0) out[line.slice(0, eq)] = line.slice(eq + 1); + } + return out; +} + +/** + * The run's conclusion. A counted job that failed on its own (none of what it needs was infra) makes it red. A + * counted job the runner could not run, or one that failed only because something it needs was infra (verify + * after an infra job), makes it infra: the runner's failure, never the commit's. Otherwise green. + */ +export function runConclusion(jobs: Array, needsInfra: (job: string) => boolean): "success" | "failure" | "infra" { + const counted = jobs.filter((j) => j.counts); + if (counted.some((j) => j.conclusion === "failure" && !needsInfra(j.job))) return "failure"; + if (counted.some((j) => j.conclusion === "infra" || (j.conclusion === "failure" && needsInfra(j.job)))) return "infra"; + return "success"; +} + +type StepRecord = { outputs: Record; outcome: string; conclusion: string }; +type RunnerResult = { conclusion: RunnerJobConclusion; note?: string; outputs: Record; failing?: CiFailure[] }; + +class Infra extends Error {} + +/** GitHub's own rule for a job id. A job id names its log file, which the runner writes outside the sandbox. */ +const JOB_ID = /^[A-Za-z_][A-Za-z0-9_-]*$/; +export function badJobIds(jobIds: string[]): string[] { + return jobIds.filter((id) => !JOB_ID.test(id)); +} + + +/** The checkout a runner works in, as the run user: a clone sharing the source's objects, at the commit GitHub would check out. */ +function checkout(ex: Executor, input: RunInput, dir: string): { root: string; headSha: string } | { refused: string } | { conflicts: string[] } { + const root = path.join(dir, repoName(input.repository)); + ex.mkdirs([dir]); + const clone = ex.git(["clone", "-q", "--shared", "--no-checkout", input.source, root], dir, 10 * 60_000); + if (clone.code !== 0) throw new Infra(`clone: ${clone.err}`); + if (input.event === "push") { + const co = ex.git(["checkout", "-q", "--detach", input.sha], root); + if (co.code !== 0) throw new Infra(`checkout ${input.sha}: ${co.err}`); + // GitHub's checkout of a push fetches the pushed sha as origin/main: for the commit's own tests origin/main is + // that commit, never a later main. + const ref = ex.git(["update-ref", `refs/remotes/origin/${input.config.branch}`, input.sha], root); + if (ref.code !== 0) throw new Infra(`origin/${input.config.branch}: ${ref.err}`); + return { root, headSha: input.sha }; + } + // A pull request runs on GitHub's merge ref: the head merged onto the base, so HEAD~1 is the base's tip. + const base = input.base!; + if (ex.git(["update-ref", `refs/remotes/origin/${input.config.branch}`, base], root).code !== 0) throw new Infra(`no base ${base} in the mirror`); + const co = ex.git(["checkout", "-q", "--detach", base], root); + if (co.code !== 0) throw new Infra(`checkout ${base}: ${co.err}`); + if (ex.git(["merge-base", "--is-ancestor", input.sha, base], root).code === 0) return { refused: `${input.sha.slice(0, 10)} is already on ${input.config.branch}: nothing to land` }; + const merge = ex.git(["-c", "user.name=codecast CI", "-c", "user.email=ci@codecast.sh", "merge", "--no-ff", "--no-edit", "-q", input.sha], root); + if (merge.code !== 0) { + const files = ex.git(["diff", "--name-only", "--diff-filter=U"], root).out.split("\n").filter(Boolean); + if (!files.length) throw new Infra(`merge onto ${input.config.branch}: ${merge.err || merge.out}`); + return { conflicts: files }; + } + return { root, headSha: ex.git(["rev-parse", "HEAD"], root).out }; +} + +/** The commit's own ci.yml (read as the run user from a checkout of it) and the files the event changed. */ +function readCommit(ex: Executor, input: RunInput, root: string): { workflow: Workflow; changed: string[] | null; before: string } { + const text = ex.readRunFile(path.join(root, input.config.workflow), 1024 * 1024); + if (text === null) throw new Infra(`${input.config.workflow} is not a regular file in this commit`); + const workflow = Bun.YAML.parse(text) as Workflow; + if (!workflow?.jobs || typeof workflow.jobs !== "object") throw new Infra(`${input.config.workflow} has no jobs`); + const before = input.event === "push" ? (input.before ?? (ex.git(["rev-parse", "--verify", "-q", `${input.sha}^`], root).out || ZERO)) : input.base!; + const from = input.event === "push" ? before : ex.git(["merge-base", input.base!, input.sha], root).out; + if (!from || from === ZERO) return { workflow, changed: null, before }; + const diff = ex.git(["diff", "--name-only", "--no-renames", from, input.sha], root); + return { workflow, changed: diff.code === 0 ? diff.out.split("\n").filter(Boolean) : null, before }; +} + +export async function runCommit(input: RunInput): Promise { + const { executor: ex, config, masker } = input; + const say = (l: string) => input.say?.(masker.apply(l)); + // GitHub's layout is work//: the failure parser strips exactly two levels under work/, so each checkout + // sits at work/./. The slot is this run's alone, and its home is wiped at every start. + const work = path.join(ex.home, "work"); + mkdirSync(path.join(input.out, "jobs"), { recursive: true }); + const verdict: RunnerVerdict = { + version: 1, + repository: input.repository, + sha: input.sha, + name: `${input.lane === "linux" ? config.name : `${config.name}-${input.lane}`}${input.only ? "-partial" : ""}`, + kind: input.event === "push" ? "main" : "landing", + host: input.host, + run_id: `castci-${input.id}`, + started_at: Date.now(), + status: "in_progress", + jobs: [], + }; + const write = () => { + const tmp = path.join(input.out, `.verdict.json.${process.pid}`); + writeFileSync(tmp, `${masker.apply(JSON.stringify(verdict, null, 2))}\n`); + renameSync(tmp, path.join(input.out, "verdict.json")); + input.onVerdict?.(verdict); + }; + const results = new Map(); + const record = (j: RunnerVerdictJob & { job: string; order: number }) => { + results.set(j.name, j); + verdict.jobs = [...results.values()].sort((a, b) => a.order - b.order).map(({ job: _j, order: _o, ...rest }) => rest); + write(); + say(`${j.name}: ${j.conclusion}${j.note ? ` (${j.note})` : ""}`); + }; + write(); + + let infraJobs = new Set(); + let workflow: Workflow | null = null; + try { + const probe = checkout(ex, input, path.join(work, `${input.id}._plan`)); + if ("refused" in probe) throw new Infra(probe.refused); + if ("conflicts" in probe) { + const note = `conflicts with ${config.branch}: ${probe.conflicts.join(", ")}`.slice(0, 2000); + writeFileSync(path.join(input.out, "jobs", "merge.log"), masker.apply(`${new Date().toISOString()} ##[error]${note}\n`)); + record({ job: "merge", order: 0, name: "merge", counts: true, conclusion: "failure", seconds: 0, failing: [{ job: "merge", test: `merge onto ${config.branch}`, assertion: note, file: null, line: null, excerpt: note }], log: "jobs/merge.log", note }); + verdict.conclusion = "failure"; + return { triggered: true, verdict: finish() }; + } + const commit = readCommit(ex, input, probe.root); + workflow = commit.workflow; + const trig = workflowTriggers(workflow, input.event, { branch: config.branch, changed: commit.changed }); + if (!trig.runs && !input.only) return { triggered: false, why: trig.why }; + const facts: RunFacts = { + event: input.event, + repository: input.repository, + sha: probe.headSha, + branch: config.branch, + before: commit.before, + ...(input.event === "pull_request" ? { pullRequest: { baseSha: input.base!, headSha: input.sha, baseRef: config.branch, headRef: input.headRef ?? "" } } : {}), + os: input.lane, + }; + infraJobs = await runJobs(input, workflow, facts, work, record, say); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + say(`the runner broke: ${msg}`); + writeFileSync(path.join(input.out, "jobs", "runner.log"), masker.apply(`${new Date().toISOString()} ${err instanceof Error ? (err.stack ?? msg) : msg}\n`), { flag: "a" }); + verdict.conclusion = "infra"; + } finally { + try { ex.cleanup(work); } catch (err) { say(`cleanup: ${err instanceof Error ? err.message : String(err)}`); } + } + if (!verdict.conclusion) { + const wf = workflow!; + const ancestors = (job: string): string[] => { const out = new Set(); const walk = (j: string) => { for (const n of needsOf(wf.jobs[j] ?? {})) if (!out.has(n)) { out.add(n); walk(n); } }; walk(job); return [...out]; }; + verdict.conclusion = runConclusion([...results.values()], (job) => ancestors(job).some((a) => infraJobs.has(a))); + } + return { triggered: true, verdict: finish() }; + + function finish(): RunnerVerdict { + verdict.status = "completed"; + verdict.finished_at = Date.now(); + write(); + say(`${input.sha.slice(0, 10)}: ${verdict.conclusion} in ${Math.round((verdict.finished_at - verdict.started_at) / 1000)}s`); + return verdict; + } +} + +/** Every job of the lane, in needs order and up to parallel_jobs runners at once. Returns the jobs that ended infra. */ +async function runJobs( + input: RunInput, + workflow: Workflow, + facts: RunFacts, + work: string, + record: (j: RunnerVerdictJob & { job: string; order: number }) => void, + say: (l: string) => void, +): Promise> { + const { config } = input; + const order = jobOrder(workflow); + const bad = badJobIds(order); + if (bad.length) throw new Infra(`ci.yml job ids ${bad.map((b) => JSON.stringify(b)).join(", ")} break GitHub's rule (a letter or _, then letters, digits, _ or -)`); + const ctx0 = baseContext(workflow, facts); + const osOf = (id: string): JobOs | null => config.jobs[id]?.os ?? runnerOs(workflow.jobs[id]!["runs-on"]); + // The lane's own jobs, and what they need wherever it would run on GitHub: a need runs here, without counting. + const wanted = order.filter((id) => (input.only ? input.only.includes(id) : osOf(id) === input.lane)); + const lane = new Set(); + const add = (id: string) => { if (lane.has(id)) return; lane.add(id); for (const n of needsOf(workflow.jobs[id]!)) add(n); }; + wanted.forEach(add); + const own = new Set(wanted); + + const state: NeedsState = {}; + const infra = new Set(); + const started = new Set(); + // Each concurrent runner holds one of parallel_jobs runner indexes: its own cores and its own ports. + const free = Array.from({ length: config.parallel_jobs }, (_, i) => config.parallel_jobs - 1 - i); + const waiters: Array<() => void> = []; + const take = async () => { while (free.length === 0) await new Promise((r) => waiters.push(r)); return free.pop()!; }; + const give = (i: number) => { free.push(i); waiters.shift()?.(); }; + + const runJob = async (id: string) => { + const job = workflow.jobs[id]!; + const c = config.jobs[id] ?? {}; + const index = order.indexOf(id) * 1000; + const ownNote = own.has(id) ? undefined : `run on ${input.lane} as a need of this lane's jobs`; + const skippedEntry = (note: string) => { + const log = `jobs/${id}.log`; + writeFileSync(path.join(input.out, log), `${new Date().toISOString()} ${note}\n`); + record({ job: id, order: index, name: id, counts: false, conclusion: "skipped", seconds: 0, failing: [], log, note }); + }; + let starts: boolean; + try { + starts = jobStarts(workflow, id, state, ctx0); + } catch (err) { + starts = false; + infra.add(id); + record({ job: id, order: index, name: id, counts: true, conclusion: "infra", seconds: 0, failing: [], note: `if: ${err instanceof Error ? err.message : String(err)}` }); + state[id] = { result: "failure", outputs: {} }; + return; + } + if (!starts) { + state[id] = { result: "skipped", outputs: {} }; + skippedEntry(job.if !== undefined ? `skipped: if: ${String(job.if)}` : "skipped: a job it needs did not succeed"); + return; + } + if (c.skip) { + state[id] = { result: "skipped", outputs: {} }; + skippedEntry(`not run by codecast's runner: ${c.skip}`); + return; + } + const jctx: ExprContext = { ...ctx0, needs: needsContext(job, state) }; + let matrices: Matrix[]; + try { + matrices = expandMatrix(job.strategy?.matrix, jctx); + } catch (err) { + infra.add(id); + state[id] = { result: "failure", outputs: {} }; + record({ job: id, order: index, name: id, counts: true, conclusion: "infra", seconds: 0, failing: [], note: `matrix: ${err instanceof Error ? err.message : String(err)}` }); + return; + } + const many = !!job.strategy?.matrix; + const outcomes = await Promise.all(matrices.map(async (matrix, k) => { + const runner = await take(); + try { + const name = runnerName(id, matrix, many); + const mctx = { ...jctx, matrix }; + const counts = own.has(id) && (c.counts ?? !truthy(resolveValue(job["continue-on-error"] ?? false, mctx))); + const t0 = Date.now(); + const log = `jobs/${name}.log`; + const jl = new JobLog(path.join(input.out, log), input.masker.apply); + const display = jobDisplayName(id, job, matrix, mctx); + jl.line(`##[group]codecast CI: ${display} on ${input.host} (${input.executor.sandboxed ? `slot ${input.executor.slot}` : "unsandboxed"})`); + jl.line("##[endgroup]"); + let r: RunnerResult; + try { + r = await runRunner(input, workflow, id, job, matrix, k, runner, mctx, path.join(work, `${input.id}.${name}`), jl, t0); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + jl.line(`##[error]codecast's runner could not run this job: ${msg}`); + r = { conclusion: "infra", note: `runner: ${msg}`.slice(0, 300), outputs: {} }; + } + await jl.close(); + const text = readFileSync(path.join(input.out, log), "utf-8"); + const failing = r.conclusion === "failure" ? (r.failing ?? parseFailures(name, text)) : []; + const note = [ownNote, r.note].filter(Boolean).join("; ") || undefined; + record({ job: id, order: index + k, name, counts, conclusion: r.conclusion, seconds: Math.round((Date.now() - t0) / 1000), failing, log, ...(note ? { note } : {}) }); + return r; + } finally { + give(runner); + } + })); + if (outcomes.some((o) => o.conclusion === "infra")) infra.add(id); + const folded = foldResults(outcomes.map((o): JobResult => (o.conclusion === "success" ? "success" : o.conclusion === "skipped" ? "skipped" : "failure"))); + state[id] = { result: folded, outputs: Object.assign({}, ...outcomes.map((o) => o.outputs)) }; + say(`${id}: ${folded}`); + }; + + // Start each job once everything it needs has a result; jobs whose needs are ready run side by side. + const running = new Map>(); + while (started.size < lane.size) { + const ready = order.filter((id) => lane.has(id) && !started.has(id) && needsOf(workflow.jobs[id]!).every((n) => n in state)); + for (const id of ready) { + started.add(id); + running.set(id, runJob(id).finally(() => running.delete(id))); + } + if (running.size === 0) break; + await Promise.race(running.values()); + } + await Promise.all(running.values()); + return infra; +} + +/** + * The cores one of a run's concurrent runners may use (systemd AllowedCPUs), as GitHub gives each job a runner of its + * own: a test script sizes itself to nproc, and four jobs each sized to the whole host starve each other's deadline + * and timeout tests. Undefined when there is no host to split. + */ +export function runnerCpus(runner: number, parallel: number, cores: number): string | undefined { + const per = Math.floor(cores / parallel); + if (parallel <= 1 || per < 1) return undefined; + return `${runner * per}-${runner * per + per - 1}`; +} + +const SKIPPED_ACTIONS: Record = { + "actions/cache": "a cache only saves time", + "actions/cache/restore": "a cache only saves time", + "actions/cache/save": "a cache only saves time", + "actions/upload-artifact": "artifacts stay on the host (the log and kept files go with the verdict)", + "actions/download-artifact": "artifacts stay on the host", +}; + +/** The mirror hash of a ci.yml job: its YAML, keys sorted, as JSON, sha256, 12 hex (Union's MIRRORED_JOBS rule). */ +export const jobHash = (job: unknown) => createHash("sha256").update(canonicalJson(job)).digest("hex").slice(0, 12); + +/** One matrix runner of a job: its checkout, its steps in order, its outputs. */ +async function runRunner(input: RunInput, workflow: Workflow, id: string, job: WorkflowJob, matrix: Matrix, k: number, runner: number, mctx: ExprContext, dir: string, log: JobLog, t0: number): Promise { + const { executor: ex, config, masker } = input; + const c = config.jobs[id] ?? {}; + const co = checkout(ex, input, dir); + if (!("root" in co)) throw new Infra("refused" in co ? co.refused : "merge conflicts"); + const root = co.root; + const temp = path.join(dir, "_temp"); + const files = path.join(dir, "_runner"); + ex.mkdirs([temp, files]); + const deadline = t0 + (Number(resolveValue(job["timeout-minutes"], mctx)) || 360) * 60_000; + const notes: string[] = []; + + // What this job gets: its granted secrets (and GitHub App tokens minted for it), else ci.toml's placeholders. + const granted: Record = {}; + for (const name of jobSecrets(config, id)) { + const s = config.secrets[name]!; + if (s.github_app) { + const key = input.secrets[s.github_app.key_secret]; + if (!key) throw new Infra(`the GitHub App key ${s.github_app.key_secret} is not on this host`); + granted[name] = await mintAppToken(s.github_app, Buffer.from(key, "base64").toString("utf-8")); + masker.add(`${name}_${id}_${k}`, granted[name]); + } else if (input.secrets[name] !== undefined) granted[name] = input.secrets[name]!; + else throw new Infra(`secret ${name} is not on this host (${s.vault ? `vault ${s.vault}` : config.host.env_file})`); + } + const secretsCtx = { ...(c.placeholders ?? {}), ...granted }; + const services: Record = {}; + for (const svc of c.services ?? []) { + const s = config.services[svc]!; + if (!ex.postgres) throw new Infra(`service ${svc} needs a CI host (Postgres is provided by the slot executor)`); + services[s.env] = ex.postgres(s.port, `ci_${input.id.replace(/-/g, "_")}_${k}`); + masker.add(`${svc}_${id}_${k}`, services[s.env]!); + } + + const runnerOsName = input.lane === "darwin" ? "macOS" : "Linux"; + let pathPrefix: string[] = []; + let envAcc: Record = {}; + const steps: Record = {}; + const status = { failed: false, cancelled: false }; + const ctxNow = (extra: Partial = {}): ExprContext => ({ + ...mctx, + // github.token is the job's GITHUB_TOKEN when ci.toml grants it one (a GitHub App token), else empty. + github: { ...(mctx.github as object), run_id: c.run_id ? githubRunId(input.id) : "", workspace: root, job: id, token: granted.GITHUB_TOKEN ?? "" }, + env: { ...envAcc }, + secrets: secretsCtx, + steps, + runner: { os: runnerOsName, arch: "X64", temp, tool_cache: path.join(ex.home, "_tool"), name: input.host }, + job: { status: status.failed ? "failure" : "success", services: {} }, + status: { ...status }, + ...extra, + }); + const resolveEnv = (env: Record | undefined, ctx: ExprContext) => + Object.fromEntries(Object.entries(env ?? {}).map(([kk, v]) => [kk, String(resolveValue(v, ctx) ?? "")])); + envAcc = { ...resolveEnv(workflow.env, ctxNow()), }; + envAcc = { ...envAcc, ...resolveEnv(job.env, ctxNow()), ...(c.env ?? {}), ...services }; + + const runnerEnv = (): Record => ({ + PATH: [...pathPrefix, ex.basePath()].join(":"), + HOME: ex.home, + USER: ex.user, + // The identity git works out on GitHub's runner (its hostname has a domain); a slot's namespace cannot resolve the + // host's, so git would refuse to commit with no user.email. + ...(input.executor.sandboxed ? { EMAIL: `${ex.user}@${input.host}.ci.internal` } : {}), + LANG: "C.UTF-8", + TMPDIR: input.executor.sandboxed ? "/tmp" : temp, + CI: "true", + GITHUB_ACTIONS: "true", + GITHUB_REPOSITORY: input.repository, + GITHUB_REPOSITORY_OWNER: input.repository.split("/")[0]!, + GITHUB_SHA: co.headSha, + GITHUB_REF: String((mctx.github as any).ref), + GITHUB_REF_NAME: String((mctx.github as any).ref_name), + GITHUB_EVENT_NAME: input.event, + GITHUB_WORKSPACE: root, + GITHUB_JOB: id, + GITHUB_SERVER_URL: "https://github.com", + ...(input.event === "pull_request" ? { GITHUB_BASE_REF: config.branch, GITHUB_HEAD_REF: input.headRef ?? "" } : {}), + ...(c.run_id ? { GITHUB_RUN_ID: githubRunId(input.id) } : {}), + RUNNER_OS: runnerOsName, + RUNNER_ARCH: "X64", + RUNNER_TEMP: temp, + CASTCI_SLOT: String(ex.slot), + CASTCI_RUNNER: String(runner), + // Each concurrent runner gets its own hundred ports (the run's runners share one network namespace), for a test + // script that scans up from a base. + CASTCI_PORT_BASE: String(4901 + 100 * (ex.slot * input.config.parallel_jobs + runner)), + }); + + let seq = 0; + /** One `run:` step: its script as GitHub's bash runs it, GITHUB_OUTPUT/ENV/PATH read back as the run user. */ + const runScript = async (title: string, script: string, o: { cwd: string; env: Record; shell?: string; timeoutMin?: number }): Promise<{ code: number; timedOut: boolean; outputs: Record }> => { + const n = ++seq; + const outFile = path.join(files, `output-${n}`); + const envFile = path.join(files, `env-${n}`); + const pathFile = path.join(files, `path-${n}`); + const shell = o.shell ?? "bash"; + if (shell !== "bash" && shell !== "sh") throw new Infra(`step "${title}" uses shell ${shell}, which this runner does not run`); + const keepDir = path.join(dir, "_keep"); + const keep = c.keep?.length ? `\n__rc=$?; mkdir -p ${JSON.stringify(keepDir)}; for __f in ${c.keep.join(" ")}; do [ -f "$__f" ] && cp -- "$__f" ${JSON.stringify(keepDir)}/; done; exit $__rc` : ""; + // With files to keep, the script runs in a subshell under the same -e/pipefail, and the copy runs whatever it did. + const body = keep ? `set +e\n( set -e${shell === "bash" ? " -o pipefail" : ""}\n${script}\n)${keep}` : script; + log.line(`##[group]Run ${title}`); + log.line(script.trimEnd().split("\n").map((l) => ` ${l}`).join("\n")); + log.line("##[endgroup]"); + const step = await ex.runStep({ + key: `${id}-${k}`, + script: body, + shell, + cwd: o.cwd, + env: { ...runnerEnv(), ...envAcc, ...o.env, GITHUB_OUTPUT: outFile, GITHUB_ENV: envFile, GITHUB_PATH: pathFile, GITHUB_STEP_SUMMARY: path.join(files, `summary-${n}`) }, + deadline: o.timeoutMin ? Math.min(deadline, Date.now() + o.timeoutMin * 60_000) : deadline, + cpus: runnerCpus(runner, input.config.parallel_jobs, os.availableParallelism()), + onLine: (l) => log.line(l), + }); + if (step.timedOut) log.line("##[error]The job running on this runner has exceeded the maximum execution time."); + if (step.code !== 0) log.line(`##[error]Process completed with exit code ${step.code}.`); + const outputs = parseCommandFile(ex.readRunFile(outFile, 1024 * 1024) ?? ""); + Object.assign(envAcc, parseCommandFile(ex.readRunFile(envFile, 1024 * 1024) ?? "")); + const added = (ex.readRunFile(pathFile, 64 * 1024) ?? "").split("\n").map((l) => l.trim()).filter((l) => l.startsWith("/")); + if (added.length) pathPrefix = [...added.reverse(), ...pathPrefix]; + return { ...step, outputs }; + }; + + /** A `uses:` step: an action this runner knows, a local composite, or ci.toml's word on it. */ + const runUses = async (step: WorkflowStep, ctx: ExprContext, depth: number): Promise<{ ok: boolean; outputs: Record; timedOut?: boolean }> => { + const uses = String(step.uses); + const name = uses.split("@")[0]!; + // Before its inputs are read: a skipped action's `with` may hold what this reader does not evaluate (hashFiles). + if (SKIPPED_ACTIONS[name]) { log.line(`##[notice]${uses}: left out (${SKIPPED_ACTIONS[name]})`); return { ok: true, outputs: {} }; } + if (config.uses[name]?.skip) { log.line(`##[notice]${uses}: left out (${config.uses[name]!.skip})`); return { ok: true, outputs: {} }; } + const withArgs = Object.fromEntries(Object.entries(step.with ?? {}).map(([kk, v]) => [kk, resolveValue(v, ctx)])); + if (name === "actions/checkout") { + // The runner made the checkout; a `ref:` moves it, as GitHub's checkout of that ref would. + const ref = withArgs.ref ? String(withArgs.ref) : ""; + if (ref && withArgs.path === undefined) { + const co = ex.git(["checkout", "-q", "--detach", ref], root); + if (co.code !== 0) { log.line(`##[error]checkout ${ref}: ${co.err}`); return { ok: false, outputs: {} }; } + log.line(`checked out ${ref}`); + } else if (withArgs.path !== undefined || withArgs.repository !== undefined) { + throw new Infra(`${uses} with path or repository: this runner checks out the commit's own repository at its root only`); + } + return { ok: true, outputs: {} }; + } + if (name === "oven-sh/setup-bun") { + const v = String(withArgs["bun-version"] ?? "latest"); + if (!/^\d+\.\d+\.\d+$/.test(v)) throw new Infra(`setup-bun asks for bun ${v}; this runner pins exact versions`); + pathPrefix = [ex.ownCopy(ex.bunBin(v), path.join(dir, "_tool", "bun", v, "bin")), ...pathPrefix]; + log.line(`bun ${v}`); + return { ok: true, outputs: { "bun-version": v } }; + } + if (name === "actions/setup-node") { + const v = String(withArgs["node-version"] ?? ""); + const major = /^(\d+)/.exec(v)?.[1]; + if (!major) throw new Infra(`setup-node asks for node "${v}"; this runner needs a major version`); + pathPrefix = [ex.nodeBin(major), ...pathPrefix]; + return { ok: true, outputs: {} }; + } + if (uses.startsWith("./")) { + if (depth > 5) throw new Infra(`composite actions nest deeper than 5 at ${uses}`); + const base = path.join(root, uses); + const text = ex.readRunFile(path.join(base, "action.yml"), 256 * 1024) ?? ex.readRunFile(path.join(base, "action.yaml"), 256 * 1024); + if (text === null) throw new Infra(`${uses} has no action.yml`); + const action = Bun.YAML.parse(text) as { inputs?: Record; runs?: { using?: string; steps?: WorkflowStep[] } }; + if (action.runs?.using !== "composite") throw new Infra(`${uses} is a ${action.runs?.using ?? "?"} action; this runner runs composite ones`); + const inputs = Object.fromEntries(Object.entries(action.inputs ?? {}).map(([kk, d]) => [kk, String(withArgs[kk] ?? resolveValue(d?.default ?? "", ctx) ?? "")])); + const inner: Record = {}; + for (const s of action.runs.steps ?? []) { + const sctx = { ...ctx, inputs, steps: inner }; + if (!condition(s.if, sctx)) continue; + const r = await runOne(s, sctx, depth + 1, base); + if (s.id) inner[s.id] = { outputs: r.outputs, outcome: r.ok ? "success" : "failure", conclusion: r.ok ? "success" : "failure" }; + if (!r.ok) return { ok: false, outputs: {}, timedOut: r.timedOut }; + } + return { ok: true, outputs: {} }; + } + const known = config.uses[name]; + if (known?.run) { + const r = await runScript(`${uses} (ci.toml)`, interpolate(known.run, ctx), { cwd: root, env: Object.fromEntries(Object.entries(withArgs).map(([kk, v]) => [`INPUT_${kk.toUpperCase().replace(/-/g, "_")}`, String(v ?? "")])) }); + return { ok: r.code === 0, outputs: r.outputs, timedOut: r.timedOut }; + } + throw new Infra(`${uses} is an action this runner does not run; say how in ci.toml [uses."${name}"]`); + }; + + const runOne = async (step: WorkflowStep, ctx: ExprContext, depth: number, actionDir?: string): Promise<{ ok: boolean; outputs: Record; timedOut?: boolean }> => { + if (step.uses) return runUses(step, ctx, depth); + if (typeof step.run !== "string") return { ok: true, outputs: {} }; + const title = step.name ? interpolate(String(step.name), ctx) : step.run.split("\n")[0]!; + // A job's defaults, then the workflow's, apply to its own run steps (never to a composite action's). + const defaults = depth === 0 ? { ...((workflow as any).defaults?.run ?? {}), ...(job.defaults?.run ?? {}) } : {}; + const wd = step["working-directory"] ?? defaults["working-directory"]; + const r = await runScript(title, interpolate(step.run, ctx), { + cwd: wd ? path.join(root, interpolate(String(wd), ctx)) : root, + env: { ...resolveEnv(step.env, ctx), ...(actionDir ? { GITHUB_ACTION_PATH: actionDir } : {}) }, + shell: step.shell ?? defaults.shell, + timeoutMin: Number(resolveValue(step["timeout-minutes"], ctx)) || undefined, + }); + return { ok: r.code === 0, outputs: r.outputs, timedOut: r.timedOut }; + }; + + // The steps: ci.toml's hand-mirrored list (flagged when ci.yml's definition moved), else ci.yml's own. + let list: WorkflowStep[] = job.steps ?? []; + if (c.steps) { + const have = jobHash(job); + if (have !== c.mirrors) { + const drift = `ci.yml's ${id} changed since ci.toml's steps were written (${c.mirrors}..${have}): runner may be stale`; + log.line(`##[warning]${drift}`); + notes.push(drift); + } + // A hand-written job gets its granted secrets as environment, as Union's runner gave them. + list = c.steps.map((s) => ({ ...s, env: { ...granted, ...(s.env ?? {}) } })); + } + const skipSteps = { ...config.skip_steps, ...(c.skip_steps ?? {}) }; + let failedNote: string | undefined; + for (const step of list) { + const name = String(step.name ?? step.uses ?? step.run?.split("\n")[0] ?? ""); + if (skipSteps[name]) { + log.line(`##[notice]${name}: left out (${skipSteps[name]})`); + if (step.id) steps[step.id] = { outputs: {}, outcome: "skipped", conclusion: "skipped" }; + continue; + } + const ctx = ctxNow(); + let runs: boolean; + try { + runs = condition(step.if, ctx); + } catch (err) { + throw new Infra(`step "${name}": if: ${err instanceof ExprError ? err.message : String(err)}`); + } + if (!runs) { + if (step.id) steps[step.id] = { outputs: {}, outcome: "skipped", conclusion: "skipped" }; + continue; + } + if (Date.now() > deadline) { failedNote ??= "timed out (ci.yml's limit)"; status.failed = true; break; } + let r: { ok: boolean; outputs: Record; timedOut?: boolean }; + try { + r = await runOne(step, ctx, 0); + } catch (err) { + if (err instanceof ExprError) throw new Infra(`step "${name}": ${err.message}`); + throw err; + } + const continueOnError = truthy(resolveValue(step["continue-on-error"] ?? false, ctx)); + if (step.id) steps[step.id] = { outputs: r.outputs, outcome: r.ok ? "success" : "failure", conclusion: r.ok || continueOnError ? "success" : "failure" }; + if (!r.ok && !continueOnError) { + status.failed = true; + failedNote ??= r.timedOut ? `timed out in: ${name}` : `${name}: failed`; + } + } + + // Files the job's steps kept (ci.toml keep), read as the run user, masked, gzipped beside the log. + if (c.keep?.length) { + const keepDir = path.join(dir, "_keep"); + const dest = path.join(input.out, "jobs", `${runnerName(id, matrix, !!job.strategy?.matrix)}-kept`); + for (const f of ex.listRunFiles(keepDir, "*")) { + const text = ex.readRunFile(path.join(keepDir, f), 20 * 1024 * 1024); + if (text === null) continue; + mkdirSync(dest, { recursive: true }); + writeFileSync(path.join(dest, `${f}.gz`), gzipSync(masker.apply(text))); + } + } + + const outputs: Record = {}; + for (const [kk, v] of Object.entries(job.outputs ?? {})) outputs[kk] = String(resolveValue(v, ctxNow()) ?? ""); + const note = [...notes, failedNote].filter(Boolean).join("; ") || undefined; + return { conclusion: status.failed ? "failure" : "success", outputs, ...(note ? { note } : {}) }; +} + +/** A GITHUB_RUN_ID for the run: its id's launch time (base 36 ms, `-