diff --git a/.github/actions/setup-linux-sandbox/action.yml b/.github/actions/setup-linux-sandbox/action.yml new file mode 100644 index 000000000000..6e3a78042045 --- /dev/null +++ b/.github/actions/setup-linux-sandbox/action.yml @@ -0,0 +1,21 @@ +# kilocode_change - new file +name: "Setup Linux Sandbox" +description: "Build the Linux bubblewrap helper" +runs: + using: "composite" + steps: + - name: Setup Zig + run: | + curl --fail --location --retry 3 \ + https://ziglang.org/download/0.14.0/zig-linux-x86_64-0.14.0.tar.xz \ + --output "$RUNNER_TEMP/zig.tar.xz" + echo "473ec26806133cf4d1918caf1a410f8403a13d979726a9045b421b685031a982 $RUNNER_TEMP/zig.tar.xz" | sha256sum --check --status + tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP" + echo "$RUNNER_TEMP/zig-linux-x86_64-0.14.0" >> "$GITHUB_PATH" + shell: bash + + - name: Build bubblewrap helper + run: | + bun packages/opencode/script/kilocode/bubblewrap.ts --arch x64 --output "$RUNNER_TEMP/bwrap" + echo "KILO_BWRAP_PATH=$RUNNER_TEMP/bwrap" >> "$GITHUB_ENV" + shell: bash diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2fa277d09019..7684462d27f5 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,6 +30,7 @@ jobs: pull-requests: read outputs: settings: ${{ steps.matrix.outputs.settings }} + general: ${{ steps.matrix.outputs.general }} steps: - name: Checkout repository if: github.event_name != 'workflow_dispatch' @@ -57,14 +58,16 @@ jobs: env: GENERAL: ${{ github.event_name != 'pull_request' || steps.filter.outputs.general == 'true' }} run: | - if [ "$GENERAL" = "true" ]; then - echo 'settings=[{"name":"linux","host":"blacksmith-4vcpu-ubuntu-2404","run":true},{"name":"macos","host":"macos-15","run":true},{"name":"windows","host":"blacksmith-4vcpu-windows-2025","run":true}]' >> "$GITHUB_OUTPUT" + if [ "$GENERAL" != "true" ]; then + echo 'general=false' >> "$GITHUB_OUTPUT" + echo 'settings=[{"os":"linux","index":1,"total":1,"host":"blacksmith-4vcpu-ubuntu-2404","run":false,"packages":false}]' >> "$GITHUB_OUTPUT" exit 0 fi - echo 'settings=[{"name":"linux","host":"blacksmith-4vcpu-ubuntu-2404","run":false}]' >> "$GITHUB_OUTPUT" + echo 'general=true' >> "$GITHUB_OUTPUT" + echo 'settings=[{"os":"linux","index":1,"total":2,"host":"blacksmith-4vcpu-ubuntu-2404","run":true,"packages":true},{"os":"linux","index":2,"total":2,"host":"blacksmith-4vcpu-ubuntu-2404","run":true,"packages":false},{"os":"macos","index":1,"total":1,"host":"macos-15","run":true,"packages":true},{"os":"windows","index":1,"total":4,"host":"blacksmith-4vcpu-windows-2025","run":true,"packages":true},{"os":"windows","index":2,"total":4,"host":"blacksmith-4vcpu-windows-2025","run":true,"packages":false},{"os":"windows","index":3,"total":4,"host":"blacksmith-4vcpu-windows-2025","run":true,"packages":false},{"os":"windows","index":4,"total":4,"host":"blacksmith-4vcpu-windows-2025","run":true,"packages":false}]' >> "$GITHUB_OUTPUT" unit: - name: unit (${{ matrix.settings.name }}) + name: ${{ !matrix.settings.run && 'unit (unchanged)' || matrix.settings.total > 1 && format('unit ({0}, {1}/{2})', matrix.settings.os, matrix.settings.index, matrix.settings.total) || format('unit ({0})', matrix.settings.os) }} needs: changes strategy: fail-fast: false @@ -107,21 +110,9 @@ jobs: uses: ./.github/actions/setup-bun # kilocode_change start - - name: Setup Zig for Linux sandbox helper + - name: Setup Linux sandbox helper if: matrix.settings.run && runner.os == 'Linux' - run: | - curl --fail --location --retry 3 \ - https://ziglang.org/download/0.14.0/zig-linux-x86_64-0.14.0.tar.xz \ - --output "$RUNNER_TEMP/zig.tar.xz" - echo "473ec26806133cf4d1918caf1a410f8403a13d979726a9045b421b685031a982 $RUNNER_TEMP/zig.tar.xz" | sha256sum --check --status - tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP" - echo "$RUNNER_TEMP/zig-linux-x86_64-0.14.0" >> "$GITHUB_PATH" - - - name: Build Linux sandbox helper - if: matrix.settings.run && runner.os == 'Linux' - run: | - bun packages/opencode/script/kilocode/bubblewrap.ts --arch x64 --output "$RUNNER_TEMP/bwrap" - echo "KILO_BWRAP_PATH=$RUNNER_TEMP/bwrap" >> "$GITHUB_ENV" + uses: ./.github/actions/setup-linux-sandbox # kilocode_change end - name: Configure git identity if: matrix.settings.run @@ -134,31 +125,30 @@ jobs: uses: actions/cache@v5 # kilocode_change with: path: .turbo/cache # kilocode_change - key: turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}-${{ github.sha }} + key: turbo-${{ runner.os }}-${{ hashFiles('turbo.json', 'bun.lock') }}-${{ matrix.settings.os }}-${{ matrix.settings.index }}-${{ github.sha }} restore-keys: | - turbo-${{ runner.os }}-${{ hashFiles('turbo.json', '**/package.json') }}- + turbo-${{ runner.os }}-${{ hashFiles('turbo.json', 'bun.lock') }}-${{ matrix.settings.os }}-${{ matrix.settings.index }}- + turbo-${{ runner.os }}-${{ hashFiles('turbo.json', 'bun.lock') }}- turbo-${{ runner.os }}- - - name: Run unit tests + - name: Run non-CLI unit tests + if: matrix.settings.run && matrix.settings.packages + run: bun turbo test:ci --filter='!@kilocode/cli' --filter='!@kilocode/kilo-jetbrains' + + - name: Run CLI unit tests if: matrix.settings.run - run: bun turbo test:ci --filter='!@kilocode/kilo-jetbrains' + run: bun turbo test:ci --filter='@kilocode/cli' env: KILO_EXPERIMENTAL_DISABLE_FILEWATCHER: ${{ runner.os == 'Windows' && 'true' || 'false' }} - KILO_TEST_PROFILE: ${{ runner.os == 'macOS' && github.event_name == 'pull_request' && 'darwin' || '' }} # kilocode_change - - # kilocode_change start - - name: Run HttpApi exerciser gates - if: matrix.settings.run && runner.os == 'Linux' - working-directory: packages/opencode - run: bun run test:httpapi - # kilocode_change end + KILO_TEST_PROFILE: ${{ matrix.settings.os == 'macos' && 'darwin' || '' }} + KILO_TEST_SHARD: ${{ format('{0}/{1}', matrix.settings.index, matrix.settings.total) }} - name: Publish unit reports # kilocode_change if: always() && matrix.settings.run uses: mikepenz/action-junit-report@bccf2e31636835cf0874589931c4116687171386 # v6.4.0 with: report_paths: packages/*/.artifacts/unit/junit.xml - check_name: "unit results (${{ matrix.settings.name }})" + annotate_only: true detailed_summary: true include_time_in_summary: true fail_on_failure: false @@ -167,13 +157,52 @@ jobs: if: always() && matrix.settings.run uses: actions/upload-artifact@v7 # kilocode_change with: - name: unit-${{ matrix.settings.name }}-${{ github.run_attempt }} + name: unit-${{ matrix.settings.os }}-${{ matrix.settings.index }}-${{ github.run_attempt }} include-hidden-files: true if-no-files-found: ignore retention-days: 7 path: packages/*/.artifacts/unit/junit.xml # kilocode_change end + # kilocode_change start + httpapi: + name: HttpApi exerciser + needs: changes + if: needs.changes.outputs.general == 'true' + runs-on: blacksmith-4vcpu-ubuntu-2404 + timeout-minutes: 15 + defaults: + run: + shell: bash + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Setup Bun + uses: ./.github/actions/setup-bun + + - name: Setup Linux sandbox helper + uses: ./.github/actions/setup-linux-sandbox + + - name: Configure git identity + run: | + git config --global user.email "kilo-maintainer[bot]@users.noreply.github.com" + git config --global user.name "kilo-maintainer[bot]" + + - name: Cache Turbo + uses: actions/cache@v5 + with: + path: .turbo/cache + key: turbo-${{ runner.os }}-${{ hashFiles('turbo.json', 'bun.lock') }}-httpapi-${{ github.sha }} + restore-keys: | + turbo-${{ runner.os }}-${{ hashFiles('turbo.json', 'bun.lock') }}-httpapi- + turbo-${{ runner.os }}-${{ hashFiles('turbo.json', 'bun.lock') }}- + turbo-${{ runner.os }}- + + - name: Run HttpApi exerciser gates + run: bun turbo test:httpapi --filter='@kilocode/cli' + # kilocode_change end + # kilocode_change start jetbrains: name: jetbrains @@ -185,18 +214,38 @@ jobs: # kilocode_change end # kilocode_change start + unit-required: + name: unit (linux) + runs-on: blacksmith-4vcpu-ubuntu-2404 + needs: + - unit + if: always() + steps: + - name: Verify unit matrix passed + run: | + echo "unit=${{ needs.unit.result }}" + test "${{ needs.unit.result }}" = "success" + required: name: test (linux) runs-on: blacksmith-4vcpu-ubuntu-2404 needs: + - changes - unit + - httpapi - jetbrains if: always() steps: - name: Verify upstream test jobs passed run: | echo "unit=${{ needs.unit.result }}" + echo "httpapi=${{ needs.httpapi.result }}" echo "jetbrains=${{ needs.jetbrains.result }}" test "${{ needs.unit.result }}" = "success" + if [ "${{ needs.changes.outputs.general }}" = "true" ]; then + test "${{ needs.httpapi.result }}" = "success" + else + test "${{ needs.httpapi.result }}" = "skipped" + fi test "${{ needs.jetbrains.result }}" = "success" # kilocode_change end diff --git a/packages/opencode/script/kilocode/test-profile.ts b/packages/opencode/script/kilocode/test-profile.ts index 9851b2f4a0b9..cada4f1fbdfb 100644 --- a/packages/opencode/script/kilocode/test-profile.ts +++ b/packages/opencode/script/kilocode/test-profile.ts @@ -1,42 +1,49 @@ export namespace TestProfile { // Broad globs keep platform coverage maintainable as tests are added or renamed. - // Full macOS runs on main remain the backstop for tests outside these areas. + // Full Linux and Windows runs remain the backstop for platform-neutral behavior. const profiles = { darwin: { description: "Darwin-native process, terminal, filesystem, worktree, and runtime coverage", groups: { cli: [ - "cli/acp/*.test.ts", - "cli/run/{footer.view,run-process,scrollback.surface}.test.{ts,tsx}", + "cli/acp/lifecycle.test.ts", + "cli/run/run-process.test.ts", "cli/serve/*.test.ts", "cli/smokes/*.test.ts", - "cli/tui/{app-lifecycle,dialog-prompt,diff-viewer-file-tree,diff-viewer,inline-tool-wrap-snapshot,keymap,plugin-loader-entrypoint,slot-replace,thread,use-event}.test.{ts,tsx}", + "cli/tui/{plugin-lifecycle,plugin-loader-entrypoint,thread}.test.ts", + ], + config: [ + "config/{config,tui}.test.ts", + "control-plane/workspace.test.ts", ], filesystem: [ - "file/{index,path-traversal,ripgrep}.test.ts", + "file/{index,path-traversal,ripgrep,watcher}.test.ts", + "filesystem/filesystem.test.ts", + "fixture/fixture.test.ts", "git/*.test.ts", "image/*.test.ts", "plugin/{install-concurrency,loader-shared}.test.ts", "reference/*.test.ts", "snapshot/*.test.ts", - "tool/{external-directory,glob,grep,read,repo_clone,repo_overview,shell}.test.ts", - "util/{filesystem,module,process,which}.test.ts", + "tool/{apply_patch,edit,glob,grep,read,recall,registry,repo_clone,repo_overview,shell,skill,truncation,write}.test.ts", + "util/{filesystem,glob,module,process,which}.test.ts", ], kilo: [ - "kilocode/{background-process,bin-tree-sitter-env,daemon,external-directory-boundary,indexing-worker,indexing-worktree,mcp-oauth-callback,primary-worktree,snapshot-freeze-repro,snapshot-revert-move,snapshot-seed}.test.ts", + "kilocode/{background-process,daemon,diff-full,external-directory-boundary,indexing-worker,indexing-worktree,interactive-terminal,mcp-oauth-callback,primary-worktree,project-id,read-directory,session-diff-restore,snapshot-cache,snapshot-freeze-repro,snapshot-revert-move,snapshot-seed,task-nesting}.test.ts", + "kilocode/cli/cmd/serve.test.ts", "kilocode/cli/install-artifact.test.ts", + "kilocode/config/config.test.ts", "kilocode/sandbox/*.test.ts", - "kilocode/server/{listener-runtime,worktree-list}.test.ts", + "kilocode/server/{config-overlay,listener-runtime,tui-config,worktree-list}.test.ts", "kilocode/session-export/{e2e,sequence,worker,workspace-provider}.test.ts", "kilocode/session-export/worker/{storage,zstd}.test.ts", - "kilocode/sessions/*.test.ts", "kilocode/worktree*.test.ts", ], - process: ["provider/header-timeout.test.ts", "session/{prompt,retry}.test.ts", "shell/*.test.ts"], + process: ["session/prompt.test.ts"], project: ["project/*.test.ts"], - pty: ["pty/pty-*.test.ts", "server/httpapi-pty*.test.ts"], + pty: ["pty/pty-*.test.ts", "server/httpapi-pty.test.ts"], server: [ - "server/{httpapi-compression,httpapi-experimental,httpapi-file,httpapi-listen,httpapi-workspace-routing,project-init-git,workspace-proxy,worktree-endpoint-repro}.test.ts", + "server/{experimental-session-list,httpapi-experimental,httpapi-file,httpapi-listen,httpapi-workspace-routing,project-init-git,worktree-endpoint-repro}.test.ts", ], }, }, diff --git a/packages/opencode/script/kilocode/test-shard.ts b/packages/opencode/script/kilocode/test-shard.ts new file mode 100644 index 000000000000..5cc9efd809b4 --- /dev/null +++ b/packages/opencode/script/kilocode/test-shard.ts @@ -0,0 +1,43 @@ +export namespace TestShard { + export type Info = { + index: number + total: number + } + + export function parse(input?: string) { + if (!input) return { ok: true as const, value: undefined } + const match = input.match(/^(\d+)\/(\d+)$/) + if (!match) return { ok: false as const, error: `Invalid test shard "${input}"; expected N/M` } + + const value = { index: Number(match[1]), total: Number(match[2]) } + if ( + !Number.isSafeInteger(value.index) || + !Number.isSafeInteger(value.total) || + value.total < 1 || + value.total > 1_000 || + value.index < 1 || + value.index > value.total + ) { + return { ok: false as const, error: `Invalid test shard "${input}"; expected 1 <= N <= M <= 1000` } + } + return { ok: true as const, value } + } + + export function order(files: readonly string[], weight: (file: string) => number) { + return files.slice().sort((a, b) => weight(b) - weight(a) || a.localeCompare(b)) + } + + export function split(files: readonly string[], weight: (file: string) => number, total: number) { + const groups = Array.from({ length: total }, () => ({ files: [] as string[], weight: 0 })) + for (const file of order(files, weight)) { + const group = groups.reduce((best, item) => { + if (item.weight < best.weight) return item + if (item.weight === best.weight && item.files.length < best.files.length) return item + return best + }) + group.files.push(file) + group.weight += weight(file) + } + return groups.map((group) => group.files) + } +} diff --git a/packages/opencode/script/test-runner.ts b/packages/opencode/script/test-runner.ts index 4b43a0e6f206..795bf0566045 100644 --- a/packages/opencode/script/test-runner.ts +++ b/packages/opencode/script/test-runner.ts @@ -8,6 +8,7 @@ import os from "os" import path from "path" import fs from "fs/promises" import { TestProfile } from "./kilocode/test-profile" +import { TestShard } from "./kilocode/test-shard" const root = path.resolve(import.meta.dir, "..") const argv = process.argv.slice(2) @@ -31,6 +32,7 @@ if (argv.includes("--help") || argv.includes("-h")) { " --file-timeout Per-file process timeout (default: 300000)", " --retries Extra attempts for failing files (default: 1)", " --profile Run a curated test profile (env: KILO_TEST_PROFILE)", + " --shard Run one balanced file shard (env: KILO_TEST_SHARD)", " --bail Stop on first failure", " --dots Show compact dot progress", " --verbose Show full output for every file", @@ -80,8 +82,20 @@ if (flag && env && flag !== env) { process.exit(2) } const profile = flag ?? env +const shardFlag = text("shard") +const shardEnv = process.env.KILO_TEST_SHARD?.trim() || undefined +if (shardFlag && shardEnv && shardFlag !== shardEnv) { + console.error(`Conflicting test shards: --shard=${shardFlag}, KILO_TEST_SHARD=${shardEnv}`) + process.exit(2) +} +const parsed = TestShard.parse(shardFlag ?? shardEnv) +if (!parsed.ok) { + console.error(parsed.error) + process.exit(2) +} +const shard = parsed.value -const valued = new Set(["--concurrency", "--timeout", "--file-timeout", "--retries", "--profile"]) +const valued = new Set(["--concurrency", "--timeout", "--file-timeout", "--retries", "--profile", "--shard"]) const patterns = argv.filter((arg, i) => { if (arg.startsWith("-")) return false if (i > 0 && valued.has(argv[i - 1])) return false @@ -135,7 +149,13 @@ const matched = patterns.some((pattern) => file.includes(pattern) || path.join("test", file).includes(pattern)), ) : selected -const files = patterns.length > 0 && !profile ? matched : matched.filter((file) => !skipped.has(file)) // kilocode_change +const candidates = patterns.length > 0 && !profile ? matched : matched.filter((file) => !skipped.has(file)) // kilocode_change +if (shard && shard.total > candidates.length) { + console.error(`Test shard count ${shard.total} exceeds selected file count ${candidates.length}`) + process.exit(2) +} +const weight = (file: string) => Bun.file(path.join(root, "test", file)).size +const files = shard ? TestShard.split(candidates, weight, shard.total)[shard.index - 1] : candidates if (files.length === 0) { console.log("No test files found") @@ -195,6 +215,7 @@ async function run(file: string): Promise { cwd: root, stdout: "pipe", stderr: "pipe", + windowsHide: true, }) const timer = setTimeout(() => { @@ -274,12 +295,13 @@ function report(result: Result) { // --------------------------------------------------------------------------- console.log(`\nRunning ${bold(String(files.length))} test files with concurrency ${bold(String(concurrency))}`) +if (shard) console.log(`Using balanced test shard ${shard.index}/${shard.total}`) if (dots) console.log(dim(legend)) console.log() const start = performance.now() const results: Result[] = [] -const queue = [...files] +const queue = TestShard.order(files, weight) const stopped = { value: false } const workers = Array.from({ length: Math.min(concurrency, files.length) }, async () => { diff --git a/packages/opencode/test/file/watcher.test.ts b/packages/opencode/test/file/watcher.test.ts index 98f27318eadf..50ddb39bc06b 100644 --- a/packages/opencode/test/file/watcher.test.ts +++ b/packages/opencode/test/file/watcher.test.ts @@ -10,8 +10,13 @@ import { Config } from "@/config/config" import { FileWatcher } from "../../src/file/watcher" import { Git } from "../../src/git" -// Native @parcel/watcher bindings aren't reliably available in CI (missing on Linux, flaky on Windows) -const describeWatcher = FileWatcher.hasNativeBinding() && !process.env.CI ? describe : describe.skip +// kilocode_change start +// Native @parcel/watcher bindings aren't reliably available in CI (missing on Linux, flaky on Windows). +const describeWatcher = + FileWatcher.hasNativeBinding() && (!process.env.CI || process.env.KILO_TEST_PROFILE === "darwin") + ? describe + : describe.skip +// kilocode_change end // --------------------------------------------------------------------------- // Helpers diff --git a/packages/opencode/test/kilocode/background-process.test.ts b/packages/opencode/test/kilocode/background-process.test.ts index 794d6456b475..7b53c48fe23c 100644 --- a/packages/opencode/test/kilocode/background-process.test.ts +++ b/packages/opencode/test/kilocode/background-process.test.ts @@ -8,6 +8,7 @@ import { Global } from "@opencode-ai/core/global" import { Hash } from "@opencode-ai/core/util/hash" import { Effect } from "effect" import { spawn } from "child_process" +import { once } from "node:events" import fs from "fs/promises" import path from "path" import { provideTestInstance, TestInstance, tmpdir } from "../fixture/fixture" @@ -392,6 +393,13 @@ setInterval(() => console.log("tick"), 100) const otherID = SessionID.descending() const visible = yield* Effect.promise(() => BackgroundProcess.list({ sessionID: otherID })) expect(visible.map((item) => item.id)).toContain(info.id) + const files = artifacts(test.directory, info.id) + yield* Effect.promise(() => + until(async () => { + const log = Bun.file(files.log) + return (await log.exists()) && (await log.text()).includes("ready") + }, "persistent process output was not flushed before reload"), + ) yield* Effect.promise(() => BackgroundProcess.shutdown()) const adopted = yield* Effect.promise(() => BackgroundProcess.get(info.id)) expect(adopted?.pid).toBe(info.pid) @@ -597,10 +605,14 @@ setInterval(() => {}, 1_000) expect(alive(unrelated.pid)).toBe(true) expect(yield* Effect.promise(() => Bun.file(target.manifest).exists())).toBe(false) } finally { - if (unrelated.pid && alive(unrelated.pid)) { - if (process.platform === "win32") unrelated.kill("SIGKILL") - else process.kill(-unrelated.pid, "SIGKILL") - } + yield* Effect.promise(async () => { + const exited = unrelated.exitCode !== null || unrelated.signalCode !== null ? undefined : once(unrelated, "exit") + if (unrelated.pid && alive(unrelated.pid)) { + if (process.platform === "win32") unrelated.kill("SIGKILL") + else process.kill(-unrelated.pid, "SIGKILL") + } + await exited + }) yield* Effect.promise(() => BackgroundProcess.stop(info.id)) } }), diff --git a/packages/opencode/test/kilocode/cleanup.ts b/packages/opencode/test/kilocode/cleanup.ts index a687012598c0..5d7e03db5a76 100644 --- a/packages/opencode/test/kilocode/cleanup.ts +++ b/packages/opencode/test/kilocode/cleanup.ts @@ -15,11 +15,15 @@ function locked(error: unknown) { export async function remove(dir: string) { const cfg = opts() + const state = { gc: false } const rm = async (left: number): Promise => { - if (process.platform === "win32") Bun.gc(true) return fs.rm(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }).catch(async (error) => { if (!locked(error)) throw error if (left <= 1) throw error + if (process.platform === "win32" && !state.gc) { + Bun.gc(true) + state.gc = true + } await Bun.sleep(cfg.delay) return rm(left - 1) }) diff --git a/packages/opencode/test/kilocode/test-profile.test.ts b/packages/opencode/test/kilocode/test-profile.test.ts index 656657931689..2ad63622ee42 100644 --- a/packages/opencode/test/kilocode/test-profile.test.ts +++ b/packages/opencode/test/kilocode/test-profile.test.ts @@ -4,7 +4,7 @@ import { TestProfile } from "../../script/kilocode/test-profile" const root = path.resolve(import.meta.dir, "..") const glob = new Bun.Glob("**/*.test.{ts,tsx}") -const all = (await Array.fromAsync(glob.scan({ cwd: root }))).sort() +const all = (await Array.fromAsync(glob.scan({ cwd: root }))).map((file) => file.replaceAll("\\", "/")).sort() describe("test profiles", () => { test("darwin profile contains valid test files", () => { @@ -15,8 +15,16 @@ describe("test profiles", () => { expect(result.files).toContain("pty/pty-session.test.ts") expect(result.files).toContain("kilocode/cli/install-artifact.test.ts") expect(result.files).toContain("kilocode/sandbox/macos-confinement.test.ts") - expect(result.files).toContain("kilocode/sessions/remote-ws.test.ts") - expect(result.files).toContain("kilocode/sessions/remote-sender.test.ts") + expect(result.files).toContain("file/watcher.test.ts") + expect(result.files).toContain("kilocode/interactive-terminal.test.ts") + const sandbox = all.filter((file) => file.startsWith("kilocode/sandbox/")) + expect(result.files.filter((file) => file.startsWith("kilocode/sandbox/"))).toEqual(sandbox) + expect(result.files).not.toContain("cli/run/footer.view.test.tsx") + expect(result.files).not.toContain("mcp/lifecycle.test.ts") + expect(result.files).not.toContain("server/httpapi-pty-websocket.test.ts") + expect(result.files).not.toContain("shell/shell.test.ts") + expect(result.files).not.toContain("kilocode/sessions/remote-ws.test.ts") + expect(result.files).not.toContain("provider/header-timeout.test.ts") }) test("normalizes Windows test paths", () => { diff --git a/packages/opencode/test/kilocode/test-shard.test.ts b/packages/opencode/test/kilocode/test-shard.test.ts new file mode 100644 index 000000000000..49dd10d62f33 --- /dev/null +++ b/packages/opencode/test/kilocode/test-shard.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, test } from "bun:test" +import { TestShard } from "../../script/kilocode/test-shard" + +describe("test shard", () => { + test("parses valid shard specifications", () => { + expect(TestShard.parse()).toEqual({ ok: true, value: undefined }) + expect(TestShard.parse("2/3")).toEqual({ ok: true, value: { index: 2, total: 3 } }) + }) + + test("rejects invalid shard specifications", () => { + expect(TestShard.parse("0/2").ok).toBe(false) + expect(TestShard.parse("3/2").ok).toBe(false) + expect(TestShard.parse("1/0").ok).toBe(false) + expect(TestShard.parse("one/two").ok).toBe(false) + expect(TestShard.parse("1/999999999999999999999").ok).toBe(false) + }) + + test("orders the heaviest files first with stable ties", () => { + const weights = new Map([ + ["small.test.ts", 1], + ["b.test.ts", 5], + ["a.test.ts", 5], + ]) + expect(TestShard.order([...weights.keys()], (file) => weights.get(file)!)).toEqual([ + "a.test.ts", + "b.test.ts", + "small.test.ts", + ]) + }) + + test("partitions every file once while balancing weights", () => { + const weights = new Map([ + ["largest.test.ts", 8], + ["large.test.ts", 7], + ["medium.test.ts", 6], + ["small.test.ts", 3], + ]) + const groups = TestShard.split([...weights.keys()], (file) => weights.get(file)!, 2) + expect(groups.flat().sort()).toEqual([...weights.keys()].sort()) + expect(groups.map((group) => group.reduce((sum, file) => sum + weights.get(file)!, 0))).toEqual([11, 13]) + }) + + test("distributes zero-weight files across shards", () => { + expect(TestShard.split(["a.test.ts", "b.test.ts"], () => 0, 2)).toEqual([["a.test.ts"], ["b.test.ts"]]) + }) +}) diff --git a/turbo.json b/turbo.json index c0f379a64d39..fbf4207c9f41 100644 --- a/turbo.json +++ b/turbo.json @@ -25,10 +25,17 @@ }, "@kilocode/cli#test:ci": { "dependsOn": ["^build"], - "env": ["KILO_TEST_PROFILE"], + "env": ["KILO_TEST_PROFILE", "KILO_TEST_SHARD"], + "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/.github/workflows/test.yml"], "outputs": [".artifacts/unit/junit.xml"], "passThroughEnv": ["*"] }, + "@kilocode/cli#test:httpapi": { + "dependsOn": ["^build"], + "cache": false, + "outputs": [], + "passThroughEnv": ["*"] + }, "@kilocode/kilo-gateway#test:ci": { "outputs": [".artifacts/unit/junit.xml"] },