Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
ci: speed up pull request checks (#446)
Gener32f121bd2f4f
diff --git a/.github/workflows/auto-tag-release.yml b/.github/workflows/auto-tag-release.ymlindex 004394486..d4b2a2891 100644--- a/.github/workflows/auto-tag-release.yml+++ b/.github/workflows/auto-tag-release.yml@@ -13,7 +13,7 @@ jobs:permissions:contents: writesteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7with:fetch-depth: 0@@ -52,7 +52,7 @@ jobs:- name: Generate changelog with git-cliffif: steps.check.outputs.exists == 'false'id: changelog- uses: orhun/git-cliff-action@v4+ uses: orhun/git-cliff-action@f50e11560dce63f7c33227798f90b924471a88b5 # v4with:args: --latest --strip headerenv:diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 66c332caa..b63ae94df 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -3,25 +3,76 @@ name: CIon:push:branches: [main]- paths-ignore: ["**/*.md"]pull_request:branches: [main]- paths-ignore: ["**/*.md"]+ merge_group:+ types: [checks_requested]+ schedule:+ - cron: "17 3 * * *"+ workflow_dispatch:++permissions:+ contents: readconcurrency:- group: ${{ github.workflow }}-${{ github.ref }}+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.merge_group.head_sha || github.ref }}cancel-in-progress: truejobs:+ scope:+ name: Change Scope+ runs-on: ubuntu-latest+ timeout-minutes: 5+ outputs:+ blog_only: ${{ steps.scope.outputs.blog_only }}+ run_code_checks: ${{ steps.scope.outputs.run_code_checks }}+ run_windows: ${{ steps.scope.outputs.run_windows }}+ run_e2e: ${{ steps.scope.outputs.run_e2e }}+ run_rust: ${{ steps.scope.outputs.run_rust }}+ run_lighthouse: ${{ steps.scope.outputs.run_lighthouse }}+ run_knip: ${{ steps.scope.outputs.run_knip }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ with:+ fetch-depth: 0+ - id: scope+ env:+ BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event_name == 'merge_group' && github.event.merge_group.base_sha || github.event.before }}+ HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}+ FORCE_FULL: ${{ github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}+ run: |+ args=(--base "$BASE_SHA" --head "$HEAD_SHA" --output "$GITHUB_OUTPUT" --summary "$GITHUB_STEP_SUMMARY")+ if [[ "$FORCE_FULL" == "true" ]]; then args+=(--force-full); fi+ node scripts/ci/changed-scopes.mjs "${args[@]}"++ blog-content:+ name: Blog Content+ needs: scope+ if: needs.scope.outputs.blog_only == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7+ with:+ node-version: 22+ cache: pnpm+ - run: pnpm install --frozen-lockfile+ - run: pnpm --filter @alook/web validate:blog+ - run: pnpm build --filter=@alook/web+quality:name: Typecheck & Lint+ needs: scope+ if: needs.scope.outputs.run_code_checks == 'true'runs-on: ubuntu-latesttimeout-minutes: 10steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: oven-sh/setup-bun@v2- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm@@ -32,39 +83,49 @@ jobs:knip:name: Dead Code Detection (knip)- # Non-blocking: reports unused code but does not fail the PR.- # To switch to blocking mode, remove `continue-on-error: true` below.+ needs: scope+ if: needs.scope.outputs.run_knip == 'true'runs-on: ubuntu-latesttimeout-minutes: 10continue-on-error: true- strategy:- fail-fast: false- matrix:- module: [app, cli, email-worker, shared, wake-worker, web, ws-do]steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- - name: "knip: ${{ matrix.module }}"- run: pnpm --filter "./src/${{ matrix.module }}" run knip+ - run: pnpm knip- test:- name: Tests (${{ matrix.os }})- runs-on: ${{ matrix.os }}+ test-linux:+ name: Tests (ubuntu-latest)+ needs: scope+ if: needs.scope.outputs.run_code_checks == 'true'+ runs-on: ubuntu-latesttimeout-minutes: 10- strategy:- fail-fast: false- matrix:- os: [ubuntu-latest, windows-latest]steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: oven-sh/setup-bun@v2- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7+ with:+ node-version: 22+ cache: pnpm+ - run: pnpm install --frozen-lockfile+ - run: pnpm test++ test-windows:+ name: Tests (windows-latest)+ needs: scope+ if: needs.scope.outputs.run_windows == 'true'+ runs-on: windows-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm@@ -73,22 +134,23 @@ jobs:e2e:name: E2E Tests- if: github.event_name == 'pull_request'+ needs: scope+ if: needs.scope.outputs.run_e2e == 'true' && github.event_name != 'push'runs-on: ubuntu-latesttimeout-minutes: 15env:BETTER_AUTH_SECRET: ci-e2e-secretBETTER_AUTH_URL: http://localhost:3000steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: oven-sh/setup-bun@v2- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- - name: Create .dev.vars for local bindings+ - name: Create local bindingsrun: printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars- run: pnpm run db:migrate- name: Start dev servers@@ -97,29 +159,20 @@ jobs:pnpm --filter @alook/ws-do dev &pnpm --filter @alook/web dev &pnpm --filter @alook/wake-worker dev &- - name: Wait for services to be ready+ - name: Wait for servicesrun: |wait_for() {- local url=$1 name=$2 timeout=60 elapsed=0- echo "Waiting for $name ($url)..."+ local url=$1 timeout=60 elapsed=0until curl -sf "$url" > /dev/null 2>&1; dosleep 2elapsed=$((elapsed + 2))- if [ $elapsed -ge $timeout ]; then- echo "WARN: $name not ready after ${timeout}s"- return 1- fi+ if [ $elapsed -ge $timeout ]; then return 1; fidone- echo "$name ready (${elapsed}s)"- return 0}-- # First attempt- if ! wait_for http://localhost:8787/health "email-worker" || \- ! wait_for http://localhost:8789/health "ws-do" || \- ! wait_for http://localhost:3000/api/health "web app" || \- ! wait_for http://localhost:8790/health "wake-worker"; then- echo "Some services failed to start, restarting..."+ if ! wait_for http://localhost:8787/health email-worker || \+ ! wait_for http://localhost:8789/health ws-do || \+ ! wait_for http://localhost:3000/api/health web || \+ ! wait_for http://localhost:8790/health wake-worker; thenpkill -f "wrangler" || truepkill -f "next" || truesleep 3@@ -127,11 +180,10 @@ jobs:pnpm --filter @alook/ws-do dev &pnpm --filter @alook/web dev &pnpm --filter @alook/wake-worker dev &- # Second attempt — fail hard- wait_for http://localhost:8787/health "email-worker" || exit 1- wait_for http://localhost:8789/health "ws-do" || exit 1- wait_for http://localhost:3000/api/health "web app" || exit 1- wait_for http://localhost:8790/health "wake-worker" || exit 1+ wait_for http://localhost:8787/health email-worker+ wait_for http://localhost:8789/health ws-do+ wait_for http://localhost:3000/api/health web+ wait_for http://localhost:8790/health wake-workerfi- run: pnpm test:e2e- run: pnpm --filter @alook/cli run test:integration@@ -139,13 +191,15 @@ jobs:build:name: Build+ needs: scope+ if: needs.scope.outputs.run_code_checks == 'true'runs-on: ubuntu-latesttimeout-minutes: 10steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: oven-sh/setup-bun@v2- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm@@ -154,20 +208,21 @@ jobs:coverage:name: Coverage- if: github.event_name == 'pull_request' || (github.event_name == 'push' && startsWith(github.event.head_commit.message, 'release:'))+ needs: scope+ if: needs.scope.outputs.run_code_checks == 'true' && (github.event_name != 'push' || startsWith(github.event.head_commit.message, 'release:'))runs-on: ubuntu-latesttimeout-minutes: 10steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: oven-sh/setup-bun@v2- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- run: pnpm vitest run --coverage --coverage.reporter=json --coverage.reporter=text- - uses: codecov/codecov-action@v7+ - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7with:token: ${{ secrets.CODECOV_TOKEN }}files: ./coverage/coverage-final.json@@ -175,47 +230,82 @@ jobs:desktop-rust:name: Desktop Rust (test + machete)+ needs: scope+ if: needs.scope.outputs.run_rust == 'true'runs-on: ubuntu-latesttimeout-minutes: 15defaults:run:working-directory: src/desktop/src-taurienv:- RUSTFLAGS: "-D warnings"+ RUSTFLAGS: -D warningssteps:- - uses: actions/checkout@v7- - uses: dtolnay/rust-toolchain@stable- - uses: Swatinem/rust-cache@v2+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stable+ - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2with:workspaces: src/desktop/src-tauri- - name: Install system dependencies- run: |+ - run: |sudo apt-get updatesudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libxdo-dev- run: cargo test- - name: Install cargo-machete- run: cargo install cargo-machete --locked+ - run: cargo install cargo-machete --locked- run: cargo machetelighthouse:name: Lighthouse SEO- if: github.event_name == 'pull_request'+ needs: scope+ if: needs.scope.outputs.run_lighthouse == 'true' && github.event_name != 'push'runs-on: ubuntu-latesttimeout-minutes: 10env:BETTER_AUTH_SECRET: ci-lighthouse-secretBETTER_AUTH_URL: http://localhost:3000steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: oven-sh/setup-bun@v2- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile- - name: Create .dev.vars- run: printf 'BETTER_AUTH_SECRET=ci-lighthouse-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\n' > src/web/.dev.vars- - name: Lighthouse CI- working-directory: src/web+ - run: printf 'BETTER_AUTH_SECRET=ci-lighthouse-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\n' > src/web/.dev.vars+ - working-directory: src/webrun: npx @lhci/cli autorun --config=lighthouserc.json && node scripts/print-lighthouse-scores.mjs++ ci-gate:+ name: CI Gate+ if: always()+ needs:+ - scope+ - blog-content+ - quality+ - knip+ - test-linux+ - test-windows+ - e2e+ - build+ - coverage+ - desktop-rust+ - lighthouse+ runs-on: ubuntu-latest+ timeout-minutes: 5+ env:+ CI_GATE_RESULTS: >-+ [+ {"name":"scope","expected":true,"result":"${{ needs.scope.result }}"},+ {"name":"blog-content","expected":${{ needs.scope.outputs.blog_only == 'true' }},"result":"${{ needs.blog-content.result }}"},+ {"name":"quality","expected":${{ needs.scope.outputs.run_code_checks == 'true' }},"result":"${{ needs.quality.result }}"},+ {"name":"knip","expected":${{ needs.scope.outputs.run_knip == 'true' }},"result":"${{ needs.knip.result }}"},+ {"name":"test-linux","expected":${{ needs.scope.outputs.run_code_checks == 'true' }},"result":"${{ needs.test-linux.result }}"},+ {"name":"test-windows","expected":${{ needs.scope.outputs.run_windows == 'true' }},"result":"${{ needs.test-windows.result }}"},+ {"name":"e2e","expected":${{ needs.scope.outputs.run_e2e == 'true' && github.event_name != 'push' }},"result":"${{ needs.e2e.result }}"},+ {"name":"build","expected":${{ needs.scope.outputs.run_code_checks == 'true' }},"result":"${{ needs.build.result }}"},+ {"name":"coverage","expected":${{ needs.scope.outputs.run_code_checks == 'true' && (github.event_name != 'push' || startsWith(github.event.head_commit.message, 'release:')) }},"result":"${{ needs.coverage.result }}"},+ {"name":"desktop-rust","expected":${{ needs.scope.outputs.run_rust == 'true' }},"result":"${{ needs.desktop-rust.result }}"},+ {"name":"lighthouse","expected":${{ needs.scope.outputs.run_lighthouse == 'true' && github.event_name != 'push' }},"result":"${{ needs.lighthouse.result }}"}+ ]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - run: node scripts/ci/assert-gate.mjsdiff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex d775ec33b..c1e121fb2 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -26,18 +26,18 @@ jobs:runs-on: ${{ matrix.platform }}timeout-minutes: 30steps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22- name: Install pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6- name: Install Rust stable- uses: dtolnay/rust-toolchain@stable+ uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stablewith:targets: ${{ matrix.target }}@@ -57,7 +57,7 @@ jobs:run: echo "version=$(tr -d '\n' < src/desktop/.deploy-version)" >> "$GITHUB_OUTPUT"- name: Build Tauri app- uses: tauri-apps/[email protected]+ uses: tauri-apps/tauri-action@1deb371b0cd8bd54025b384f1cd735e725c4060f # v1.0.0env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}@@ -78,7 +78,7 @@ jobs:permissions:contents: writesteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Read versionid: versiondiff --git a/.github/workflows/e2e-ui.yml b/.github/workflows/e2e-ui.ymlindex 8e97242fb..441d6fddc 100644--- a/.github/workflows/e2e-ui.yml+++ b/.github/workflows/e2e-ui.yml@@ -1,69 +1,154 @@name: E2E UI-# Playwright browser E2E for the web UI (community today; extends to the full-# UI over time). Runs on PRs that touch the web app, so UI regressions are-# caught BEFORE merge — the right gate point (a `release:` bump only changes-# version numbers, so gating there catches nothing). Keeps main green under a-# PR-only workflow; releases inherit that green state.on:+ push:+ branches: [main]pull_request:branches: [main]- paths:- - "src/web/**"- - "src/shared/**"- - "src/ws-do/**"- - ".github/workflows/e2e-ui.yml"+ merge_group:+ types: [checks_requested]+ schedule:+ - cron: "17 3 * * *"+ workflow_dispatch:++permissions:+ contents: readconcurrency:- group: e2e-ui-${{ github.ref }}+ group: e2e-ui-${{ github.event.pull_request.number || github.event.merge_group.head_sha || github.ref }}cancel-in-progress: truejobs:+ scope:+ name: UI Change Scope+ runs-on: ubuntu-latest+ timeout-minutes: 5+ outputs:+ run_ui_e2e: ${{ steps.scope.outputs.run_ui_e2e }}+ e2e_matrix: ${{ steps.scope.outputs.e2e_matrix }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ with:+ fetch-depth: 0+ - id: scope+ env:+ BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event_name == 'merge_group' && github.event.merge_group.base_sha || github.event.before }}+ HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}+ FORCE_FULL: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}+ run: |+ args=(--base "$BASE_SHA" --head "$HEAD_SHA" --output "$GITHUB_OUTPUT" --summary "$GITHUB_STEP_SUMMARY")+ if [[ "$FORCE_FULL" == "true" ]]; then args+=(--force-full); fi+ node scripts/ci/changed-scopes.mjs "${args[@]}"+ node scripts/ci/e2e-shards.mjs --output "$GITHUB_OUTPUT" --summary "$GITHUB_STEP_SUMMARY"+e2e-ui:- name: UI Playwright E2E+ name: UI Playwright E2E (${{ matrix.shard }}/${{ matrix.total }})+ needs: scope+ if: needs.scope.outputs.run_ui_e2e == 'true'runs-on: ubuntu-latesttimeout-minutes: 20+ strategy:+ fail-fast: false+ matrix: ${{ fromJSON(needs.scope.outputs.e2e_matrix) }}env:- # next dev (development) is required — the dev email+password sign-in- # form and better-auth emailAndPassword are only enabled when NOT prod.BETTER_AUTH_SECRET: ci-e2e-ui-secretBETTER_AUTH_URL: http://localhost:3000steps:- - uses: actions/checkout@v7- - uses: pnpm/action-setup@v6- - uses: oven-sh/setup-bun@v2- - uses: actions/setup-node@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22cache: pnpm- run: pnpm install --frozen-lockfile-- - name: Create .dev.vars for local bindings- run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars-- - name: Install Playwright Chromium+ - run: printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\n' > src/web/.dev.vars+ - id: playwright-versionworking-directory: src/web- run: pnpm exec playwright install --with-deps chromium-- # global-setup runs db:reset, starts dev:web + dev:ws (fail-fast on ws- # health), and logs in the test users — so this single step drives the- # whole suite. Run from the repo root via the root alias (delegates to- # --filter @alook/web, which sets cwd so the Playwright config resolves).- - name: Run UI E2E- run: pnpm test:e2e-ui+ run: |+ node -p '"version=" + require("./node_modules/@playwright/test/package.json").version' >> "$GITHUB_OUTPUT"+ - id: playwright-browser-cache+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ~/.cache/ms-playwright+ key: playwright-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright-version.outputs.version }}+ - working-directory: src/web+ run: pnpm exec playwright install-deps chromium+ - if: steps.playwright-browser-cache.outputs.cache-hit != 'true'+ working-directory: src/web+ run: pnpm exec playwright install chromium+ - env:+ E2E_SPECS: ${{ toJSON(matrix.specs) }}+ run: |+ mapfile -t specs < <(node -e 'for (const spec of JSON.parse(process.env.E2E_SPECS)) console.log(spec)')+ pnpm --filter @alook/web exec playwright test "${specs[@]}"+ - if: ${{ !cancelled() && matrix.shard == 1 }}+ run: |+ test_package=$(realpath src/web/node_modules/@playwright/test)+ test_node_modules=$(dirname "$(dirname "$test_package")")+ playwright_package=$(realpath "$test_node_modules/playwright")+ playwright_node_modules=$(dirname "$playwright_package")+ core_package=$(realpath "$playwright_node_modules/playwright-core")+ runtime=src/web/playwright-merge-runtime/node_modules+ mkdir -p "$runtime/@playwright"+ cp -R "$test_package" "$runtime/@playwright/test"+ cp -R "$playwright_package" "$runtime/playwright"+ cp -R "$core_package" "$runtime/playwright-core"+ - if: ${{ !cancelled() && matrix.shard == 1 }}+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:+ name: playwright-merge-runtime+ path: src/web/playwright-merge-runtime/+ retention-days: 1+ - if: ${{ !cancelled() }}+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:+ name: blob-report-${{ matrix.shard }}+ path: src/web/blob-report/+ retention-days: 1+ - if: failure()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7+ with:+ name: playwright-artifacts-${{ matrix.shard }}+ path: src/web/test-results/+ retention-days: 14- - name: Upload Playwright report- if: ${{ !cancelled() }}- uses: actions/upload-artifact@v7+ merge-reports:+ name: Merge Playwright Reports+ needs: [scope, e2e-ui]+ if: ${{ !cancelled() && needs.scope.outputs.run_ui_e2e == 'true' }}+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8+ with:+ pattern: blob-report-*+ path: all-blob-reports+ merge-multiple: true+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8+ with:+ name: playwright-merge-runtime+ path: playwright-merge-runtime+ - run: node playwright-merge-runtime/node_modules/@playwright/test/cli.js merge-reports --reporter html all-blob-reports+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7with:name: playwright-report- path: src/web/playwright-report/- retention-days: 30+ path: playwright-report/+ retention-days: 14- - name: Upload traces & videos- if: failure()- uses: actions/upload-artifact@v7- with:- name: playwright-artifacts- path: src/web/test-results/- retention-days: 30+ ui-e2e-gate:+ name: UI E2E Gate+ if: always()+ needs: [scope, e2e-ui, merge-reports]+ runs-on: ubuntu-latest+ timeout-minutes: 5+ env:+ CI_GATE_RESULTS: >-+ [+ {"name":"scope","expected":true,"result":"${{ needs.scope.result }}"},+ {"name":"e2e-ui","expected":${{ needs.scope.outputs.run_ui_e2e == 'true' }},"result":"${{ needs.e2e-ui.result }}"},+ {"name":"merge-reports","expected":${{ needs.scope.outputs.run_ui_e2e == 'true' }},"result":"${{ needs.merge-reports.result }}"}+ ]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - run: node scripts/ci/assert-gate.mjsdiff --git a/.github/workflows/lint-workflows.yaml b/.github/workflows/lint-workflows.yamlindex 0d4e5f924..943c99cf5 100644--- a/.github/workflows/lint-workflows.yaml+++ b/.github/workflows/lint-workflows.yaml@@ -1,14 +1,25 @@name: Lint Workflowson:+ push:+ branches: [main]+ paths:+ - ".github/workflows/**"pull_request:paths:- ".github/workflows/**"+permissions:+ contents: read++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true+jobs:actionlint:runs-on: ubuntu-latesttimeout-minutes: 5steps:- - uses: actions/checkout@v7- - uses: raven-actions/actionlint@v2+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ - uses: raven-actions/actionlint@3d39aea434753780c3b3d4a1a31c854b4dbf49d7 # v2diff --git a/.github/workflows/mobile-release.yml b/.github/workflows/mobile-release.ymlindex b7af55fa8..a9c2d84bb 100644--- a/.github/workflows/mobile-release.yml+++ b/.github/workflows/mobile-release.yml@@ -6,23 +6,26 @@ on:paths:- "src/desktop/.deploy-version-mobile"+permissions:+ contents: read+jobs:ios:runs-on: macos-latesttimeout-minutes: 45steps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22- name: Install pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6- name: Install Rust stable- uses: dtolnay/rust-toolchain@stable+ uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stablewith:targets: aarch64-apple-ios@@ -51,29 +54,29 @@ jobs:runs-on: ubuntu-22.04timeout-minutes: 45steps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Setup Node.js- uses: actions/setup-node@v7+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7with:node-version: 22- name: Install pnpm- uses: pnpm/action-setup@v6+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6- name: Install Rust stable- uses: dtolnay/rust-toolchain@stable+ uses: dtolnay/rust-toolchain@4360b52568e2003a75bf9bc1d59f33a8e3fc893c # stablewith:targets: aarch64-linux-android,armv7-linux-androideabi- name: Setup Java- uses: actions/setup-java@v5+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5with:distribution: temurinjava-version: 17- name: Setup Android SDK- uses: android-actions/setup-android@v4+ uses: android-actions/setup-android@40fd30fb8d7440372e1316f5d1809ec01dcd3699 # v4- name: Install Android NDKrun: sdkmanager "ndk;27.0.12077973"@@ -102,7 +105,7 @@ jobs:NDK_HOME: /usr/local/lib/android/sdk/ndk/27.0.12077973- name: Upload to Google Play- uses: r0adkll/upload-google-play@v1+ uses: r0adkll/upload-google-play@e738b9dd8f2476ea806d921b64aacd24f34515a5 # v1with:serviceAccountJsonPlainText: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT }}packageName: ai.alook.desktopdiff --git a/.github/workflows/publish-app.yml b/.github/workflows/publish-app.ymlindex 1b9901b6a..cf6e95ee4 100644--- a/.github/workflows/publish-app.yml+++ b/.github/workflows/publish-app.yml@@ -15,9 +15,10 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 30permissions:+ contents: readid-token: writesteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Detect versionid: version@@ -35,13 +36,13 @@ jobs:echo "skip=false" >> "$GITHUB_OUTPUT"fi- - uses: pnpm/action-setup@v6+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6if: steps.check.outputs.skip == 'false'- - uses: oven-sh/setup-bun@v2+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2if: steps.check.outputs.skip == 'false'- - uses: actions/setup-node@v7+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7if: steps.check.outputs.skip == 'false'with:node-version: 22diff --git a/.github/workflows/publish-cli.yml b/.github/workflows/publish-cli.ymlindex 7734b3ad4..8a8caaaf3 100644--- a/.github/workflows/publish-cli.yml+++ b/.github/workflows/publish-cli.yml@@ -15,9 +15,10 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 10permissions:+ contents: readid-token: writesteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Detect versionid: version@@ -35,13 +36,13 @@ jobs:echo "skip=false" >> "$GITHUB_OUTPUT"fi- - uses: pnpm/action-setup@v6+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6if: steps.check.outputs.skip == 'false'- - uses: oven-sh/setup-bun@v2+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2if: steps.check.outputs.skip == 'false'- - uses: actions/setup-node@v7+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7if: steps.check.outputs.skip == 'false'with:node-version: 22@@ -65,4 +66,3 @@ jobs:if: steps.check.outputs.skip == 'false'working-directory: src/clirun: npm publish --access public-diff --git a/.github/workflows/publish-daemon.yml b/.github/workflows/publish-daemon.ymlindex 0e486e9af..0a0e59edb 100644--- a/.github/workflows/publish-daemon.yml+++ b/.github/workflows/publish-daemon.yml@@ -15,9 +15,10 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 10permissions:+ contents: readid-token: writesteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- name: Detect versionid: version@@ -35,13 +36,13 @@ jobs:echo "skip=false" >> "$GITHUB_OUTPUT"fi- - uses: pnpm/action-setup@v6+ - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6if: steps.check.outputs.skip == 'false'- - uses: oven-sh/setup-bun@v2+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2if: steps.check.outputs.skip == 'false'- - uses: actions/setup-node@v7+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7if: steps.check.outputs.skip == 'false'with:node-version: 22diff --git a/AGENTS.md b/AGENTS.mdindex de1ab2c06..1d5726c92 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -118,6 +118,7 @@ Required fields (see `src/web/src/lib/blog/types.ts`): `slug`, `title`, `date`,- Path: `src/web/public/blog/<slug>/<name>.<ext>`, referenced from MDX as `/blog/<slug>/<name>.<ext>`.- Naming: short semantic names (`hero.png`, `timeline.png`, `workflow-1-dev-team-pipeline.svg`). No date prefix. Don't repeat the slug — the parent directory already carries it.- Format: `png` for photos/screenshots, `svg` for diagrams, `webp` when compression matters. Pick one; don't mix formats for the same purpose in one post.+- CI accepts `.jpg`, `.jpeg`, `.png`, `.svg`, and `.webp`; each referenced image must be at most 2 MiB.- **Safe margin (anti-crop):** keep ≥8% of the shorter side (and ≥64px) empty cream/bg padding on all four edges. Blog MDX applies `rounded-lg` on `img`, so ink or labels flush to the canvas edge get clipped. Do not stretch-crop heroes into OG size if that eats the margin — letterbox on `#FEFDFB` instead.## Scrollbardiff --git a/package.json b/package.jsonindex c8e0d921a..9390d98c6 100644--- a/package.json+++ b/package.json@@ -4,7 +4,7 @@"packageManager": "[email protected]","scripts": {"build": "turbo run build",- "test": "turbo run test",+ "test": "turbo run test && vitest run --project ci-scripts","predev": "[ -f src/web/.dev.vars ] || (cp src/web/.dev.vars.example src/web/.dev.vars && sed -i '' \"s|^BETTER_AUTH_SECRET=$|BETTER_AUTH_SECRET=$(openssl rand -base64 32)|\" src/web/.dev.vars && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$(openssl rand -base64 32)|\" src/web/.dev.vars && echo '✓ Generated src/web/.dev.vars (fill in OAuth keys if needed)'); [ -f src/email-worker/.dev.vars ] || (cp src/email-worker/.dev.vars.example src/email-worker/.dev.vars && KEY=$(grep '^ENCRYPTION_KEY=' src/web/.dev.vars | cut -d= -f2-) && sed -i '' \"s|^ENCRYPTION_KEY=$|ENCRYPTION_KEY=$KEY|\" src/email-worker/.dev.vars && echo '✓ Generated src/email-worker/.dev.vars (synced ENCRYPTION_KEY from web)')","dev": "turbo run dev --filter=@alook/web --filter=@alook/email-worker --filter=@alook/ws-do --filter=@alook/wake-worker --filter=@alook/shared","clean": "rm -rf node_modules src/*/node_modules src/*/dist src/*/.turbo .turbo src/web/.next src/web/.open-next src/*/.wrangler .alook",@@ -64,4 +64,4 @@"workerd"]}-}\ No newline at end of file+}diff --git a/scripts/ci/assert-gate.mjs b/scripts/ci/assert-gate.mjsnew file mode 100644index 000000000..8d508d743--- /dev/null+++ b/scripts/ci/assert-gate.mjs@@ -0,0 +1,25 @@+const raw = process.env.CI_GATE_RESULTS++if (!raw) {+ throw new Error("CI_GATE_RESULTS is required")+}++const checks = JSON.parse(raw)+const errors = []++for (const check of checks) {+ const expected = check.expected === true || check.expected === "true"+ const accepted = expected ? check.result === "success" : check.result === "skipped"+ if (!accepted) {+ errors.push(+ `${check.name}: expected ${expected ? "success" : "skipped"}, received ${check.result}`+ )+ }+}++if (errors.length > 0) {+ process.stderr.write(`${errors.join("\n")}\n`)+ process.exit(1)+}++process.stdout.write("All expected CI jobs completed successfully.\n")diff --git a/scripts/ci/assert-gate.test.ts b/scripts/ci/assert-gate.test.tsnew file mode 100644index 000000000..f8295e06f--- /dev/null+++ b/scripts/ci/assert-gate.test.ts@@ -0,0 +1,37 @@+import { spawnSync } from "node:child_process"+import { fileURLToPath } from "node:url"+import { describe, expect, it } from "vitest"++const script = fileURLToPath(new URL("./assert-gate.mjs", import.meta.url))++function run(checks: unknown) {+ return spawnSync(process.execPath, [script], {+ encoding: "utf8",+ env: { ...process.env, CI_GATE_RESULTS: JSON.stringify(checks) },+ })+}++describe("assert-gate", () => {+ it("accepts successful required jobs and skipped out-of-scope jobs", () => {+ const result = run([+ { name: "quality", expected: true, result: "success" },+ { name: "rust", expected: false, result: "skipped" },+ ])++ expect(result.status).toBe(0)+ })++ it("rejects failed, cancelled, and unexpectedly skipped required jobs", () => {+ for (const status of ["failure", "cancelled", "skipped"]) {+ const result = run([{ name: "quality", expected: true, result: status }])+ expect(result.status).toBe(1)+ expect(result.stderr).toContain(`received ${status}`)+ }+ })++ it("rejects an unexpected out-of-scope execution", () => {+ const result = run([{ name: "rust", expected: false, result: "success" }])++ expect(result.status).toBe(1)+ })+})diff --git a/scripts/ci/changed-scopes.mjs b/scripts/ci/changed-scopes.mjsnew file mode 100644index 000000000..780669f4f--- /dev/null+++ b/scripts/ci/changed-scopes.mjs@@ -0,0 +1,189 @@+import { execFileSync } from "node:child_process"+import { appendFileSync, readFileSync } from "node:fs"+import { resolve } from "node:path"+import { fileURLToPath } from "node:url"++const BLOG_CONTENT = /^src\/web\/src\/content\/.*\.mdx$/+const BLOG_ASSET = /^src\/web\/public\/blog(?:\/|$)/+const MARKDOWN = /(?:^|\/)\w[^/]*\.md$/i+const WORKFLOW = /^\.github\/workflows\//+const GLOBAL_PATHS = new Set([+ "package.json",+ "pnpm-lock.yaml",+ "pnpm-workspace.yaml",+ "turbo.json",+ "tsconfig.json",+ "vitest.config.ts",+])+const KNOWN_ROOTS = [+ ".github/",+ ".claude/",+ ".openai/",+ "docs/",+ "scripts/",+ "src/",+ "tests/",+]++function normalizePath(path) {+ return path.replaceAll("\\", "/").replace(/^\.\//, "")+}++function isBlogPath(path) {+ return BLOG_CONTENT.test(path) || BLOG_ASSET.test(path)+}++function isMarkdownPath(path) {+ return MARKDOWN.test(path)+}++function isKnownPath(path) {+ return (+ isMarkdownPath(path) ||+ isBlogPath(path) ||+ GLOBAL_PATHS.has(path) ||+ KNOWN_ROOTS.some((root) => path.startsWith(root))+ )+}++export function classifyPaths(inputPaths, options = {}) {+ const paths = [...new Set(inputPaths.map(normalizePath).filter(Boolean))].sort()+ const empty = paths.length === 0+ const docsOnly = !empty && paths.every(isMarkdownPath)+ const blogOnly = !empty && paths.every(isBlogPath)+ const contentMix =+ !docsOnly && !blogOnly && paths.every((path) => isMarkdownPath(path) || isBlogPath(path))+ const workflowChanged = paths.some((path) => WORKFLOW.test(path))+ const globalChanged = paths.some(+ (path) =>+ GLOBAL_PATHS.has(path) ||+ path.startsWith("scripts/") ||+ (path.startsWith(".github/") && !isMarkdownPath(path))+ )+ const unknownChanged = paths.some((path) => !isKnownPath(path))+ const forceFull = options.forceFull === true+ const full = empty || forceFull || contentMix || workflowChanged || globalChanged || unknownChanged+ const effectiveDocsOnly = docsOnly && !full+ const effectiveBlogOnly = blogOnly && !full+ const web = full || paths.some((path) => path.startsWith("src/web/"))+ const shared = full || paths.some((path) => path.startsWith("src/shared/"))+ const cli = full || paths.some((path) => path.startsWith("src/cli/"))+ const daemon = full || paths.some((path) => path.startsWith("src/daemon/"))+ const desktop = full || paths.some((path) => path.startsWith("src/desktop/"))+ const wsDo = full || paths.some((path) => path.startsWith("src/ws-do/"))+ const worker =+ full ||+ paths.some(+ (path) =>+ path.startsWith("src/email-worker/") ||+ path.startsWith("src/wake-worker/") ||+ path.startsWith("src/ws-do/")+ )+ const app = full || paths.some((path) => path.startsWith("src/app/"))+ const codeChanged =+ full || paths.some((path) => !isMarkdownPath(path) && !isBlogPath(path))+ const runCodeChecks = codeChanged && !effectiveBlogOnly && !effectiveDocsOnly++ return {+ paths,+ full,+ docs_only: effectiveDocsOnly,+ blog_only: effectiveBlogOnly,+ workflow_changed: workflowChanged,+ run_code_checks: runCodeChecks,+ run_windows: runCodeChecks && (full || cli || daemon || shared),+ run_e2e: runCodeChecks && (full || web || shared || cli || daemon || worker),+ run_ui_e2e: !effectiveBlogOnly && runCodeChecks && (full || web || shared || wsDo),+ run_rust: runCodeChecks && (full || desktop),+ run_lighthouse: runCodeChecks && (full || web),+ run_knip: runCodeChecks && (full || app || cli || shared || web || worker),+ }+}++export function parseNameStatus(buffer) {+ const fields = buffer.toString("utf8").split("\0")+ const paths = []+ for (let index = 0; index < fields.length; ) {+ const status = fields[index++]+ if (!status) continue+ const firstPath = fields[index++]+ if (firstPath) paths.push(firstPath)+ if (status.startsWith("R") || status.startsWith("C")) {+ const secondPath = fields[index++]+ if (secondPath) paths.push(secondPath)+ }+ }+ return paths+}++function readChangedPaths(args) {+ if (args.forceFull) return []+ if (args.pathsFile) {+ return readFileSync(resolve(args.pathsFile), "utf8")+ .split(/\r?\n/)+ .filter(Boolean)+ }+ if (!args.base || !args.head) {+ throw new Error("Both --base and --head are required")+ }+ const diff = execFileSync(+ "git",+ ["diff", "--name-status", "-z", "--find-renames", `${args.base}...${args.head}`],+ { stdio: ["ignore", "pipe", "pipe"] }+ )+ return parseNameStatus(diff)+}++function parseArgs(argv) {+ const args = { forceFull: false }+ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index]+ if (arg === "--force-full") {+ args.forceFull = true+ continue+ }+ const key = arg.replace(/^--/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())+ args[key] = argv[++index]+ }+ return args+}++function writeOutputs(path, result) {+ const output = Object.entries(result)+ .filter(([key]) => key !== "paths")+ .map(([key, value]) => `${key}=${String(value)}`)+ .join("\n")+ appendFileSync(path, `${output}\n`)+}++function writeSummary(path, result, fallbackReason) {+ const flags = Object.entries(result)+ .filter(([key]) => key !== "paths")+ .map(([key, value]) => `| \`${key}\` | \`${value}\` |`)+ .join("\n")+ const changed = result.paths.map((item) => `- \`${item}\``).join("\n") || "- none"+ const fallback = fallbackReason ? `\nFail-closed reason: ${fallbackReason}\n` : ""+ appendFileSync(+ path,+ `## CI scope\n${fallback}\n| Output | Value |\n| --- | --- |\n${flags}\n\n<details><summary>Changed paths</summary>\n\n${changed}\n\n</details>\n`+ )+}++export function runCli(argv) {+ const args = parseArgs(argv)+ let result+ let fallbackReason = ""+ try {+ result = classifyPaths(readChangedPaths(args), { forceFull: args.forceFull })+ } catch (error) {+ fallbackReason = error instanceof Error ? error.message : String(error)+ result = classifyPaths([], { forceFull: true })+ }+ if (args.output) writeOutputs(args.output, result)+ if (args.summary) writeSummary(args.summary, result, fallbackReason)+ if (!args.output) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ runCli(process.argv.slice(2))+}diff --git a/scripts/ci/changed-scopes.test.ts b/scripts/ci/changed-scopes.test.tsnew file mode 100644index 000000000..30750c0ea--- /dev/null+++ b/scripts/ci/changed-scopes.test.ts@@ -0,0 +1,107 @@+import { mkdtempSync, readFileSync, rmSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { describe, expect, it } from "vitest"+import { classifyPaths, parseNameStatus, runCli } from "./changed-scopes.mjs"++describe("classifyPaths", () => {+ it("selects the strict blog fast path for MDX and blog assets", () => {+ const result = classifyPaths([+ "src/web/src/content/example.mdx",+ "src/web/public/blog/example/hero.webp",+ ])++ expect(result.blog_only).toBe(true)+ expect(result.run_code_checks).toBe(false)+ expect(result.run_ui_e2e).toBe(false)+ })++ it("selects no package work for markdown-only changes", () => {+ const result = classifyPaths(["README.md", "docs/operations.md"])++ expect(result.docs_only).toBe(true)+ expect(result.run_code_checks).toBe(false)+ })++ it("disables the blog fast path when content is mixed with docs", () => {+ const result = classifyPaths([+ "src/web/src/content/example.mdx",+ "README.md",+ ])++ expect(result.blog_only).toBe(false)+ expect(result.full).toBe(true)+ })++ it("keeps Windows for shared and CLI changes", () => {+ expect(classifyPaths(["src/shared/src/schema.ts"]).run_windows).toBe(true)+ expect(classifyPaths(["src/cli/src/index.ts"]).run_windows).toBe(true)+ expect(classifyPaths(["src/web/src/app/page.tsx"]).run_windows).toBe(false)+ })++ it("routes web runtime changes through browser and Lighthouse checks", () => {+ const result = classifyPaths(["src/web/src/app/page.tsx"])++ expect(result.run_ui_e2e).toBe(true)+ expect(result.run_lighthouse).toBe(true)+ expect(result.run_e2e).toBe(true)+ })++ it("routes desktop-only changes through Rust without UI E2E", () => {+ const result = classifyPaths(["src/desktop/src-tauri/src/lib.rs"])++ expect(result.run_rust).toBe(true)+ expect(result.run_ui_e2e).toBe(false)+ })++ it("fails closed for workflows, root configuration, unknown paths, and empty diffs", () => {+ expect(classifyPaths([".github/workflows/ci.yml"]).full).toBe(true)+ expect(classifyPaths([".github/dependabot.yml"]).full).toBe(true)+ expect(classifyPaths(["scripts/bump-version.mjs"]).full).toBe(true)+ expect(classifyPaths(["pnpm-lock.yaml"]).full).toBe(true)+ expect(classifyPaths(["unexpected/file.txt"]).full).toBe(true)+ expect(classifyPaths([]).full).toBe(true)+ })++ it("honors an explicit full run", () => {+ const result = classifyPaths(["src/web/src/content/example.mdx"], {+ forceFull: true,+ })++ expect(result.full).toBe(true)+ expect(result.blog_only).toBe(false)+ expect(result.run_windows).toBe(true)+ })+})++describe("parseNameStatus", () => {+ it("includes both sides of renames and copies", () => {+ const input = Buffer.from(+ "M\0src/web/src/content/a.mdx\0R100\0src/cli/a.ts\0src/web/src/content/a.mdx\0C090\0old.ts\0new.ts\0"+ )++ expect(parseNameStatus(input)).toEqual([+ "src/web/src/content/a.mdx",+ "src/cli/a.ts",+ "src/web/src/content/a.mdx",+ "old.ts",+ "new.ts",+ ])+ })+})++describe("runCli", () => {+ it("writes full-CI outputs when the diff cannot be resolved", () => {+ const directory = mkdtempSync(join(tmpdir(), "alook-ci-scope-"))+ const output = join(directory, "output")+ try {+ runCli(["--base", "missing-base", "--head", "missing-head", "--output", output])+ const values = readFileSync(output, "utf8")+ expect(values).toContain("full=true")+ expect(values).toContain("run_windows=true")+ expect(values).toContain("run_ui_e2e=true")+ } finally {+ rmSync(directory, { recursive: true, force: true })+ }+ })+})diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjsnew file mode 100644index 000000000..134b8b6fc--- /dev/null+++ b/scripts/ci/e2e-shards.mjs@@ -0,0 +1,129 @@+import { appendFileSync, readdirSync } from "node:fs"+import { relative, resolve } from "node:path"+import { fileURLToPath } from "node:url"++export const E2E_SPEC_ROOT = "src/web/src/test/e2e-ui"+export const E2E_SHARD_COUNT = 2+export const DEFAULT_SPEC_SECONDS = 60++export const SPEC_SECONDS = {+ "01-auth.spec.ts": 5,+ "02-server-channel-message.spec.ts": 75,+ "03-realtime-multiuser.spec.ts": 63,+ "04-dm.spec.ts": 42,+ "05-mention-bot.spec.ts": 15,+ "06-channel-member-admin.spec.ts": 17,+ "07-invite.spec.ts": 10,+ "08-mobile.spec.ts": 7,+ "09-forum-thread.spec.ts": 35,+ "10-eject-nav-auth.spec.ts": 30,+ "11-profile-ui-stability.spec.ts": 9,+ "12-friends.spec.ts": 6,+ "13-mentions.spec.ts": 50,+ "14-forum-post-tags-presence.spec.ts": 59,+ "15-mention-scope.spec.ts": 74,+ "16-jump-to-present.spec.ts": 30,+ "17-forum-sidebar-stage-b.spec.ts": 35,+ "18-new-divider-scroll.spec.ts": 46,+}++function walk(directory) {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const path = resolve(directory, entry.name)+ return entry.isDirectory() ? walk(path) : [path]+ })+}++export function discoverE2eSpecs(root = resolve(E2E_SPEC_ROOT)) {+ return walk(root)+ .filter((path) => path.endsWith(".spec.ts"))+ .map((path) => relative(root, path).replaceAll("\\", "/"))+ .sort()+}++export function planE2eShards(+ specs,+ shardCount = E2E_SHARD_COUNT,+ weights = SPEC_SECONDS,+ defaultSeconds = DEFAULT_SPEC_SECONDS,+) {+ if (!Number.isInteger(shardCount) || shardCount < 1) {+ throw new Error("shardCount must be a positive integer")+ }++ const uniqueSpecs = [...new Set(specs)]+ if (uniqueSpecs.length !== specs.length) {+ throw new Error("spec paths must be unique")+ }+ if (uniqueSpecs.length === 0) {+ throw new Error("at least one spec is required")+ }++ const effectiveShardCount = Math.min(shardCount, uniqueSpecs.length)+ const shards = Array.from({ length: effectiveShardCount }, (_, index) => ({+ shard: index + 1,+ predicted_seconds: 0,+ files: [],+ }))++ const weighted = uniqueSpecs+ .map((path) => ({ path, seconds: weights[path] ?? defaultSeconds }))+ .sort((left, right) => right.seconds - left.seconds || left.path.localeCompare(right.path))++ for (const spec of weighted) {+ const target = [...shards].sort(+ (left, right) => left.predicted_seconds - right.predicted_seconds || left.shard - right.shard,+ )[0]+ target.files.push(spec.path)+ target.predicted_seconds += spec.seconds+ }++ return shards.map((shard) => ({+ ...shard,+ files: shard.files.sort(),+ }))+}++export function createE2eMatrix(specs = discoverE2eSpecs()) {+ const shards = planE2eShards(specs)+ return {+ include: shards.map((shard) => ({+ shard: shard.shard,+ total: shards.length,+ predicted_seconds: shard.predicted_seconds,+ specs: shard.files.map((path) => `src/test/e2e-ui/${path}`),+ })),+ }+}++function parseArgs(argv) {+ const args = {}+ for (let index = 0; index < argv.length; index += 1) {+ const key = argv[index].replace(/^--/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())+ args[key] = argv[++index]+ }+ return args+}++function writeSummary(path, matrix) {+ const rows = matrix.include+ .map((shard) => `| ${shard.shard}/${shard.total} | ${shard.predicted_seconds}s | \`${shard.specs.join(" ")}\` |`)+ .join("\n")+ appendFileSync(+ path,+ `## UI E2E shards\n\n| Shard | Predicted | Specs |\n| --- | ---: | --- |\n${rows}\n`,+ )+}++export function runCli(argv) {+ const args = parseArgs(argv)+ const matrix = createE2eMatrix()+ const json = JSON.stringify(matrix)+ if (args.output) appendFileSync(args.output, `e2e_matrix=${json}\n`)+ if (args.summary) writeSummary(args.summary, matrix)+ if (!args.output) process.stdout.write(`${JSON.stringify(matrix, null, 2)}\n`)+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ runCli(process.argv.slice(2))+}diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.tsnew file mode 100644index 000000000..fe4842193--- /dev/null+++ b/scripts/ci/e2e-shards.test.ts@@ -0,0 +1,73 @@+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { describe, expect, it } from "vitest"+import {+ createE2eMatrix,+ discoverE2eSpecs,+ E2E_SHARD_COUNT,+ planE2eShards,+} from "./e2e-shards.mjs"++describe("discoverE2eSpecs", () => {+ it("discovers nested specs in deterministic order", () => {+ const root = mkdtempSync(join(tmpdir(), "alook-e2e-specs-"))+ try {+ mkdirSync(join(root, "nested"))+ writeFileSync(join(root, "z.spec.ts"), "")+ writeFileSync(join(root, "nested", "a.spec.ts"), "")+ writeFileSync(join(root, "ignored.ts"), "")++ expect(discoverE2eSpecs(root)).toEqual(["nested/a.spec.ts", "z.spec.ts"])+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+ })+})++describe("planE2eShards", () => {+ it("assigns every spec exactly once with deterministic duration balance", () => {+ const specs = discoverE2eSpecs()+ const first = planE2eShards(specs)+ const second = planE2eShards([...specs].reverse())+ const assigned = first.flatMap((shard) => shard.files)+ const totals = first.map((shard) => shard.predicted_seconds)++ expect(first).toEqual(second)+ expect(first).toHaveLength(E2E_SHARD_COUNT)+ expect([...assigned].sort()).toEqual(specs)+ expect(new Set(assigned).size).toBe(specs.length)+ expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)+ })++ it("includes an unknown spec with a conservative default weight", () => {+ const shards = planE2eShards(["known.spec.ts", "new.spec.ts"], 2, {+ "known.spec.ts": 5,+ }, 60)++ expect(shards.flatMap((shard) => shard.files).sort()).toEqual([+ "known.spec.ts",+ "new.spec.ts",+ ])+ expect(shards.map((shard) => shard.predicted_seconds).sort((a, b) => a - b)).toEqual([5, 60])+ })++ it("rejects duplicate paths and invalid shard counts", () => {+ expect(() => planE2eShards(["a.spec.ts", "a.spec.ts"])).toThrow("unique")+ expect(() => planE2eShards([])).toThrow("at least one")+ expect(() => planE2eShards(["a.spec.ts"], 0)).toThrow("positive integer")+ })+})++describe("createE2eMatrix", () => {+ it("emits shell-safe repo-local spec arguments", () => {+ const matrix = createE2eMatrix(["a.spec.ts", "nested/b.spec.ts"])+ const argumentsList = matrix.include.flatMap((entry) => entry.specs)++ expect(argumentsList.sort()).toEqual([+ "src/test/e2e-ui/a.spec.ts",+ "src/test/e2e-ui/nested/b.spec.ts",+ ])+ expect(matrix.include.every((entry) => entry.total === 2)).toBe(true)+ })+})diff --git a/scripts/ci/vitest.config.ts b/scripts/ci/vitest.config.tsnew file mode 100644index 000000000..4d393e173--- /dev/null+++ b/scripts/ci/vitest.config.ts@@ -0,0 +1,9 @@+import { defineProject } from "vitest/config"++export default defineProject({+ test: {+ name: "ci-scripts",+ environment: "node",+ include: ["**/*.test.ts"],+ },+})diff --git a/src/web/playwright.config.ts b/src/web/playwright.config.tsindex 6f71fde6a..039a5b68e 100644--- a/src/web/playwright.config.ts+++ b/src/web/playwright.config.ts@@ -11,7 +11,7 @@ export default defineConfig({// single-worker and zero-retry; parallelism or retries would reuse state.retries: 0,workers: 1,- reporter: process.env.CI ? [["html", { open: "never" }], ["list"]] : "list",+ reporter: process.env.CI ? [["blob"], ["list"]] : "list",globalSetup: "./src/test/e2e-ui/_setup/global-setup.ts",globalTeardown: "./src/test/e2e-ui/_setup/global-teardown.ts",timeout: 60_000,diff --git a/src/web/src/lib/blog/validate-assets.test.ts b/src/web/src/lib/blog/validate-assets.test.tsindex c946fa62b..c4ccf2262 100644--- a/src/web/src/lib/blog/validate-assets.test.ts+++ b/src/web/src/lib/blog/validate-assets.test.ts@@ -4,6 +4,7 @@ import {collectBlogAssetErrors,findBlogImageErrors,findDuplicateMdxH1Errors,+ readBlogMetadata,runValidateBlogAssetsCli,validateBlogAssets,type BlogAssetFs,@@ -14,6 +15,74 @@ function norm(p: string): string {return p.replace(/\\/g, "/");}+function post(slug = "demo", body = "## Section"): string {+ return `export const metadata = {+ slug: "${slug}",+ title: "Demo",+ date: "2026-08-11",+ author: "Alook Team",+ excerpt: "Demo excerpt",+ readingTime: "2 min read",+};++${body}+`;+}++describe("readBlogMetadata", () => {+ it("reads required metadata and accepts valid dates", () => {+ expect(readBlogMetadata(post(), "demo")).toEqual({+ metadata: {+ slug: "demo",+ title: "Demo",+ date: "2026-08-11",+ author: "Alook Team",+ excerpt: "Demo excerpt",+ readingTime: "2 min read",+ },+ errors: [],+ });+ });++ it("rejects missing fields, invalid dates, and filename mismatches", () => {+ const content = `export const metadata = {+ slug: "other",+ title: "Demo",+ date: "2026-02-30",+ author: "Alook Team",+ excerpt: "Demo excerpt",+};`;+ const result = readBlogMetadata(content, "demo");++ expect(result.errors).toEqual(+ expect.arrayContaining([+ '[post: demo] Missing or empty metadata field "readingTime".',+ '[post: demo] Metadata slug "other" must match filename "demo.mdx".',+ '[post: demo] Metadata field "date" must be a valid YYYY-MM-DD date.',+ ])+ );+ });++ it("rejects backwards modified dates and invalid reading time", () => {+ const content = post()+ .replace('date: "2026-08-11",', 'date: "2026-08-11",\n dateModified: "2026-08-10",')+ .replace('readingTime: "2 min read",', 'readingTime: "about two minutes",');+ const result = readBlogMetadata(content, "demo");++ expect(result.errors).toEqual([+ "[post: demo] Metadata dateModified cannot be earlier than date.",+ '[post: demo] Metadata readingTime must use "N min read".',+ ]);+ });++ it("rejects missing and unterminated metadata objects", () => {+ expect(readBlogMetadata("## Body", "demo").errors[0]).toContain("Missing or unterminated");+ expect(+ readBlogMetadata('export const metadata = { slug: "demo"', "demo").errors[0]+ ).toContain("Missing or unterminated");+ });+});+describe("findDuplicateMdxH1Errors", () => {it("flags markdown H1 lines with line numbers", () => {const content = ["export const metadata = {};", "", "# Hello Title", "", "Body"].join(@@ -34,7 +103,7 @@ describe("findBlogImageErrors", () => {it("requires /blog/ image prefix", () => {const content = "\n";expect(findBlogImageErrors(content, "demo", "/public", () => true)).toEqual([- '[post: demo] Image src "/images/hero.png" must start with /blog/ — move the file to public/blog/',+ '[post: demo] Image src "/images/hero.png" must start with /blog/demo/ — move the file to the post\'s public/blog directory.',]);});@@ -49,6 +118,26 @@ describe("findBlogImageErrors", () => {const content = '\n<img src="/blog/demo/b.png" />\n';expect(findBlogImageErrors(content, "demo", "/public", () => true)).toEqual([]);});++ it("validates metadata images, extensions, and file size", () => {+ expect(+ findBlogImageErrors("", "demo", "/public", () => true, "/blog/demo/hero.gif")+ ).toEqual([+ '[post: demo] Image src "/blog/demo/hero.gif" must use jpg, jpeg, png, svg, or webp.',+ ]);+ expect(+ findBlogImageErrors(+ "",+ "demo",+ "/public",+ () => true,+ "/blog/demo/hero.webp",+ () => 2 * 1024 * 1024 + 1+ )+ ).toEqual([+ "[post: demo] Image file exceeds 2 MiB: public/blog/demo/hero.webp",+ ]);+ });});describe("collectBlogAssetErrors", () => {@@ -75,7 +164,7 @@ describe("validateBlogAssets", () => {const fs: BlogAssetFs = {existsSync: (path) =>norm(path) === "/content" || norm(path) === norm(heroPath),- readFileSync: () => "\n\n## Section\n",+ readFileSync: () => post("demo", "\n\n## Section"),readdirSync: () => ["demo.mdx", "readme.txt"],};expect(validateBlogAssets("/content", "/public", fs)).toEqual({@@ -86,7 +175,7 @@ describe("validateBlogAssets", () => {it("returns failed with duplicate H1 errors", () => {const fs: BlogAssetFs = {existsSync: (path) => norm(path) === "/content",- readFileSync: () => "# Title\n\nBody\n",+ readFileSync: () => post("demo", "# Title\n\nBody"),readdirSync: () => ["demo.mdx"],};const result = validateBlogAssets("/content", "/public", fs);@@ -95,6 +184,20 @@ describe("validateBlogAssets", () => {expect(result.errors[0]).toContain("Duplicate H1");}});++ it("returns failed for duplicate metadata slugs", () => {+ const fs: BlogAssetFs = {+ existsSync: (path) => norm(path) === "/content",+ readFileSync: () => post("same"),+ readdirSync: () => ["one.mdx", "two.mdx"],+ };+ const result = validateBlogAssets("/content", "/public", fs);++ expect(result.status).toBe("failed");+ if (result.status === "failed") {+ expect(result.errors.some((error) => error.includes("Duplicate metadata slug"))).toBe(true);+ }+ });});describe("runValidateBlogAssetsCli", () => {@@ -132,7 +235,7 @@ describe("runValidateBlogAssetsCli", () => {const fs: BlogAssetFs = {existsSync: (path) =>norm(path) === "/content" || norm(path) === norm(heroPath),- readFileSync: () => "\n",+ readFileSync: () => post("demo", ""),readdirSync: () => ["demo.mdx"],};runValidateBlogAssetsCli("/content", "/public", io, fs);@@ -144,7 +247,7 @@ describe("runValidateBlogAssetsCli", () => {const { io, errors, exits } = mockIo();const fs: BlogAssetFs = {existsSync: (path) => norm(path) === "/content",- readFileSync: () => "# Title\n",+ readFileSync: () => post("demo", "# Title"),readdirSync: () => ["demo.mdx"],};runValidateBlogAssetsCli("/content", "/public", io, fs);diff --git a/src/web/src/lib/blog/validate-assets.ts b/src/web/src/lib/blog/validate-assets.tsindex 0cd80f53d..6ada81383 100644--- a/src/web/src/lib/blog/validate-assets.ts+++ b/src/web/src/lib/blog/validate-assets.ts@@ -1,5 +1,5 @@-import { existsSync, readFileSync, readdirSync } from "fs";-import { join } from "path";+import { existsSync, readFileSync, readdirSync, statSync } from "fs";+import { extname, join } from "path";export type BlogAssetError = string;@@ -7,15 +7,146 @@ export type BlogAssetFs = {existsSync: (path: string) => boolean;readFileSync: (path: string, encoding: "utf-8") => string;readdirSync: (path: string) => string[];+ fileSize?: (path: string) => number;};const defaultFs: BlogAssetFs = {existsSync,readFileSync: (path, encoding) => readFileSync(path, encoding),readdirSync: (path) => readdirSync(path) as string[],+ fileSize: (path) => statSync(path).size,};-/** Markdown ATX `# Title` lines (not ## / ###). Page shell already owns the H1. */+const REQUIRED_METADATA_FIELDS = [+ "slug",+ "title",+ "date",+ "author",+ "excerpt",+ "readingTime",+] as const;+const OPTIONAL_METADATA_FIELDS = ["dateModified", "image"] as const;+const ALLOWED_IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".svg", ".webp"]);+const MAX_IMAGE_BYTES = 2 * 1024 * 1024;++export type BlogMetadata = Record<string, string>;++function extractMetadataObject(content: string): string | null {+ const declaration = /export\s+const\s+metadata\s*=\s*\{/.exec(content);+ if (!declaration) return null;++ const start = content.indexOf("{", declaration.index);+ let depth = 0;+ let quote = "";+ let escaped = false;++ for (let index = start; index < content.length; index += 1) {+ const char = content[index];+ if (quote) {+ if (escaped) {+ escaped = false;+ } else if (char === "\\") {+ escaped = true;+ } else if (char === quote) {+ quote = "";+ }+ continue;+ }+ if (char === '"' || char === "'" || char === "`") {+ quote = char;+ continue;+ }+ if (char === "{") depth += 1;+ if (char === "}") {+ depth -= 1;+ if (depth === 0) return content.slice(start + 1, index);+ }+ }+ return null;+}++function readStringProperty(object: string, property: string): string | null {+ const match = new RegExp(`(?:^|[,\\n])\\s*${property}\\s*:\\s*(["'])`).exec(object);+ if (!match) return null;++ const quote = match[1];+ let value = "";+ let escaped = false;+ for (let index = match.index + match[0].length; index < object.length; index += 1) {+ const char = object[index];+ if (escaped) {+ value += char;+ escaped = false;+ } else if (char === "\\") {+ escaped = true;+ } else if (char === quote) {+ return value;+ } else {+ value += char;+ }+ }+ return null;+}++function isIsoDate(value: string): boolean {+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;+ const date = new Date(`${value}T00:00:00.000Z`);+ return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value;+}++export function readBlogMetadata(+ content: string,+ fileSlug: string+): { metadata: BlogMetadata; errors: BlogAssetError[] } {+ const object = extractMetadataObject(content);+ if (!object) {+ return {+ metadata: {},+ errors: [`[post: ${fileSlug}] Missing or unterminated export const metadata object.`],+ };+ }++ const metadata: BlogMetadata = {};+ const errors: BlogAssetError[] = [];+ for (const field of [...REQUIRED_METADATA_FIELDS, ...OPTIONAL_METADATA_FIELDS]) {+ const value = readStringProperty(object, field);+ if (value !== null) metadata[field] = value;+ }++ for (const field of REQUIRED_METADATA_FIELDS) {+ if (!metadata[field]?.trim()) {+ errors.push(`[post: ${fileSlug}] Missing or empty metadata field "${field}".`);+ }+ }+ if (metadata.slug && metadata.slug !== fileSlug) {+ errors.push(+ `[post: ${fileSlug}] Metadata slug "${metadata.slug}" must match filename "${fileSlug}.mdx".`+ );+ }+ if (metadata.slug && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(metadata.slug)) {+ errors.push(`[post: ${fileSlug}] Metadata slug must use lowercase kebab-case.`);+ }+ for (const field of ["date", "dateModified"] as const) {+ if (metadata[field] && !isIsoDate(metadata[field])) {+ errors.push(`[post: ${fileSlug}] Metadata field "${field}" must be a valid YYYY-MM-DD date.`);+ }+ }+ if (+ metadata.date &&+ metadata.dateModified &&+ isIsoDate(metadata.date) &&+ isIsoDate(metadata.dateModified) &&+ metadata.dateModified < metadata.date+ ) {+ errors.push(`[post: ${fileSlug}] Metadata dateModified cannot be earlier than date.`);+ }+ if (metadata.readingTime && !/^[1-9]\d* min read$/.test(metadata.readingTime)) {+ errors.push(`[post: ${fileSlug}] Metadata readingTime must use "N min read".`);+ }++ return { metadata, errors };+}+export function findDuplicateMdxH1Errors(content: string,slug: string@@ -33,43 +164,68 @@ export function findDuplicateMdxH1Errors(return errors;}-export function findBlogImageErrors(- content: string,+function findImageSourceErrors(+ sources: string[],slug: string,publicDir: string,- fileExists: (path: string) => boolean = existsSync+ fileExists: (path: string) => boolean,+ fileSize?: (path: string) => number): BlogAssetError[] {const errors: BlogAssetError[] = [];- const imgRegex = /!\[[^\]]*\]\(([^)]*)\)|<img[^>]+src="([^"]*)"[^>]*>/g;- let match: RegExpExecArray | null;-- while ((match = imgRegex.exec(content)) !== null) {- const src = match[1] || match[2];-- if (!src.startsWith("/blog/")) {+ for (const src of new Set(sources)) {+ if (!src.startsWith(`/blog/${slug}/`)) {errors.push(- `[post: ${slug}] Image src "${src}" must start with /blog/ — move the file to public/blog/`+ `[post: ${slug}] Image src "${src}" must start with /blog/${slug}/ — move the file to the post's public/blog directory.`+ );+ continue;+ }+ const extension = extname(src).toLowerCase();+ if (!ALLOWED_IMAGE_EXTENSIONS.has(extension)) {+ errors.push(+ `[post: ${slug}] Image src "${src}" must use jpg, jpeg, png, svg, or webp.`);continue;}-const filePath = join(publicDir, src);if (!fileExists(filePath)) {errors.push(`[post: ${slug}] Image file not found: public${src}`);+ continue;+ }+ if (fileSize && fileSize(filePath) > MAX_IMAGE_BYTES) {+ errors.push(`[post: ${slug}] Image file exceeds 2 MiB: public${src}`);}}return errors;}+export function findBlogImageErrors(+ content: string,+ slug: string,+ publicDir: string,+ fileExists: (path: string) => boolean = existsSync,+ metadataImage?: string,+ fileSize?: (path: string) => number+): BlogAssetError[] {+ const sources = metadataImage ? [metadataImage] : [];+ const imgRegex = /!\[[^\]]*\]\(([^)\s]+)(?:\s+[^)]*)?\)|<img[^>]+src=["']([^"']*)["'][^>]*>/g;+ let match: RegExpExecArray | null;+ while ((match = imgRegex.exec(content)) !== null) {+ sources.push(match[1] || match[2]);+ }+ return findImageSourceErrors(sources, slug, publicDir, fileExists, fileSize);+}+export function collectBlogAssetErrors(content: string,slug: string,publicDir: string,- fileExists: (path: string) => boolean = existsSync+ fileExists: (path: string) => boolean = existsSync,+ metadataImage?: string,+ fileSize?: (path: string) => number): BlogAssetError[] {return [...findDuplicateMdxH1Errors(content, slug),- ...findBlogImageErrors(content, slug, publicDir, fileExists),+ ...findBlogImageErrors(content, slug, publicDir, fileExists, metadataImage, fileSize),];}@@ -78,7 +234,6 @@ export type ValidateBlogAssetsResult =| { status: "ok" }| { status: "failed"; errors: BlogAssetError[] };-/** Validate all MDX posts under contentDir against publicDir image files. */export function validateBlogAssets(contentDir: string,publicDir: string,@@ -89,13 +244,33 @@ export function validateBlogAssets(}const errors: BlogAssetError[] = [];- const mdxFiles = fs.readdirSync(contentDir).filter((f) => f.endsWith(".mdx"));+ const seenSlugs = new Map<string, string>();+ const mdxFiles = fs.readdirSync(contentDir).filter((file) => file.endsWith(".mdx"));for (const file of mdxFiles) {- const slug = file.replace(/\.mdx$/, "");+ const fileSlug = file.replace(/\.mdx$/, "");const content = fs.readFileSync(join(contentDir, file), "utf-8");+ const { metadata, errors: metadataErrors } = readBlogMetadata(content, fileSlug);+ errors.push(...metadataErrors);+ if (metadata.slug) {+ const previousFile = seenSlugs.get(metadata.slug);+ if (previousFile) {+ errors.push(+ `[post: ${fileSlug}] Duplicate metadata slug "${metadata.slug}" also used by ${previousFile}.`+ );+ } else {+ seenSlugs.set(metadata.slug, file);+ }+ }errors.push(- ...collectBlogAssetErrors(content, slug, publicDir, fs.existsSync)+ ...collectBlogAssetErrors(+ content,+ fileSlug,+ publicDir,+ fs.existsSync,+ metadata.image,+ fs.fileSize+ ));}@@ -111,7 +286,6 @@ export type ValidateBlogAssetsIo = {exit: (code: number) => void;};-/** CLI entry used by scripts/validate-blog-assets.ts */export function runValidateBlogAssetsCli(contentDir: string,publicDir: string,@@ -121,13 +295,13 @@ export function runValidateBlogAssetsCli(const result = validateBlogAssets(contentDir, publicDir, fs);if (result.status === "skipped") {- io.log("✓ Blog asset validation skipped (no content directory).");+ io.log("✓ Blog validation skipped (no content directory).");io.exit(0);return;}if (result.status === "failed") {- io.error("Blog asset validation failed:\n");+ io.error("Blog validation failed:\n");for (const err of result.errors) {io.error(` ✗ ${err}`);}@@ -136,6 +310,6 @@ export function runValidateBlogAssetsCli(return;}- io.log("✓ Blog asset validation passed.");+ io.log("✓ Blog validation passed.");io.exit(0);}diff --git a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.tsindex 3d146915c..174e9d524 100644--- a/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts+++ b/src/web/src/test/e2e-ui/03-realtime-multiuser.spec.ts@@ -1,6 +1,6 @@import { test, expect } from "./_fixtures/community-fixture"import { tid } from "./_fixtures/testids"-import { sendMessage, expectMessageVisible, composerEditable } from "./_fixtures/actions"+import { sendMessage, expectMessageVisible, composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"import { seedServer, seedChannel, seedJoinServer } from "./_fixtures/seed"// Journey 3 — multi-user realtime. Alice and Bob are both online in the same@@ -53,8 +53,8 @@ test.describe.serial("multi-user realtime", () => {test("Bob sees Alice's typing indicator, which clears after her message", async ({ asUser }) => {const alice = await asUser("alice")const bob = await asUser("bob")- await alice.page.goto(`/c/channels/${serverId}/${channelId}`)- await bob.page.goto(`/c/channels/${serverId}/${channelId}`)+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${channelId}`)await bob.page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })// Gate on Bob's WS subscription being LIVE before testing the typing@@ -84,7 +84,14 @@ test.describe.serial("multi-user realtime", () => {// Alice sends; her typing indicator clears on Bob's side (assert// presence→absence, not an exact duration).+ const finalMessagePromise = alice.page.waitForResponse((response) => {+ return response.request().method() === "POST"+ && new URL(response.url()).pathname === `/api/community/channels/${channelId}/messages`+ })await alice.page.keyboard.press("Enter")+ const finalMessage = await finalMessagePromise+ expect(finalMessage.status()).toBe(201)+ await expectMessageVisible(bob.page, "typing…")await expect(bob.page.getByTestId(tid.typingIndicator)).toBeHidden({ timeout: 15_000 })})})diff --git a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.tsindex 96969c7b1..2e7f722f6 100644--- a/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts+++ b/src/web/src/test/e2e-ui/14-forum-post-tags-presence.spec.ts@@ -1,5 +1,6 @@import { test, expect, userId } from "./_fixtures/community-fixture"import { tid } from "./_fixtures/testids"+import { gotoAfterUserWsAuth } from "./_fixtures/actions"import {seedServer,seedChannel,@@ -117,11 +118,18 @@ test.describe.serial("DM presence stability on refresh", () => {test("peer stays online after the viewer refreshes the DM view", async ({ asUser }) => {// Alice stays connected (her page holds a live WS connection → she's online).const alice = await asUser("alice")- await alice.page.goto("/c/me")+ await gotoAfterUserWsAuth(alice.page, "/c/me")await alice.page.waitForURL(/\/c\/me/, { timeout: 20_000, waitUntil: "commit" })const bob = await asUser("bob")- await bob.page.goto(`/c/me/${dmId}`)+ await expect.poll(async () => {+ const response = await bob.page.request.get(`/api/community/servers/${serverId}/presence`)+ if (!response.ok()) return false+ const body = await response.json() as { online?: string[] }+ return body.online?.includes(userId("alice")) ?? false+ }, { timeout: 20_000 }).toBe(true)++ await gotoAfterUserWsAuth(bob.page, `/c/me/${dmId}`)await bob.page.waitForURL(new RegExp(dmId), { timeout: 20_000, waitUntil: "commit" })const aliceDot = bob.page.getByTestId(tid.dmRow(dmId)).locator("[data-slot='avatar-badge']")diff --git a/src/web/src/test/e2e-ui/_fixtures/actions.ts b/src/web/src/test/e2e-ui/_fixtures/actions.tsindex ad7659ee7..8bca8c124 100644--- a/src/web/src/test/e2e-ui/_fixtures/actions.ts+++ b/src/web/src/test/e2e-ui/_fixtures/actions.ts@@ -1,6 +1,38 @@-import { type Page, expect } from "@playwright/test"+import { type Page, type WebSocket, expect } from "@playwright/test"import { tid } from "./testids"+export async function gotoAfterUserWsAuth(page: Page, url: string): Promise<void> {+ const frameHandlers = new Map<WebSocket, (event: { payload: string | Buffer }) => void>()+ let cleanup = () => {}+ const authenticated = new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("user WebSocket did not authenticate")), 20_000)+ const onWebSocket = (socket: WebSocket) => {+ const onFrame = (event: { payload: string | Buffer }) => {+ try {+ const message = JSON.parse(event.payload.toString()) as { type?: string }+ if (message.type !== "auth.ok") return+ cleanup()+ resolve()+ } catch {}+ }+ frameHandlers.set(socket, onFrame)+ socket.on("framereceived", onFrame)+ }+ cleanup = () => {+ clearTimeout(timer)+ page.off("websocket", onWebSocket)+ for (const [socket, handler] of frameHandlers) socket.off("framereceived", handler)+ }+ page.on("websocket", onWebSocket)+ })++ try {+ await Promise.all([page.goto(url, { waitUntil: "commit" }), authenticated])+ } finally {+ cleanup()+ }+}+// Reusable UI action helpers built on the canonical testids. Journeys compose// these so the real user path (click → type → assert) stays readable and the// selectors live in one place.diff --git a/src/web/src/test/e2e-ui/_fixtures/community-fixture.ts b/src/web/src/test/e2e-ui/_fixtures/community-fixture.tsindex 65719ef79..2da84d9a7 100644--- a/src/web/src/test/e2e-ui/_fixtures/community-fixture.ts+++ b/src/web/src/test/e2e-ui/_fixtures/community-fixture.ts@@ -21,7 +21,7 @@ export const test = base.extend<{ asUser: AsUser }>({return { context, page }}await provide(factory)- for (const c of opened) await c.close()+ await Promise.all(opened.map((context) => context.close()))},})diff --git a/src/web/src/test/e2e-ui/_setup/auth.ts b/src/web/src/test/e2e-ui/_setup/auth.tsindex 91262fcab..266dab88e 100644--- a/src/web/src/test/e2e-ui/_setup/auth.ts+++ b/src/web/src/test/e2e-ui/_setup/auth.ts@@ -1,13 +1,38 @@-import { chromium } from "@playwright/test"+import type { Browser, Page } from "@playwright/test"import { WEB_URL } from "./paths"import { emailFor, type SeededUser, type UserKey } from "./users"+async function signIn(page: Page, email: string): Promise<void> {+ const attempts = [`${WEB_URL}/c`, `${WEB_URL}/sign-in?redirect=/c`]+ let lastError: unknown++ for (const url of attempts) {+ await page.goto(url, { waitUntil: "load" })+ try {+ const emailInput = page.getByRole("textbox", { name: "Email" })+ await emailInput.waitFor({ state: "visible", timeout: 15_000 })+ await emailInput.fill(email)+ await page.getByRole("button", { name: "Sign in", exact: true }).click()+ await page.waitForURL((current) => !current.pathname.startsWith("/sign-in"), {+ timeout: 15_000,+ waitUntil: "commit",+ })+ return+ } catch (error) {+ lastError = error+ }+ }++ throw lastError+}+// Drives the real dev sign-in UI: navigating to /c first makes// middleware redirect to /sign-in?redirect=/c, so post-login lands// back in community (the default is /c/me otherwise). In dev the form// is email-only — `handleDevSignIn` signs in with DEV_PASSWORD and// auto-registers on first use. Captures storageState + the seeded userId.export async function loginAndSaveState(+ browser: Browser,key: UserKey,stamp: string,storageStatePath: string,@@ -16,21 +41,10 @@ export async function loginAndSaveState(// Dev sign-up derives the display name from the email local-part// (`handleDevSignIn`: `name: email.split("@")[0]`), so mirror that here.const name = email.split("@")[0]- const browser = await chromium.launch()const context = await browser.newContext()const page = await context.newPage()try {- await page.goto(`${WEB_URL}/c`)- await page.waitForURL(/\/sign-in/, { timeout: 30_000 , waitUntil: "commit" })-- await page.getByRole("textbox", { name: "Email" }).fill(email)- await page.getByRole("button", { name: "Sign in", exact: true }).click()-- // Land somewhere authenticated — community shell or the default workspace.- await page.waitForURL((url) => !url.pathname.startsWith("/sign-in"), {- timeout: 30_000,- waitUntil: "commit",- })+ await signIn(page, email)// Resolve the seeded userId via the authenticated community profile API,// reusing the session cookie the login just established.@@ -44,6 +58,6 @@ export async function loginAndSaveState(await context.storageState({ path: storageStatePath })return { key, email, name, userId: me.userId, storageState: storageStatePath }} finally {- await browser.close()+ await context.close()}}diff --git a/src/web/src/test/e2e-ui/_setup/global-setup.ts b/src/web/src/test/e2e-ui/_setup/global-setup.tsindex 010915f0b..58afb9201 100644--- a/src/web/src/test/e2e-ui/_setup/global-setup.ts+++ b/src/web/src/test/e2e-ui/_setup/global-setup.ts@@ -1,5 +1,6 @@import { mkdirSync, writeFileSync, rmSync } from "fs"import { resolve } from "path"+import { chromium } from "@playwright/test"import { AUTH_DIR, MANIFEST_PATH } from "./paths"import { loginAndSaveState } from "./auth"import { resetDb, startServices, backupState, REUSE_EXISTING } from "./services"@@ -22,9 +23,14 @@ export default async function globalSetup(): Promise<void> {const stamp = `${process.pid.toString(36)}${Math.floor(process.hrtime()[1] / 1e3).toString(36)}`const users = {} as Record<UserKey, SeededUser>- for (const key of USER_KEYS) {- const statePath = resolve(AUTH_DIR, `${key}.json`)- users[key] = await loginAndSaveState(key, stamp, statePath)+ const browser = await chromium.launch()+ try {+ for (const key of USER_KEYS) {+ const statePath = resolve(AUTH_DIR, `${key}.json`)+ users[key] = await loginAndSaveState(browser, key, stamp, statePath)+ }+ } finally {+ await browser.close()}const manifest: RunManifest & { servicePids: number[]; restoreState: boolean } = {diff --git a/vitest.config.ts b/vitest.config.tsindex 296bb9bd8..4dd33673c 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -2,7 +2,7 @@ import { defineConfig } from "vitest/config"export default defineConfig({test: {- projects: ["src/shared", "src/web", "src/cli", "src/daemon", "src/email-worker", "src/ws-do", "src/app", "tests/utils"],+ projects: ["src/shared", "src/web", "src/cli", "src/daemon", "src/email-worker", "src/ws-do", "src/app", "tests/utils", "scripts/ci"],coverage: {provider: "v8",include: ["src/**/*.{ts,tsx,js,jsx}"],