diff --git a/.codesignal/run_solution.sh b/.codesignal/run_solution.sh new file mode 100644 index 0000000..76a063f --- /dev/null +++ b/.codesignal/run_solution.sh @@ -0,0 +1,11 @@ +#!/bin/bash +# BASE-TASK CONTENT: the base task's .codesignal/run_solution.sh. It is not run from this repository. +# Cosmo reads this script's STDOUT and nothing else: the report of the learner's workflow and runs. +# +# setup.sh keeps running (it serves the editor), so wait for its marker rather than for it to finish. +cd /usercode/FILESYSTEM/agentflow || exit 1 +if [ ! -f /tmp/agentflow-release-ready ]; then + echo "AgentFlow is not ready: it is still starting, or its setup failed. Wait a few seconds and run again; if this repeats, reset the session." + exit 1 +fi +PROJECT_ROOT=/usercode/FILESYSTEM/agentflow node apps/server/dist/report.cjs diff --git a/.codesignal/setup.sh b/.codesignal/setup.sh new file mode 100644 index 0000000..25eed3a --- /dev/null +++ b/.codesignal/setup.sh @@ -0,0 +1,55 @@ +#!/bin/sh +# BASE-TASK CONTENT: the base task's .codesignal/setup.sh. It is not run from this repository. +# +# Downloads the release into agentflow/, adds the models (and the task's starting workflow, if +# any) from .codesignal/agentflow/, and serves the editor on port 3000. +# +# A task changes what the base task provides by shipping its own file at the same path: +# .codesignal/agentflow/config.json the models learners can pick (required) +# .codesignal/agentflow/default-workflow.json the starting canvas (optional) + +WORKSPACE=/usercode/FILESYSTEM +APP_DIR="$WORKSPACE/agentflow" +SETTINGS_DIR="$WORKSPACE/.codesignal/agentflow" +READY_MARKER=/tmp/agentflow-release-ready +rm -f "$READY_MARKER" +mkdir -p "$APP_DIR" || exit 1 +cd "$APP_DIR" || exit 1 + +# Production runs the latest release; staging runs the newest build. +RELEASE_URL="https://github.com/CodeSignal/learn_bespoke-agentflow/releases/latest/download/release.tar.gz" +if [ "${APP_ENVIRONMENT:-}" = "staging" ]; then + RELEASE_URL="https://github.com/CodeSignal/learn_bespoke-agentflow/releases/download/prerelease/release.tar.gz" +fi + +# Stop on a failed download or unpack rather than start whatever an earlier session left here. +if ! wget -q "$RELEASE_URL" -O release.tar.gz; then + rm -f release.tar.gz + echo "Cannot start AgentFlow: the release could not be downloaded from $RELEASE_URL" >&2 + exit 1 +fi +if ! tar -xzf release.tar.gz; then + rm -f release.tar.gz + echo "Cannot start AgentFlow: the release could not be unpacked" >&2 + exit 1 +fi +rm release.tar.gz + +# The release ships no models: they come from the base task or the task, every session. +mkdir -p .config +if ! cp "$SETTINGS_DIR/config.json" .config/config.json; then + echo "Cannot start AgentFlow: $SETTINGS_DIR/config.json is missing" >&2 + exit 1 +fi +if [ -f "$SETTINGS_DIR/default-workflow.json" ]; then + cp "$SETTINGS_DIR/default-workflow.json" .config/default-workflow.json +else + rm -f .config/default-workflow.json +fi +touch "$READY_MARKER" + +# The learner's canvas and runs live in agentflow/data/ and survive a return visit. +# Keep the server in the foreground; the platform does not expect this script to return. +export PORT=3000 +export PROJECT_ROOT="$APP_DIR" +exec npm run start:prod diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..bb3514e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,94 @@ +# Publishes a pre-release for every merge to main. +# +# Each run builds release.tar.gz (npm run pack: bundled server and report, built +# editor, no node_modules), boots it like a session (npm run verify:release), +# publishes it as pre-release v, and moves the floating `prerelease` +# release to it. +# +# Staging: https://github.com/CodeSignal/learn_bespoke-agentflow/releases/download/prerelease/release.tar.gz +# Production: https://github.com/CodeSignal/learn_bespoke-agentflow/releases/latest/download/release.tar.gz +# +# Production only changes when a tested pre-release is promoted: +# gh release edit vN --prerelease=false --latest + +name: Release + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: write + +# Never cancel: two merges in a row must both publish, in order. +concurrency: + group: release + cancel-in-progress: false + +jobs: + release: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + + - uses: actions/setup-node@v4 + with: + node-version: 22.x + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Test + run: | + npm run lint + npm run typecheck + npm test + + - name: Build and pack + run: | + npm run build + npm run pack + + - name: Verify the release like a session + run: npm run verify:release + + - name: Publish pre-release v${{ github.run_number }} + uses: ncipollo/release-action@v1 + with: + tag: v${{ github.run_number }} + commit: ${{ github.sha }} + name: v${{ github.run_number }} + body: Build of ${{ github.sha }}. Promote it with `gh release edit v${{ github.run_number }} --prerelease=false --latest` after a staging test. + artifacts: release.tar.gz + artifactErrorsFailBuild: true + prerelease: true + makeLatest: false + + - name: Move the prerelease channel to this build + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: v${{ github.run_number }} + run: | + set -euo pipefail + # Skip if a newer build was published while this run waited in the queue. + newest="$(gh api "repos/${GITHUB_REPOSITORY}/releases" \ + --jq '[.[] | select(.draft == false and (.tag_name | test("^v[0-9]+$")))] | map(.tag_name | ltrimstr("v") | tonumber) | max')" + if [ "${newest}" != "${{ github.run_number }}" ]; then + echo "v${newest} is newer than ${TAG}; leaving the prerelease channel alone." + exit 0 + fi + git tag -f prerelease "${GITHUB_SHA}" + git push --no-verify -f origin refs/tags/prerelease + notes="Floating channel for staging sessions. Currently ${TAG} (${GITHUB_SHA})." + if gh release view prerelease >/dev/null 2>&1; then + gh release edit prerelease --prerelease --title "Latest pre-release" --notes "${notes}" + gh release upload prerelease release.tar.gz --clobber + else + gh release create prerelease release.tar.gz --prerelease --latest=false \ + --title "Latest pre-release" --notes "${notes}" + fi diff --git a/.gitignore b/.gitignore index ec2d2e4..2f741b7 100644 --- a/.gitignore +++ b/.gitignore @@ -24,6 +24,11 @@ yarn-error.log* # Scripts setup.sh +!.codesignal/setup.sh + +# Release packing (npm run pack) +release/ +release.tar.gz # Local config .config/default-workflow.json diff --git a/AGENTS.md b/AGENTS.md index ab02969..928dcc2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,7 @@ Server routes: - `npm run build`: Build server and web app. - `npm run build:packages`: Build shared packages. - `npm run report`: Print the workflow and run report (build the server first). +- `npm run release:local`: Build, pack `release.tar.gz` and boot it like a session (`docs/releases.md`). - `npm run lint`: Run ESLint. - `npm run typecheck`: Typecheck every workspace. - `npm test`: Build shared packages, then run Vitest in the engine, server and web workspaces. @@ -52,6 +53,8 @@ Server routes: ## Testing Guidelines - CI checks in `.github/workflows/pr.yml`: `lint`, `build:packages`, `typecheck`, `test`, `build`. +- `.github/workflows/release.yml` publishes every merge to `main` as pre-release `vN` and moves the `prerelease` channel; promote a tested build to `latest` by hand. +- `.codesignal/` mirrors the session scripts of the CodeSignal base task; it is not run from the repository. - Every workspace with logic uses Vitest (`npm --workspace run test`). The engine and server suites use a stub LLM; the server's SDK suite runs the real Agents SDK against a scripted model, so no API key is needed. - Server and package sources are ES modules compiled with `NodeNext`: relative imports need a `.js` extension. - Prefer targeted `*.test.ts` files near changed behavior. diff --git a/CLAUDE.md b/CLAUDE.md index 75d2373..35eb5c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -44,6 +44,7 @@ npm run lint npm run typecheck npm test npm run report # after npm run build:server +npm run release:local # build, pack release.tar.gz, boot it like a session npm --workspace apps/web run test npm --workspace apps/server run test @@ -112,6 +113,7 @@ git submodule update --init --recursive - `docs/workflow-semantics.md` - `docs/run-persistence.md` - `docs/report.md` +- `docs/releases.md` - `docs/configuration.md` - `docs/troubleshooting.md` - `apps/web/docs/run-readiness.md` diff --git a/README.md b/README.md index f91ac74..0c9c6c8 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ npm run dev | `npm run build` | Build server and web app. | | `npm run build:packages` | Build `packages/types`, `packages/workflow-graph` and `packages/workflow-engine`. | | `npm run report` | Print the workflow and run report (after `npm run build:server`; see [Report](./docs/report.md)). | +| `npm run release:local` | Build, pack `release.tar.gz` and boot it like a session (see [Releases and Sessions](./docs/releases.md)). | | `npm run typecheck` | Typecheck every workspace. | | `npm run lint` | ESLint across repo TypeScript files. | | `npm test` | Build shared packages, then run the Vitest suites of the engine, server and web app. | @@ -70,6 +71,7 @@ npm run dev - [Workflow Semantics](./docs/workflow-semantics.md) - [Run Persistence and Recovery](./docs/run-persistence.md) - [Report](./docs/report.md) +- [Releases and Sessions](./docs/releases.md) - [Configuration](./docs/configuration.md) - [Troubleshooting](./docs/troubleshooting.md) - [Web Run Readiness Rules](./apps/web/docs/run-readiness.md) diff --git a/docs/README.md b/docs/README.md index 2f556c0..9d0fc0a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,6 +5,7 @@ - [Workflow Semantics](./workflow-semantics.md) - [Run Persistence and Recovery](./run-persistence.md) - [Report](./report.md) +- [Releases and Sessions](./releases.md) - [Configuration](./configuration.md) - [Troubleshooting](./troubleshooting.md) - [Web Run Readiness](../apps/web/docs/run-readiness.md) diff --git a/docs/releases.md b/docs/releases.md new file mode 100644 index 0000000..2080693 --- /dev/null +++ b/docs/releases.md @@ -0,0 +1,51 @@ +# Releases and Sessions + +A CodeSignal session never clones this repository or runs `npm install`. It downloads a release, adds the task's models, and starts the server on port 3000. + +## The release + +`npm run pack` (after `npm run build`) writes `release.tar.gz`: + +| Path | What it is | +| --- | --- | +| `package.json` | `start:prod` (the server) and `report` scripts | +| `apps/server/dist/index.cjs` | the server, bundled with its dependencies by esbuild | +| `apps/server/dist/report.cjs` | the report for the grader (`npm run report`), bundled | +| `apps/web/dist/` | the built editor, with the design system | + +It holds no `node_modules` and no `.config/`: the models and the starting workflow come from the session, so unpacking a release never overwrites them. + +`npm run verify:release` boots the tarball the way a session does: it unpacks it into an empty directory, adds `.config/config.json`, starts the server without API keys, saves a canvas, runs a Start → Approval workflow (which needs no model) and checks the report. `npm run release:local` builds, packs and verifies in one go. + +## Channels + +`.github/workflows/release.yml` runs on every merge to `main`: lint, typecheck, tests, build, pack, verify, then it publishes pre-release `v` and moves the floating `prerelease` release to it. + +| Channel | URL | +| --- | --- | +| Staging | `https://github.com/CodeSignal/learn_bespoke-agentflow/releases/download/prerelease/release.tar.gz` | +| Production | `https://github.com/CodeSignal/learn_bespoke-agentflow/releases/latest/download/release.tar.gz` | + +Production only changes when a pre-release has passed a staging test and is promoted: + +```bash +gh release edit vN -R CodeSignal/learn_bespoke-agentflow --prerelease=false --latest +``` + +## Session scripts + +The scripts the session runs belong to the base task; copies are kept in [`.codesignal/`](../.codesignal) so a change to the release layout and to the scripts land together. + +| Base-task file | Runs on | Job | +| --- | --- | --- | +| `.codesignal/setup.sh` | session start | download the release into `agentflow/` (`prerelease` when `APP_ENVIRONMENT=staging`, else `latest`), copy the models and starting workflow, serve on port 3000 | +| `.codesignal/run_solution.sh` | Run | print the report to STDOUT for the grader | +| `main.sh` | Run | `bash .codesignal/run_solution.sh` | +| `.codesignal/agentflow/config.json` | session start | the models learners can pick ([Configuration](./configuration.md)) | +| `.codesignal/agentflow/default-workflow.json` | session start | optional starting canvas | + +A task overrides the base task's models or starting workflow by shipping its own file at the same path. `setup.sh` copies them into `agentflow/.config/` on every start, so a changed file applies from the next session. + +The learner's canvas and runs are written to `agentflow/data/`, which the session saves, so they survive a return visit. Run records count toward the session's save budget; retention keeps the newest 20. + +Every model in `config.json` must also be allowed by the LLM proxy the session uses, and the proxy must provide a key for each provider in the file (`OPENAI_API_KEY` and `OPENAI_BASE_URL` for OpenAI, `ANTHROPIC_API_KEY` and `ANTHROPIC_BASE_URL` for Anthropic). The SDKs read the base URLs from the environment when the provider sets no `baseUrl`. diff --git a/package-lock.json b/package-lock.json index 9b59218..fc3ef8d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "@types/node": "^26.6.6", "@typescript-eslint/eslint-plugin": "^8.73.0", "@typescript-eslint/parser": "^8.73.0", + "esbuild": "^0.28.2", "eslint": "^10.15.0", "tsx": "^4.23.15", "typescript": "^6.0.3", diff --git a/package.json b/package.json index f88815b..ac5f65f 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,9 @@ "build:packages": "npm --workspace packages/types run build && npm --workspace packages/workflow-graph run build && npm --workspace packages/workflow-engine run build", "build:server": "npm run build:packages && npm --workspace apps/server run build", "build:web": "npm --workspace apps/web run build", + "pack": "node scripts/pack-release.mjs", + "verify:release": "node scripts/verify-release.mjs", + "release:local": "npm run build && npm run pack && npm run verify:release", "test": "npm run build:packages && npm run test --workspaces --if-present", "clean": "npm run clean --workspaces", "lint": "eslint .", @@ -26,6 +29,7 @@ "@types/node": "^26.6.6", "@typescript-eslint/eslint-plugin": "^8.73.0", "@typescript-eslint/parser": "^8.73.0", + "esbuild": "^0.28.2", "eslint": "^10.15.0", "tsx": "^4.23.15", "typescript": "^6.0.3", diff --git a/scripts/pack-release.mjs b/scripts/pack-release.mjs new file mode 100644 index 0000000..70f81d1 --- /dev/null +++ b/scripts/pack-release.mjs @@ -0,0 +1,117 @@ +#!/usr/bin/env node +/** + * Builds release.tar.gz: what a session downloads and starts. Run `npm run build` first. + * + * The tarball keeps the repository's layout so the server finds the web app + * where it expects it, but holds only what runs: + * + * package.json start:prod and report scripts + * apps/server/dist/index.cjs the server, bundled with its dependencies + * apps/server/dist/report.cjs the report for the grader, bundled + * apps/web/dist/ the built editor + * + * No node_modules and no .config/: the models (.config/config.json) and the + * optional starting workflow come from the session, never from the release, + * so unpacking it cannot overwrite them. + */ + +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import * as esbuild from 'esbuild'; + +const ROOT = path.resolve(import.meta.dirname, '..'); +const OUT = path.join(ROOT, 'release'); +const TARBALL = path.join(ROOT, 'release.tar.gz'); +const WEB_DIST = path.join(ROOT, 'apps', 'web', 'dist'); + +// Files of the design-system submodule that the editor never loads. +const DESIGN_SYSTEM_EXTRAS = new Set([ + '.git', + '.github', + 'tests', + 'test.html', + 'test-server.js', + 'playwright.config.mjs', + 'agents.md', + 'llms.txt', + 'package-lock.json' +]); + +function formatSize(bytes) { + return bytes >= 1024 * 1024 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB` : `${Math.round(bytes / 1024)} KB`; +} + +if (!fs.existsSync(path.join(WEB_DIST, 'index.html'))) { + console.error('apps/web/dist is missing: run `npm run build` first.'); + process.exit(1); +} + +fs.rmSync(OUT, { recursive: true, force: true }); +fs.rmSync(TARBALL, { force: true }); + +// The server sources are ES modules that use import.meta.dirname; a CommonJS +// bundle has __dirname instead, and the bundles sit where the compiled files +// did (apps/server/dist), so paths resolved from them stay correct. +const shared = { + absWorkingDir: ROOT, + bundle: true, + platform: 'node', + format: 'cjs', + target: 'node20', + minify: true, + keepNames: true, + // Vite is only imported for development, never when NODE_ENV=production. + external: ['vite'], + define: { 'import.meta.dirname': '__dirname', 'import.meta.url': '__agentflowImportMetaUrl' }, + banner: { js: 'const __agentflowImportMetaUrl = require("node:url").pathToFileURL(__filename).href;' }, + logLevel: 'warning' +}; + +await esbuild.build({ + ...shared, + entryPoints: ['apps/server/src/index.ts'], + outfile: 'release/apps/server/dist/index.cjs' +}); +await esbuild.build({ + ...shared, + entryPoints: ['apps/server/src/report/cli.ts'], + outfile: 'release/apps/server/dist/report.cjs' +}); + +fs.cpSync(WEB_DIST, path.join(OUT, 'apps', 'web', 'dist'), { + recursive: true, + dereference: true, + filter: (source) => { + const relative = path.relative(path.join(WEB_DIST, 'design-system'), source); + if (relative.startsWith('..') || path.isAbsolute(relative)) return true; + return !relative.split(path.sep).some((part) => DESIGN_SYSTEM_EXTRAS.has(part)); + } +}); + +const { version } = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8')); +fs.writeFileSync( + path.join(OUT, 'package.json'), + `${JSON.stringify( + { + name: 'agentflow-release', + version, + private: true, + description: 'AgentFlow, bundled to run without node_modules', + scripts: { + 'start:prod': 'NODE_ENV=production node apps/server/dist/index.cjs', + report: 'node apps/server/dist/report.cjs' + }, + engines: { node: '>=20.19' } + }, + null, + 2 + )}\n` +); + +execFileSync('tar', ['-czf', TARBALL, '-C', OUT, '.'], { stdio: 'inherit' }); + +for (const file of ['apps/server/dist/index.cjs', 'apps/server/dist/report.cjs']) { + console.log(`${file}: ${formatSize(fs.statSync(path.join(OUT, file)).size)}`); +} +console.log(`release.tar.gz: ${formatSize(fs.statSync(TARBALL).size)}`); diff --git a/scripts/verify-release.mjs b/scripts/verify-release.mjs new file mode 100644 index 0000000..28058f7 --- /dev/null +++ b/scripts/verify-release.mjs @@ -0,0 +1,101 @@ +#!/usr/bin/env node +/** + * Boots release.tar.gz the way a session does and fails if anything a learner + * or the grader needs is broken. Run `npm run pack` first. + * + * 1. Unpack into an empty directory and add .config/config.json, as setup.sh does. + * 2. Start the server with no node_modules and no API keys. + * 3. Check the editor page, the model configuration and saving the canvas. + * 4. Run a workflow that needs no model (Start → Approval) so a run record is written. + * 5. Run the report and check it describes the workflow and the run. + */ + +import { execFileSync, spawn } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const ROOT = path.resolve(import.meta.dirname, '..'); +const TARBALL = path.join(ROOT, 'release.tar.gz'); +const PORT = 3000 + Math.floor(Math.random() * 1000) + 1000; +const BASE = `http://127.0.0.1:${PORT}`; + +function fail(message) { + throw new Error(message); +} + +async function waitForServer(server) { + for (let attempt = 0; attempt < 60; attempt += 1) { + if (server.exitCode !== null) fail(`The server exited with code ${server.exitCode}.`); + try { + const response = await fetch(`${BASE}/api/config`); + if (response.ok) return; + } catch { + // not listening yet + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + fail('The server did not answer within 15 seconds.'); +} + +async function request(method, url, body) { + const response = await fetch(`${BASE}${url}`, { + method, + headers: body ? { 'Content-Type': 'application/json' } : undefined, + body: body ? JSON.stringify(body) : undefined + }); + const text = await response.text(); + if (!response.ok) fail(`${method} ${url} answered ${response.status}: ${text}`); + return text; +} + +if (!fs.existsSync(TARBALL)) fail('release.tar.gz is missing: run `npm run pack` first.'); + +const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agentflow-release-')); +let server; +let output = ''; +try { + execFileSync('tar', ['-xzf', TARBALL, '-C', dir]); + if (fs.existsSync(path.join(dir, 'node_modules'))) fail('The release contains node_modules.'); + if (fs.existsSync(path.join(dir, '.config'))) fail('The release contains .config/, which would overwrite the session’s.'); + fs.mkdirSync(path.join(dir, '.config')); + fs.copyFileSync(path.join(ROOT, '.config', 'config.json'), path.join(dir, '.config', 'config.json')); + + const env = { ...process.env, PORT: String(PORT), PROJECT_ROOT: dir }; + delete env.OPENAI_API_KEY; + delete env.ANTHROPIC_API_KEY; + server = spawn('npm', ['run', 'start:prod'], { cwd: dir, env, stdio: ['ignore', 'pipe', 'pipe'] }); + server.stdout.on('data', (chunk) => (output += chunk)); + server.stderr.on('data', (chunk) => (output += chunk)); + await waitForServer(server); + + const page = await request('GET', '/'); + if (!page.includes('id="canvas-container"')) fail('GET / did not return the editor page.'); + const config = JSON.parse(await request('GET', '/api/config')); + if (!config.defaultModel || !config.providers?.length) fail('GET /api/config returned no models.'); + + const graph = { + nodes: [ + { id: 'start', type: 'start', x: 0, y: 0, data: { initialInput: 'Release check' } }, + { id: 'review', type: 'approval', x: 200, y: 0, data: { prompt: 'Approve?' } } + ], + connections: [{ source: 'start', target: 'review', sourceHandle: 'output', targetHandle: 'input' }] + }; + await request('PUT', '/api/workflow', { workflow: graph }); + const run = JSON.parse(await request('POST', '/api/run', { graph })); + if (run.status !== 'paused') fail(`The run ended as "${run.status}" instead of pausing at the approval.`); + if (fs.readdirSync(path.join(dir, 'data', 'runs')).length !== 1) fail('The run record was not saved.'); + + const report = execFileSync('npm', ['--silent', 'run', 'report'], { cwd: dir, env, encoding: 'utf-8' }); + for (const expected of ['# AgentFlow report', "the learner's canvas", 'Runs: 1 saved run (1 paused)']) { + if (!report.includes(expected)) fail(`The report does not contain "${expected}":\n${report}`); + } + console.log('Release verified: editor, model configuration, saved canvas, run record and report.'); +} catch (error) { + console.error(error instanceof Error ? error.message : error); + if (output) console.error(`Server output:\n${output}`); + process.exitCode = 1; +} finally { + server?.kill(); + fs.rmSync(dir, { recursive: true, force: true }); +}