Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

73.8 KB
Raw Blame
import { existsSync, readFileSync, readdirSync } from "node:fs"
import { resolve } from "node:path"
import { describe, expect, it } from "vitest"

const workflowRoot = resolve(import.meta.dirname, "../../.github/workflows")
const repositoryRoot = resolve(import.meta.dirname, "../..")
function normalizeWorkflow(text: string): string {
  return text.replace(/\r\n/g, "\n")
}

const ciWorkflow = normalizeWorkflow(readFileSync(resolve(workflowRoot, "ci.yml"), "utf8"))

it("pins every external workflow action to a full commit SHA", () => {
  for (const filename of readdirSync(workflowRoot).filter(name => /\.ya?ml$/.test(name))) {
    const text = readFileSync(resolve(workflowRoot, filename), "utf8")
    const actions = [...text.matchAll(/^\s*(?:-\s*)?uses:\s*(\S+)/gm)].map(match => match[1])
    for (const action of actions.filter(action => !action.startsWith("./"))) {
      expect(action, `${filename}:${action}`).toMatch(/^[A-Za-z0-9_./-]+@[a-f0-9]{40}$/)
    }
  }
})
const workflow = ciWorkflow
const dependabotConfig = normalizeWorkflow(
  readFileSync(resolve(repositoryRoot, ".github/dependabot.yml"), "utf8"),
)
const changeScopeManifest = JSON.parse(
  readFileSync(resolve(repositoryRoot, "scripts/ci/change-scope-manifest.json"), "utf8"),
) as { ui: { contracts: { resizable_panels: string[] } } }
const legacyUiWorkflowPath = resolve(workflowRoot, "e2e-ui.yml")
const playwrightConfig = readFileSync(
  resolve(import.meta.dirname, "../../src/web/playwright.config.ts"),
  "utf8",
)
type WorkerModuleContract = {
  name: string
  packageJson: {
    scripts: Record<string, string>
    devDependencies: Record<string, string>
  }
  nodeConfig: string
  runtimeConfig: string
  workspaceConfig: string
  wranglerConfig: string
}

const directWorkerModules = ["ws-do", "email-worker", "queue-worker", "web"].map((name): WorkerModuleContract => {
  const moduleRoot = resolve(import.meta.dirname, `../../src/${name}`)
  return {
    name,
    packageJson: JSON.parse(readFileSync(resolve(moduleRoot, "package.json"), "utf8")),
    nodeConfig: readFileSync(resolve(moduleRoot, "vitest.config.ts"), "utf8"),
    runtimeConfig: readFileSync(resolve(moduleRoot, "vitest.runtime.config.mts"), "utf8"),
    workspaceConfig: readFileSync(resolve(moduleRoot, "vitest.workspace.config.ts"), "utf8"),
    wranglerConfig: readFileSync(resolve(moduleRoot, "wrangler.toml"), "utf8"),
  }
})
const rootVitestConfig = readFileSync(
  resolve(import.meta.dirname, "../../vitest.config.ts"),
  "utf8",
)
const daemonVitestConfig = readFileSync(
  resolve(import.meta.dirname, "../../src/daemon/vitest.config.ts"),
  "utf8",
)
const rootPackageJson = JSON.parse(
  readFileSync(resolve(import.meta.dirname, "../../package.json"), "utf8"),
) as {
  scripts: Record<string, string>
  devDependencies: Record<string, string>
}
const autoTagReleaseWorkflow = normalizeWorkflow(
  readFileSync(resolve(workflowRoot, "auto-tag-release.yml"), "utf8"),
)
const desktopReleaseWorkflow = normalizeWorkflow(readFileSync(resolve(workflowRoot, "desktop-release.yml"), "utf8"))
const desktopReleaseArtifacts = readFileSync(
  resolve(repositoryRoot, "scripts/ci/desktop-release-artifacts.mjs"),
  "utf8",
)
const desktopMacVerifier = readFileSync(
  resolve(repositoryRoot, "scripts/ci/verify-desktop-macos.sh"),
  "utf8",
)
const desktopWindowsVerifier = readFileSync(
  resolve(repositoryRoot, "scripts/ci/verify-desktop-windows.ps1"),
  "utf8",
)
const mobileReleaseWorkflowPath = resolve(workflowRoot, "mobile-release.yml")
const mobileReleaseWorkflow = normalizeWorkflow(readFileSync(mobileReleaseWorkflowPath, "utf8"))
const desktopConfig = JSON.parse(
  readFileSync(resolve(import.meta.dirname, "../../src/desktop/src-tauri/tauri.conf.json"), "utf8"),
) as {
  build?: { devUrl?: string; frontendDist?: string }
  app?: {
    windows?: Array<{ label?: string; dragDropEnabled?: boolean }>
    security?: { capabilities?: Array<string | Record<string, unknown>> }
  }
  bundle?: { createUpdaterArtifacts?: boolean | string }
  plugins?: { updater?: { endpoints?: string[] } }
}
type ExternalLinksCapability = {
  identifier: string
  windows: string[]
  platforms: string[]
  local: boolean
  remote: { urls: string[] }
  permissions: Array<{
    identifier: string
    allow?: Array<{ url: string }>
  }>
}
const externalLinksCapability = JSON.parse(
  readFileSync(
    resolve(import.meta.dirname, "../../src/desktop/src-tauri/capabilities/external-links.json"),
    "utf8",
  ),
) as ExternalLinksCapability
const desktopMacConfig = JSON.parse(
  readFileSync(resolve(import.meta.dirname, "../../src/desktop/src-tauri/tauri.macos.conf.json"), "utf8"),
) as { bundle?: { macOS?: { entitlements?: string; hardenedRuntime?: boolean; signingIdentity?: string } } }
const desktopIosConfig = JSON.parse(
  readFileSync(resolve(import.meta.dirname, "../../src/desktop/src-tauri/tauri.ios.conf.json"), "utf8"),
) as { identifier?: string }
const desktopAndroidConfig = JSON.parse(
  readFileSync(resolve(import.meta.dirname, "../../src/desktop/src-tauri/tauri.android.conf.json"), "utf8"),
) as { identifier?: string }
const androidGradle = readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/gen/android/app/build.gradle.kts"),
  "utf8",
)
const androidMainActivity = readFileSync(
  resolve(
    import.meta.dirname,
    "../../src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt",
  ),
  "utf8",
)
const iosExportOptions = readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/gen/apple/ExportOptions.plist"),
  "utf8",
)
const iosProject = readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/gen/apple/project.yml"),
  "utf8",
)
const iosPodfile = readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/gen/apple/Podfile"),
  "utf8",
)
const nativeOauthMainAasaRoute = readFileSync(
  resolve(import.meta.dirname, "../../src/web/src/app/.well-known/apple-app-site-association/route.ts"),
  "utf8",
)
const nativeOauthMainAssetLinksRoute = readFileSync(
  resolve(import.meta.dirname, "../../src/web/src/app/.well-known/assetlinks.json/route.ts"),
  "utf8",
)
const nativeOauthAuthWorker = readFileSync(
  resolve(import.meta.dirname, "../../src/web/auth/index.ts"),
  "utf8",
)
const nativeOauthAuthConfig = readFileSync(
  resolve(import.meta.dirname, "../../src/web/auth/wrangler.toml"),
  "utf8",
)
const nativeOauthWebConfig = readFileSync(
  resolve(import.meta.dirname, "../../src/web/wrangler.toml"),
  "utf8",
)
const nativeOauthContract = readFileSync(
  resolve(import.meta.dirname, "../../src/web/src/lib/native-oauth.ts"),
  "utf8",
)
const nativeOauthWebRuntime = readFileSync(
  resolve(import.meta.dirname, "../../src/web/src/lib/worker-runtime.ts"),
  "utf8",
)
const desktopEntitlementsPath = resolve(
  import.meta.dirname,
  "../../src/desktop/src-tauri/entitlements.plist",
)
const desktopBuildScript = readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/scripts/build.sh"),
  "utf8",
)
const desktopCargoManifest = readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/Cargo.toml"),
  "utf8",
)
const desktopRustEntry = readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/src/lib.rs"),
  "utf8",
)
type DesktopCapability = {
  identifier: string
  windows?: string[]
  platforms?: string[]
  local?: boolean
  remote?: { urls?: string[] }
  permissions: string[]
}
const desktopCapability = JSON.parse(readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/capabilities/desktop.json"),
  "utf8",
)) as DesktopCapability
const desktopDevConfig = JSON.parse(readFileSync(
  resolve(import.meta.dirname, "../../src/desktop/src-tauri/tauri.dev.conf.json"),
  "utf8",
)) as {
  app: { security: { capabilities: Array<string | DesktopCapability | ExternalLinksCapability> } }
}
const bumpScript = readFileSync(resolve(import.meta.dirname, "../bump-version.mjs"), "utf8")
const desktopUpdateRoute = readFileSync(
  resolve(import.meta.dirname, "../../src/web/src/app/api/desktop/update/[target]/[arch]/[current_version]/route.ts"),
  "utf8",
)
const publishWorkflows = ["publish-app.yml", "publish-daemon.yml"]
  .map((name) => normalizeWorkflow(readFileSync(resolve(workflowRoot, name), "utf8")))
const publishDaemonWorkflow = normalizeWorkflow(
  readFileSync(resolve(workflowRoot, "publish-daemon.yml"), "utf8"),
)
const agentDriverPackage = JSON.parse(
  readFileSync(resolve(repositoryRoot, "src/daemon/agent-driver/package.json"), "utf8"),
) as {
  private?: boolean
  publishConfig?: unknown
  scripts: Record<string, string>
  devDependencies: Record<string, string>
}
const daemonPackage = JSON.parse(
  readFileSync(resolve(repositoryRoot, "src/daemon/package.json"), "utf8"),
) as {
  scripts: Record<string, string>
  devDependencies?: Record<string, string>
}
const workspaceManifest = readFileSync(resolve(repositoryRoot, "pnpm-workspace.yaml"), "utf8")
const appPackedArtifactScript = readFileSync(
  resolve(repositoryRoot, "src/app/scripts/app-packed-artifact.mjs"),
  "utf8",
)
const packedArtifactVerifier = readFileSync(
  resolve(repositoryRoot, "src/app/scripts/verify-packed-artifact.mjs"),
  "utf8",
)

function ciJob(name: string): string {
  const start = ciWorkflow.indexOf(`\n  ${name}:\n`)
  if (start < 0) throw new Error(`missing CI job: ${name}`)
  const next = ciWorkflow.slice(start + 1).search(/\n  [a-z][a-z0-9-]*:\n/)
  return next < 0 ? ciWorkflow.slice(start) : ciWorkflow.slice(start, start + 1 + next)
}

describe("E2E UI workflow", () => {
  it("uses one exact Node release for shared build production and verification", () => {
    const nodeVersion = (job: string) => ciJob(job).match(/^\s*node-version:\s*["']?([^"'\s]+)["']?\s*$/m)?.[1]
    const version = nodeVersion("ui-e2e-build")
    expect(version).toMatch(/^\d+\.\d+\.\d+$/)
    const verifiers = [...ciWorkflow.matchAll(/^  ([a-z][a-z0-9-]*):$/gm)]
      .map(match => match[1])
      .filter(job => ciJob(job).includes("e2e-build-artifact.mjs verify"))
    expect(verifiers.length).toBeGreaterThan(0)
    for (const job of verifiers) expect(nodeVersion(job), job).toBe(version)
  })

  it("isolates resizable-panels upgrades after adopting the latest compatible release", () => {
    expect(dependabotConfig).toMatch(/^[ ]{6}resizable-panels:\n[ ]{8}patterns:\n[ ]{10}- "react-resizable-panels"$/m)
    expect(dependabotConfig).toMatch(/^[ ]{8}exclude-patterns:[\s\S]*?^[ ]{10}- "react-resizable-panels"$/m)
    expect(dependabotConfig).not.toMatch(/^[ ]{6}- dependency-name: "react-resizable-panels"$/m)
  })


  it("keeps selected browser runs read-only without a separate main history", () => {
    expect(workflow).toContain("actions: read")
    expect(workflow).not.toMatch(/^  pull_request_target:/m)
    expect(workflow).not.toContain("e2e-timing-history")
    for (const job of ["e2e-ui", "merge-reports"]) {
      expect(ciJob(job)).toContain("run_ui_e2e == 'true'")
      expect(ciJob(job)).not.toContain("github.event_name != 'push'")
    }
  })

  it("keeps failure diagnostics best-effort and merge inputs strict", () => {
    expect(workflow).toContain("src/web/e2e-service-logs/")
    expect(workflow).toContain("continue-on-error: true")
    expect(workflow).toContain("if-no-files-found: ignore")
    expect(workflow).toContain("retention-days: 7")
    expect(workflow).toContain(
      "name: blob-report-${{ github.run_id }}-${{ matrix.shard }}",
    )
    expect(workflow).toContain(
      "pattern: blob-report-${{ github.run_id }}-*",
    )
    expect(workflow).toContain("overwrite: true")
    expect(workflow).toContain("merge-multiple: false")
    expect(workflow).toContain("actions: read")
    expect(workflow).toContain("verify-artifacts")
    expect(workflow).toContain("verify-merged")
    expect(workflow).toContain("--reporter html,json")
    expect(workflow).not.toContain("playwright-merge-runtime")
    expect(ciJob("e2e-ui").match(/pnpm install --frozen-lockfile/g)).toHaveLength(1)
    expect(ciJob("merge-reports").match(/pnpm install --frozen-lockfile/g)).toHaveLength(1)
    expect(ciJob("e2e-ui").match(/continue-on-error: true/g)).toHaveLength(1)
  })

  it("reports shard failures directly to GitHub Checks", () => {
    expect(playwrightConfig).toContain('[["blob"], ["github"], ["list"]]')
  })

  it("does not install Bun for Node-only browser tests", () => {
    expect(ciJob("e2e-ui")).not.toContain("oven-sh/setup-bun")
    expect(ciJob("merge-reports")).not.toContain("oven-sh/setup-bun")
  })

  it("runs shards in the lockfile-selected Playwright image without host installs", () => {
    expect(workflow).toContain("image: ${{ matrix.image }}")
    expect(workflow).toContain("options: --init --ipc=host --user 1001")
    expect(workflow).toMatch(/defaults:\n      run:\n        shell: bash/)
    expect(ciJob("e2e-ui")).not.toContain("playwright-browser-cache")
    expect(ciJob("e2e-ui")).not.toContain("~/.cache/ms-playwright")
    expect(ciJob("e2e-ui")).not.toContain("playwright install-deps")
    expect(ciJob("e2e-ui")).not.toContain("playwright install chromium")
  })

  it("builds one exact-head OpenNext artifact and makes every shard verify it without fallback", () => {
    const producer = ciJob("ui-e2e-build")
    const shard = ciJob("e2e-ui")
    const gate = ciJob("ui-e2e-gate")
    const devVars = "printf 'BETTER_AUTH_SECRET=ci-e2e-ui-secret\\nBETTER_AUTH_URL=http://localhost:3000\\nENCRYPTION_KEY=ci-e2e-encryption-key-32chars!!\\nDEV_WS_DO_URL=http://localhost:3000\\nNODE_ENV=development\\n' > src/web/.dev.vars"

    expect(producer).toContain("image: ${{ needs.scope.outputs.worker_build_image }}")
    expect(producer).toContain("options: --init --ipc=host --user 1001")
    expect(producer).toContain("NEXT_PUBLIC_WS_DO_PORT: \"3000\"")
    expect(producer).toContain(devVars)
    expect(shard).toContain(devVars)
    expect(producer).toContain("run_worker_build == 'true'")
    expect(producer).toContain('node scripts/ci/run-turbo.mjs run "${tasks[@]}" --concurrency=1')
    expect(producer).toContain('"@alook/web#build:blog"')
    expect(producer).toContain("e2e-build-artifact.mjs create")
    expect(producer).toContain("name: ${{ steps.artifact_identity.outputs.artifact_name }}")
    expect(producer).toContain("ui-e2e-build-manifest.json")
    expect(producer).toContain("ui-e2e-build.tgz")
    expect(producer).toContain("include-hidden-files: true")
    expect(producer).toContain("--directory .ci/ui-e2e-build")

    expect(shard).toContain("needs: [scope, ui-e2e-build]")
    expect(shard).toContain("actions/download-artifact")
    expect(shard).toContain("e2e-build-artifact.mjs verify")
    expect(shard).toContain('ALOOK_E2E_PREBUILT: "1"')
    expect(shard).not.toContain("opennextjs-cloudflare build")
    expect(shard).not.toContain("pnpm --filter @alook/web build:blog")
    expect(shard.indexOf("e2e-build-artifact.mjs verify"))
      .toBeLessThan(shard.indexOf("playwright test"))

    expect(gate).toContain("needs: [scope, ui-e2e-build, e2e-ui, resizable-panels-compat, merge-reports]")
    expect(gate).toContain('{"name":"ui-e2e-build"')
  })

  it("gates isolated resizable-panels upgrades on responsive shell journeys", () => {
    const compatibility = ciJob("resizable-panels-compat")
    const gate = ciJob("ui-e2e-gate")

    expect(changeScopeManifest.ui.contracts.resizable_panels).toEqual([
      "53-mobile-inbox-surface.spec.ts",
      "60-desktop-default-user-bar-width.spec.ts",
    ])
    expect(compatibility).toContain("needs.scope.outputs.run_resizable_panels_compat == 'true'")
    for (const spec of changeScopeManifest.ui.contracts.resizable_panels) {
      expect(compatibility).toContain(`src/test/e2e-ui/${spec}`)
    }
    expect(compatibility).toContain("preserves Marked tab, scroll, and request ownership across 639↔640")
    expect(compatibility).toContain("restores fresh and saved mobile-first desktop entries before paint")
    expect(compatibility).toContain("needs: [scope, ui-e2e-build]")
    expect(compatibility).toContain("e2e-build-artifact.mjs verify")
    expect(compatibility).toContain('ALOOK_E2E_PREBUILT: "1"')
    expect(compatibility).not.toContain("opennextjs-cloudflare build")
    expect(gate).toContain('{"name":"resizable-panels-compat"')
    expect(gate).toContain("needs.scope.outputs.run_resizable_panels_compat == 'true'")
  })

  it("pins partial reruns to the successful producer's artifact identity", () => {
    const producer = ciJob("ui-e2e-build")
    const shard = ciJob("e2e-ui")

    expect(producer).toContain("artifact_name: ${{ steps.artifact_identity.outputs.artifact_name }}")
    expect(producer).toContain("artifact_attempt: ${{ steps.artifact_identity.outputs.artifact_attempt }}")
    expect(producer).toContain('artifact_name=ui-e2e-build-%s-%s\\n')
    expect(producer).toContain('--attempt "${{ steps.artifact_identity.outputs.artifact_attempt }}"')
    expect(producer).toContain("name: ${{ steps.artifact_identity.outputs.artifact_name }}")

    expect(shard).toContain("name: ${{ needs.ui-e2e-build.outputs.artifact_name }}")
    expect(shard).toContain('--attempt "${{ needs.ui-e2e-build.outputs.artifact_attempt }}"')
    expect(shard).not.toContain("name: ui-e2e-build-${{ github.run_id }}-${{ github.run_attempt }}")
  })
})

describe("Bun workflow setup", () => {
  it("normalizes Windows checkout line endings before locating jobs", () => {
    expect(normalizeWorkflow("jobs:\r\n  test-linux:\r\n")).toBe("jobs:\n  test-linux:\n")
  })

  it("installs pinned Bun in every CI job that builds a daemon package fixture", () => {
    const selectedBun = ciJob("static-checks").match(/bun-version: (\d+\.\d+\.\d+)$/m)?.[1]
    expect(selectedBun).toMatch(/^\d+\.\d+\.\d+$/)
    const bunJobs = ["static-checks", "test-linux", "test-windows", "app-packed-artifact"]
    expect(ciWorkflow.match(/oven-sh\/setup-bun/g)).toHaveLength(bunJobs.length)
    for (const job of bunJobs) {
      expect(ciJob(job)).toContain("oven-sh/setup-bun")
      expect(ciJob(job).match(/bun-version: (\d+\.\d+\.\d+)$/m)?.[1]).toBe(selectedBun)
    }
    for (const publishWorkflow of publishWorkflows) {
      expect(publishWorkflow).toContain("oven-sh/setup-bun")
      expect(publishWorkflow.match(/bun-version: (\d+\.\d+\.\d+)$/m)?.[1]).toBe(selectedBun)
    }
  })
})

describe("Local package test isolation", () => {
  it("keeps daemon artifact writers serial without flattening ordinary tests", () => {
    const artifactTests = [
      "src/version.packed.test.ts",
      "src/agent-driver-bundle.packed.test.ts",
      "src/cli/daemonSelfUpdate.real.test.ts",
    ]
    expect(daemonPackage.scripts.test).toBe("pnpm test:unit && pnpm test:packed")
    expect(daemonPackage.scripts["test:unit"]).not.toContain("--no-file-parallelism")
    expect(daemonPackage.scripts["test:packed"]).toContain("--no-file-parallelism")
    for (const testPath of artifactTests) {
      expect(daemonPackage.scripts["test:unit"]).toContain(`--exclude ${testPath}`)
      expect(daemonPackage.scripts["test:packed"]).toContain(testPath)
    }

    const rootTest = rootPackageJson.scripts.test
    const workspaceTests = rootTest.indexOf("scripts/ci/run-turbo.mjs run test")
    const driverTests = rootTest.indexOf("@alook/agent-driver#test")
    const scriptTests = rootTest.indexOf("vitest run --project ci-scripts")
    expect(workspaceTests).toBeGreaterThanOrEqual(0)
    expect(driverTests).toBeGreaterThan(workspaceTests)
    expect(scriptTests).toBeGreaterThan(driverTests)
  })
})

describe("CI workflow graph", () => {
  it("isolates explicit full runs while retaining cancellation of superseded ordinary checks", () => {
    const concurrency = ciWorkflow.slice(ciWorkflow.indexOf("\nconcurrency:\n"), ciWorkflow.indexOf("\njobs:\n"))
    const group = concurrency.split("\n").find((line) => line.trimStart().startsWith("group:"))!
    expect(group).toContain("github.event_name == 'workflow_dispatch'")
    expect(group).toContain("startsWith(github.event.head_commit.message, 'release:')")
    expect(group).toContain("github.run_id")
    expect(concurrency).toContain("cancel-in-progress: true")
  })

  it("keeps approved triggers without a daily schedule", () => {
    expect(ciWorkflow).toMatch(/^  push:/m)
    expect(ciWorkflow).toMatch(/^  pull_request:/m)
    expect(ciWorkflow).toMatch(/^  merge_group:/m)
    expect(ciWorkflow).toMatch(/^  workflow_dispatch:/m)
    expect(ciWorkflow).not.toMatch(/^  schedule:/m)
    expect(existsSync(legacyUiWorkflowPath)).toBe(false)
    expect(ciWorkflow.match(/^  scope:$/gm)).toHaveLength(1)
  })

  it("keeps manual dispatch full by default and guards diagnostic fixtures before scoping", () => {
    const scope = ciJob("scope")
    expect(ciWorkflow).toContain("options: [full, characterization]")
    expect(ciWorkflow).toContain("default: full")
    expect(ciWorkflow).toContain("pull-requests: read")
    expect(scope).toContain('gh api "repos/$GITHUB_REPOSITORY/pulls/$CANDIDATE_PR"')
    expect(scope).toContain("node scripts/ci/characterization-guard.mjs")
    expect(scope).toContain('--ref-name "$GITHUB_REF_NAME"')
    expect(scope).toContain('--candidate-sha "$CANDIDATE_SHA"')
    expect(scope).toContain('--fixture-sha "$FIXTURE_SHA"')
    expect(scope).toContain('--expected-class "$EXPECTED_CLASS"')
    expect(scope).toContain('--diagnostic-only')
    expect(scope).toContain('args+=(--base "$EVENT_SHA" --head "$EVENT_SHA" --force-full)')
    expect(scope).toContain('args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --main-smoke)')
    expect(scope).toContain('args+=(--base "$PUSH_BASE_SHA" --head "$EVENT_SHA" --force-full)')
    expect(scope).not.toContain("ref: ${{ inputs.fixture_sha }}")
  })

  it("publishes one auditable plan and validates its envelope in every consumer", () => {
    const scope = ciJob("scope")
    expect(scope).toContain("--plan-file .ci/execution-plan.json")
    expect(scope).toContain("name: execution-plan-${{ github.run_id }}-${{ github.run_attempt }}")
    for (const job of [
      "auth-build", "blog-build", "static-checks", "test-linux", "test-windows", "app-packed-artifact",
      "e2e", "desktop-rust", "lighthouse", "ui-e2e-build", "e2e-ui", "resizable-panels-compat", "merge-reports",
      "ci-gate", "ui-e2e-gate",
    ]) {
      const definition = ciJob(job)
      expect(definition, job).toContain("CI_EXECUTION_PLAN_FILE: .ci/execution-plan.json")
      expect(definition, job).toContain("CI_PLAN_HASH: ${{ needs.scope.outputs.plan_hash }}")
      expect(definition, job).toContain("node scripts/ci/validate-execution-plan.mjs")
      expect(definition, job).toContain("name: ${{ needs.scope.outputs.plan_artifact_name }}")
      expect(definition.indexOf("- name: Download execution plan")).toBeLessThan(definition.indexOf("- name: Validate execution plan"))
    }
  })

  it("reports project and patch percentages while preserving coverage integrity and upload errors", () => {
    const linux = ciJob("test-linux")
    expect(linux).toContain("CI_EXECUTION_PLAN")
    expect(linux).toContain("verify-coverage-plan.mjs")
    expect(linux).toContain("coverage-target-manifest.json")
    expect(linux).toContain("coverage/coverage-final.json")
    const coveragePolicy = readFileSync(resolve(repositoryRoot, "codecov.yml"), "utf8")
    expect(coveragePolicy).toMatch(/patch:[\s\S]*informational: true/)
    expect(coveragePolicy).not.toMatch(/target: \d/)
    expect(linux).toContain("fail_ci_if_error: true")
  })

  it("prepares shared services for every selected integration suite", () => {
    const e2e = ciJob("e2e")
    const webCondition = "if: contains(fromJSON(needs.scope.outputs.integration_suites), 'web')"
    const daemonCondition = "if: contains(fromJSON(needs.scope.outputs.integration_suites), 'daemon')"

    expect(e2e).toContain("if: needs.scope.outputs.run_e2e == 'true'")
    expect(e2e).toContain("- name: Create local bindings\n        run:")
    expect(e2e).toContain("cp src/queue-worker/.dev.vars.example src/queue-worker/.dev.vars")
    expect(e2e.match(/ci-e2e-encryption-key-32chars!!/g)).toHaveLength(2)
    expect(e2e).toContain("- run: pnpm run db:migrate")
    expect(e2e).toContain("- name: Start dev servers\n        run: |")
    expect(e2e).toContain("- name: Wait for services\n        run: |")
    expect(e2e.indexOf("pnpm --filter @alook/ws-do dev &")).toBeLessThan(
      e2e.indexOf("pnpm --filter @alook/queue-worker dev &"),
    )
    expect(e2e.indexOf("pnpm --filter @alook/queue-worker dev &")).toBeLessThan(
      e2e.indexOf("pnpm --filter @alook/email-worker dev &"),
    )
    expect(e2e.indexOf("pnpm --filter @alook/email-worker dev &")).toBeLessThan(
      e2e.indexOf("pnpm --filter @alook/web dev &"),
    )
    expect(e2e).not.toContain('pkill -f "wrangler"')
    expect(e2e.match(new RegExp(webCondition.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")))
      .toHaveLength(1)
    expect(e2e.match(new RegExp(daemonCondition.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")))
      .toHaveLength(1)
    expect(e2e).toContain(`${webCondition}\n        run: pnpm test:e2e`)
    expect(e2e).toContain(`${daemonCondition}\n        run: pnpm --filter @alook/daemon run test:integration`)
  })

  it("migrates Lighthouse's fresh local database before starting the web app", () => {
    const lighthouse = ciJob("lighthouse")

    expect(lighthouse).toContain("BETTER_AUTH_SECRET=ci-lighthouse-secret")
    expect(lighthouse).toContain("- run: pnpm run db:migrate")
    expect(lighthouse).toContain("npx @lhci/cli autorun --config=lighthouserc.json")
    expect(lighthouse.indexOf("pnpm run db:migrate")).toBeLessThan(
      lighthouse.indexOf("npx @lhci/cli autorun --config=lighthouserc.json"),
    )
  })

  it("consolidates static work and preserves non-blocking Knip steps", () => {
    const staticChecks = ciJob("static-checks")
    expect(ciWorkflow).not.toMatch(/^  quality:/m)
    expect(ciWorkflow).not.toMatch(/^  knip:/m)
    expect(ciWorkflow).not.toMatch(/^  build:/m)
    expect(staticChecks.match(/pnpm install --frozen-lockfile/g)).toHaveLength(1)
    expect(staticChecks.match(/continue-on-error: true/g)).toHaveLength(1)
    expect(staticChecks).toContain("--plan-group static_tasks")
    expect(staticChecks).toContain("--plan-group static_tasks")
    expect(staticChecks).toContain("--plan-group build_tasks")
    expect(staticChecks).toContain("--plan-group knip_tasks")
  })

  it("gates the consolidated jobs under the stable CI Gate", () => {
    const gate = ciJob("ci-gate")
    for (const job of ["auth-build", "static-checks", "test-linux", "test-windows", "app-packed-artifact"]) {
      expect(gate).toContain(`- ${job}`)
      expect(gate).toContain(`"name":"${job}"`)
    }
    for (const removed of ["quality", "knip", "build", "coverage"]) {
      expect(gate).not.toContain(`- ${removed}`)
      expect(gate).not.toContain(`"name":"${removed}"`)
    }
  })

  it("gates the fail-closed exact-tarball app artifact check", () => {
    const scope = ciJob("scope")
    const artifact = ciJob("app-packed-artifact")
    const gate = ciJob("ci-gate")
    expect(scope).toContain(
      "run_app_packed_artifact: ${{ steps.scope.outputs.run_app_packed_artifact }}",
    )
    expect(artifact).toContain("if: needs.scope.outputs.run_app_packed_artifact == 'true'")
    expect(artifact).toContain("timeout-minutes: 15")
    expect(artifact).toContain("node src/app/scripts/app-packed-artifact.mjs --output-dir")
    expect(artifact).toContain("if: always()")
    expect(artifact).toContain("if-no-files-found: error")
    expect(artifact).toContain('tarballs=("$RUNNER_TEMP"/alook-app-packed-artifact/*.tgz)')
    expect(artifact).toContain("[[ ${#tarballs[@]} -eq 1 ]]")
    for (const evidence of [
      "*.tgz",
      "manifest.json",
      "artifact-verification/positive-wrangler.log",
      "artifact-verification/negative-wrangler.log",
    ]) {
      expect(artifact).toContain(evidence)
    }
    for (const excluded of [
      "artifact-verification/extracted",
      "artifact-verification/negative/package",
      "artifact-verification/positive-wrangler/**",
      "artifact-verification/negative-wrangler/**",
    ]) {
      expect(artifact).not.toContain(excluded)
    }
    expect(gate).toContain("- app-packed-artifact")
    expect(gate).toContain('"name":"app-packed-artifact"')
  })
})

describe("App packed artifact CI contract", () => {
  it("packs once and verifies those exact bytes without lifecycle or publishing", () => {
    expect(appPackedArtifactScript.match(/execFileSync\("npm", \[\s*"pack"/g)).toHaveLength(1)
    expect(appPackedArtifactScript).toContain("verifyPackedArtifact(tarball")
    expect(appPackedArtifactScript).not.toContain("self-hosted")
    expect(appPackedArtifactScript).not.toContain("onboard")
    expect(appPackedArtifactScript).not.toContain("npm publish")
  })

  it("derives the negative from the extracted candidate and requires the missing runtime", () => {
    expect(packedArtifactVerifier).toContain("cpSync(packageRoot, negativePackageRoot")
    expect(packedArtifactVerifier).toContain("rmSync(negativeRuntime)")
    expect(packedArtifactVerifier).toContain('negativeOutput.includes("worker-runtime")')
    expect(packedArtifactVerifier).toContain("Packed artifact Wrangler dry-run produced no output")
  })
})

describe("Private agent driver package", () => {
  it("remains an independent private workspace dependency of the daemon", () => {
    expect(agentDriverPackage.private).toBe(true)
    expect(agentDriverPackage).not.toHaveProperty("publishConfig")
    expect(workspaceManifest).toContain('"src/daemon/agent-driver"')
    expect(daemonPackage.devDependencies?.["@alook/agent-driver"]).toBe("workspace:*")
  })

  it("cannot be published by a repository workflow", () => {
    expect(existsSync(resolve(workflowRoot, "publish-agent-driver.yml"))).toBe(false)
  })

  it("builds the daemon publish input through the native prerequisite graph", () => {
    expect(publishDaemonWorkflow).toContain("node scripts/ci/run-turbo.mjs run @alook/daemon#build")
    const config = JSON.parse(readFileSync(resolve(repositoryRoot, "turbo.json"), "utf8"))
    expect(config.tasks["@alook/daemon#build"].dependsOn).toContain("@alook/agent-driver#build")
    expect(daemonPackage.scripts.prepack).toContain("@alook/daemon#build")
  })

  it("keeps runtime and artifact contracts without the removed API report mechanism", () => {
    expect(agentDriverPackage.scripts).not.toHaveProperty("api:check")
    expect(agentDriverPackage.scripts).not.toHaveProperty("api:update")
    expect(agentDriverPackage.devDependencies).not.toHaveProperty("@microsoft/api-extractor")
    expect(rootPackageJson.scripts).not.toHaveProperty("api:check")
    expect(rootPackageJson.scripts).not.toHaveProperty("api:update")
    for (const path of [
      ".github/api-surface-owners.json",
      ".github/workflows/api-surface-check.yml",
      ".github/workflows/api-surface-guard.yml",
      "scripts/ci/api-report-contract.test.ts",
      "scripts/ci/api-surface-guard.mjs",
      "scripts/ci/api-surface-guard.test.ts",
      "src/daemon/agent-driver/scripts/api-reports.mjs",
      "src/daemon/agent-driver/etc/api/root.api.md",
      "src/daemon/agent-driver/api-extractor.root.json",
    ]) {
      expect(existsSync(resolve(repositoryRoot, path))).toBe(false)
    }
  })
})

describe("CI test budgets", () => {
  it("gives the slower Windows workspace suite enough job time", () => {
    expect(ciJob("test-windows")).toContain("timeout-minutes: 15")
  })

  it("runs Windows process-authority and full driver fixtures in isolation before the daemon suite", () => {
    const windows = ciJob("test-windows")
    const processAuthority = windows.indexOf(
      "pnpm --filter @alook/agent-driver exec vitest run src/internal/killTree.test.ts",
    )
    const driver = windows.indexOf(
      "pnpm --filter @alook/agent-driver exec vitest run --no-file-parallelism --coverage --coverage.reporter=json --coverage.reporter=text",
    )
    const coverageUpload = windows.indexOf("files: ./src/daemon/agent-driver/coverage/coverage-final.json")
    const focusedAdmission = windows.indexOf(
      "pnpm --filter @alook/daemon exec vitest run src/daemon/createDaemon.test.ts",
    )
    const daemon = windows.indexOf("pnpm --filter @alook/daemon test")
    expect(processAuthority).toBeGreaterThan(0)
    expect(driver).toBeGreaterThan(processAuthority)
    expect(coverageUpload).toBeGreaterThan(driver)
    expect(focusedAdmission).toBeGreaterThan(coverageUpload)
    expect(daemon).toBeGreaterThan(focusedAdmission)
  })

  it("uploads the Windows driver report without accidentally discovering unrelated files", () => {
    const windows = ciJob("test-windows")
    expect(windows).toContain("disable_search: true")
    expect(windows).toContain("name: windows-agent-driver")
    expect(windows).toContain("fail_ci_if_error: true")
  })

  it("runs only Windows-relevant workspace packages after the process-bearing suites", () => {
    const windows = ciJob("test-windows")
    expect(windows).toContain("for suite in app shared")
    expect(windows).toContain('filters+=("--filter=@alook/$suite")')
    expect(windows).toContain('node scripts/ci/run-turbo.mjs run test "${filters[@]}"')
    expect(windows).not.toContain("--affected")
    for (const packageName of ["web", "email-worker", "ws-do", "queue-worker"]) {
      expect(windows).not.toContain(`--filter=@alook/${packageName}`)
    }
    expect(windows).not.toContain("--project ci-scripts")
  })
})

describe("CI dependency setup", () => {
  it("checks generated Android toolchain and tracked customization before credentials or signed builds", () => {
    const init = mobileReleaseWorkflow.indexOf("- name: Generate Android project support files")
    const verify = mobileReleaseWorkflow.indexOf("- name: Verify Android initialization and toolchain")
    const firebase = mobileReleaseWorkflow.indexOf("- name: Prepare Android Firebase configuration")
    const signing = mobileReleaseWorkflow.indexOf("- name: Prepare Android release signing")
    expect(init).toBeGreaterThan(-1)
    expect(verify).toBeGreaterThan(init)
    expect(firebase).toBeGreaterThan(verify)
    expect(signing).toBeGreaterThan(verify)
    expect(mobileReleaseWorkflow.slice(verify, firebase)).toContain("git diff --exit-code -- src/desktop/src-tauri/gen/android")
    expect(mobileReleaseWorkflow.slice(verify, firebase)).toContain("node scripts/ci/verify-android-project.mjs")
    expect(mobileReleaseWorkflow.slice(verify, firebase)).not.toContain("continue-on-error")
  })

  it("compiles Windows consumers through the existing scoped Rust gate without release credentials", () => {
    const desktopRust = ciJob("desktop-rust")
    expect(desktopRust).toContain("platform: [ubuntu-latest, windows-latest]")
    expect(desktopRust).toContain("if: needs.scope.outputs.run_rust == 'true'")
    expect(desktopRust).toContain("cargo check --locked --target x86_64-pc-windows-msvc --all-targets")
    expect(desktopRust).toContain("run: cargo test --locked")
    expect(desktopRust).not.toContain("secrets.")
    expect(desktopRust).not.toContain("tauri-action")
  })

  it("notarizes the final DMG before immutable staging and keeps the final macOS verifier", () => {
    const submit = desktopReleaseWorkflow.indexOf("- name: Notarize and staple final macOS DMG")
    const stage = desktopReleaseWorkflow.indexOf("- name: Stage exact release bytes")
    const verify = desktopReleaseWorkflow.indexOf("- name: Verify staged macOS bytes")
    expect(submit).toBeGreaterThan(-1)
    expect(stage).toBeGreaterThan(submit)
    expect(verify).toBeGreaterThan(stage)
    expect(desktopReleaseWorkflow.slice(submit, stage)).toContain("if: runner.os == 'macOS'")
    expect(desktopReleaseWorkflow.slice(submit, stage)).not.toContain("continue-on-error")
    expect(desktopMacVerifier).toContain("stapler validate")
  })

  it("installs cargo-machete from the pinned release action", () => {
    const desktopRust = ciJob("desktop-rust")
    expect(desktopRust).toMatch(/uses: taiki-e\/install-action@[a-f0-9]{40} # cargo-machete$/m)
    expect(desktopRust).not.toContain("cargo install cargo-machete")
    expect(desktopRust).toContain("run: cargo machete")
  })

  it("caches pnpm and target-specific Rust artifacts for desktop releases", () => {
    const pnpmSetup = desktopReleaseWorkflow.indexOf("pnpm/action-setup@")
    const nodeSetup = desktopReleaseWorkflow.indexOf("actions/setup-node@")
    expect(pnpmSetup).toBeGreaterThan(-1)
    expect(nodeSetup).toBeGreaterThan(pnpmSetup)
    expect(desktopReleaseWorkflow).toContain("cache: pnpm")
    expect(desktopReleaseWorkflow).toContain("cache-dependency-path: pnpm-lock.yaml")
    expect(desktopReleaseWorkflow).toMatch(/uses: Swatinem\/rust-cache@[a-f0-9]{40}(?:\s+#.*)?$/m)
    expect(desktopReleaseWorkflow).toContain("key: ${{ matrix.target }}")
  })
})

describe("Native message external-link opener", () => {
  const expectedPlatforms = ["linux", "macOS", "windows", "android", "iOS"]
  const expectedPermission = [{
    identifier: "opener:allow-open-url",
    allow: [{ url: "http://*" }, { url: "https://*" }],
  }]
  const scopedUrlAllowed = (href: string, capability: ExternalLinksCapability) => {
    const patterns = capability.permissions.flatMap((permission) => (
      permission.allow?.map((entry) => entry.url) ?? []
    ))
    return patterns.includes(`${new URL(href).protocol}//*`)
  }

  it("registers the official opener plugin in the common desktop/mobile builder", () => {
    const desktopOnlyDependencies = desktopCargoManifest.indexOf(
      "[target.\"cfg(not(any(target_os = \\\"android\\\", target_os = \\\"ios\\\")))\".dependencies]",
    )
    const dependency = desktopCargoManifest.indexOf('tauri-plugin-opener = "2"')
    const registration = desktopRustEntry.indexOf("plugin(tauri_plugin_opener::init())")
    const desktopOnlyPlugins = desktopRustEntry.indexOf("// Desktop-only plugins")

    expect(dependency).toBeGreaterThan(-1)
    expect(dependency).toBeLessThan(desktopOnlyDependencies)
    expect(registration).toBeGreaterThan(-1)
    expect(registration).toBeLessThan(desktopOnlyPlugins)
  })

  it("grants only scoped HTTP(S) URL opening to the production five-platform app webview", () => {
    expect(externalLinksCapability).toMatchObject({
      identifier: "external-links",
      windows: ["main"],
      platforms: expectedPlatforms,
      local: true,
      remote: { urls: ["https://alook.ai"] },
      permissions: expectedPermission,
    })
    expect(desktopConfig.app?.security?.capabilities).toContain("external-links")
    expect([
      "http://example.com:8080/path/to/story?source=chat#section",
      "https://example.com:9443/a/b?query=yes#fragment",
      "https://alook.ai/c/invite/abcdef?from=dm",
    ].every((href) => scopedUrlAllowed(href, externalLinksCapability))).toBe(true)
    expect([
      "mailto:[email protected]",
      "tel:+15551234567",
      "file:///tmp/private",
    ].some((href) => scopedUrlAllowed(href, externalLinksCapability))).toBe(false)
  })

  it("reuses the same minimal HTTP(S) scope for the local development app webview", () => {
    const capabilities = desktopDevConfig.app?.security?.capabilities ?? []
    const inlineOpener = capabilities.find((capability): capability is ExternalLinksCapability => (
      typeof capability !== "string"
      && capability.permissions.some((permission) => (
        typeof permission !== "string" && permission.identifier.startsWith("opener:")
      ))
    ))

    expect(capabilities).toContain("external-links")
    expect(capabilities.filter((capability) => capability === "external-links")).toHaveLength(1)
    expect(inlineOpener).toBeUndefined()
  })

  it("does not grant default schemes, paths, reveal, shell, or CSP expansion", () => {
    const capabilityText = JSON.stringify({
      production: externalLinksCapability,
      development: desktopDevConfig.app?.security?.capabilities,
    })
    for (const rejected of [
      "opener:default",
      "opener:allow-default-urls",
      "opener:allow-open-path",
      "opener:allow-reveal-item-in-dir",
      "shell:",
      "mailto:",
      "tel:",
    ]) {
      expect(capabilityText).not.toContain(rejected)
    }
    expect(desktopConfig.app).not.toHaveProperty("security.csp")
  })
})

describe("Turbo CI execution", () => {
  const cachedJobs = ["auth-build", "blog-build", "static-checks", "test-linux", "test-windows"]

  it("persists a task cache isolated by operating system, architecture, and job", () => {
    expect(ciWorkflow.match(/uses: actions\/cache@[a-f0-9]{40}(?:\s+#.*)?$/gm))
      .toHaveLength(cachedJobs.length)
    for (const job of cachedJobs) {
      const definition = ciJob(job)
      expect(definition).toContain("path: .turbo/cache")
      expect(definition).toContain(
        "key: turbo-${{ runner.os }}-${{ runner.arch }}-${{ github.job }}-${{ github.sha }}",
      )
      expect(definition).toContain(
        "turbo-${{ runner.os }}-${{ runner.arch }}-${{ github.job }}-",
      )
    }
  })

  it("passes explicit validated manifest selections instead of re-running an affected classifier", () => {
    const scope = ciJob("scope")
    expect(scope).toContain("full: ${{ steps.scope.outputs.full }}")
    expect(scope).toContain("base_sha: ${{ steps.scope.outputs.base_sha }}")
    expect(scope).toContain("head_sha: ${{ steps.scope.outputs.head_sha }}")
    expect(scope).toContain("plan_artifact_name: execution-plan-${{ github.run_id }}-${{ github.run_attempt }}")
    expect(scope).toContain("plan_hash: ${{ steps.scope.outputs.plan_hash }}")
    expect(ciWorkflow).not.toContain("--affected")
    expect(ciJob("static-checks")).toContain("CI_PROJECTION_NAME: static_tasks")
    expect(ciJob("test-windows")).toContain("CI_PROJECTION_NAME: windows_suites")
  })

  it("runs validated native task groups and the canonical unit entry", () => {
    const staticChecks = ciJob("static-checks")
    for (const group of ["static_tasks", "build_tasks", "knip_tasks"]) expect(staticChecks).toContain("--plan-group " + group)
    expect(staticChecks.match(/pnpm install --frozen-lockfile/g)).toHaveLength(1)
    const linux = ciJob("test-linux")
    expect(linux).toContain("node scripts/ci/run-unit-tests.mjs")
    expect(linux).toContain("--ci --receipt .ci/unit-execution.json")
    const windows = ciJob("test-windows")
    expect(windows).toContain("run: pnpm --filter @alook/daemon test")
    expect(windows).toContain('node scripts/ci/run-turbo.mjs run test "${filters[@]}"')
    expect(windows.match(/VITEST_MAX_WORKERS: 1/g)).toHaveLength(1)
  })

  it("isolates daemon process-authority tests in root workspace runs", () => {
    expect(daemonVitestConfig).toContain('name: "daemon-node"')
    expect(daemonVitestConfig).toContain("maxWorkers: 1")
    expect(daemonVitestConfig).toContain("sequence: { groupOrder: 2 }")
  })

  it("builds native unit prerequisites before serial process and packed phases", () => {
    const linux = ciJob("test-linux")
    const buildStart = linux.indexOf("- name: Build native unit prerequisites")
    expect(buildStart).toBeGreaterThan(-1)
    expect(linux).toContain("run: node scripts/ci/run-turbo.mjs --plan-group unit_build_tasks")
    for (const phase of ["Run selected unit files", "Run selected daemon real-process tests", "Run selected package artifact tests"]) {
      expect(linux.indexOf("- name: " + phase)).toBeGreaterThan(buildStart)
    }
  })

  it("runs each direct Worker Node and runtime project once through its standard test task", () => {
    const vitestPluginVersion = directWorkerModules[0]
      .packageJson.devDependencies["@cloudflare/vitest-plugin"]
    expect(vitestPluginVersion).toMatch(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/)

    const projectNames: string[] = []
    for (const module of directWorkerModules) {
      expect(module.packageJson.scripts.test).toBe("vitest run --config " + (module.name === "web" ? "vitest.workspace.config.ts" : "vitest.config.ts"))
      expect(module.packageJson.scripts["test:runtime"]).toContain("vitest.runtime.config.mts")
      expect(module.packageJson.scripts).not.toHaveProperty("test:workers")
      expect(module.packageJson.devDependencies["@cloudflare/vitest-plugin"])
        .toBe(vitestPluginVersion)
      const expectedProjects = 1
      expect(module.workspaceConfig.match(/vitest\.config\.ts/g)).toHaveLength(expectedProjects)
      if (module.name === "web") {
        expect(module.workspaceConfig).not.toContain("vitest.runtime.config.mts")
        expect(module.packageJson.scripts["test:runtime"]).toContain("vitest.runtime.config.mts")
      } else expect(module.workspaceConfig.match(/vitest\.runtime\.config\.mts/g)).toHaveLength(expectedProjects)
      if (module.name === "web") expect(module.workspaceConfig).toContain("./vitest.dom.config.ts")
      else expect(module.workspaceConfig).not.toContain("vitest.dom.config.ts")

      const nodeProject = `${module.name}-node`
      const runtimeProject = `${module.name}-runtime`
      expect(module.nodeConfig).toContain(`name: "${nodeProject}"`)
      expect(module.runtimeConfig).toContain(`name: "${runtimeProject}"`)
      expect(module.runtimeConfig).toContain("cloudflareTest({")
      expect(module.runtimeConfig).toContain('wrangler: { configPath: "./wrangler.toml" }')
      expect(module.wranglerConfig).not.toContain("service_binding_extra_handlers")
      projectNames.push(nodeProject, runtimeProject)
    }
    expect(new Set(projectNames).size).toBe(projectNames.length)
    expect(ciJob("test-linux")).toContain("node scripts/ci/run-unit-tests.mjs")
  })


  it("verifies the Blog artifact from the same producer before dry-run", () => {
    const blog = ciJob("blog-build")
    expect(blog).toContain("needs: [scope, ui-e2e-build]")
    expect(blog).toContain("e2e-build-artifact.mjs verify")
    expect(blog).toContain("verify:blog-dry-run")
    expect(blog.indexOf("e2e-build-artifact.mjs verify")).toBeLessThan(blog.indexOf("verify:blog-dry-run"))
    expect(blog).not.toMatch(/exec (?:tsc|eslint|vitest)\b|run build:blog|opennextjs-cloudflare build/)
  })

  it("collects Node and workerd projects in one Istanbul report", () => {
    expect(rootPackageJson.devDependencies.vitest).toBeTypeOf("string")
    expect(rootPackageJson.devDependencies["@vitest/coverage-istanbul"]).toBe(rootPackageJson.devDependencies.vitest)
    expect(rootPackageJson.devDependencies).not.toHaveProperty("@vitest/coverage-v8")
    expect(rootVitestConfig).toContain('provider: "istanbul"')
    expect(rootVitestConfig).toContain('"src/**/*.{ts,tsx,js,jsx}"')
    expect(rootVitestConfig).toContain('"**/test-runtime/**"')
    expect(rootVitestConfig).toContain('"**/test-harness.ts"')
    expect(rootVitestConfig).toContain('"**/react-dom-harness.ts"')
    expect(rootVitestConfig).toContain('"**/react-dom-setup.ts"')
    for (const project of [
      "src/shared",
      "src/web",
      "src/web/vitest.dom.config.ts",
      "src/web/auth/vitest.config.ts",
      "src/web/auth/vitest.runtime.config.mts",
      "src/daemon",
      "src/daemon/agent-driver",
      "src/email-worker",
      "src/ws-do",
      "src/queue-worker",
      "src/app",
      "tests/utils",
      "scripts/ci",
    ]) {
      expect(rootVitestConfig).toContain(`"${project}"`)
    }
    for (const [index, module] of directWorkerModules.entries()) {
      expect(rootVitestConfig).toContain(`"src/${module.name}"`)
      expect(
        rootVitestConfig.match(
          new RegExp(`src/${module.name}/vitest\\.runtime\\.config\\.mts`, "g"),
        ),
      ).toHaveLength(1)
      expect(module.runtimeConfig).toContain(`sequence: { groupOrder: ${index + 10} }`)
    }
    expect(directWorkerModules[3].runtimeConfig).toContain('main: "./custom-worker.ts"')
    expect(directWorkerModules[3].runtimeConfig).toContain(
      '"test-runtime/open-next-worker-stub.ts"',
    )
  })

  it("keeps a unit execution receipt and rejects invalid coverage before upload", () => {
    const linux = ciJob("test-linux")
    expect(linux).toContain("--ci --receipt .ci/unit-execution.json")
    expect(linux).toContain('args+=(--coverage)')
    expect(linux).toContain("if: always() && env.RUN_COVERAGE == 'true'")
    expect(linux).toContain("verify-coverage-plan.mjs")
    expect(linux).toContain("coverage/coverage-final.json")
    const upload = linux.match(/      - name: Upload unit execution evidence\n[\s\S]*?(?=\n      - name:|$)/)?.[0] || ""
    const reports = upload.match(/          path: \|\n((?:            [^\n]+\n)+)/)?.[1]
      ?.trim().split("\n").map(path => path.trim())
    expect(reports).toEqual([".ci/unit-execution.json", ".vitest-reports/unit.blob"])
    expect(upload).not.toMatch(/include-hidden-files:\s*true/i)
    expect(upload).toContain("if: always()")
    expect(upload).toContain("if-no-files-found: error")
  })

  it("keeps real-process and packed tests serial after the unit report", () => {
    const linux = ciJob("test-linux")
    expect(linux).toContain("timeout-minutes: 45")
    expect(linux).toContain("RUN_COVERAGE: ${{ needs.scope.outputs.execution_mode != 'main-smoke' }}")
    expect(linux.match(/codecov\/codecov-action/g)).toHaveLength(1)
    expect(linux).toContain("files: ./coverage/coverage-final.json")
    expect(linux).toContain("fail_ci_if_error: true")
    expect(linux).toContain("pnpm --filter @alook/daemon exec vitest run --no-file-parallelism")
    for (const path of ["src/cli/daemonLifecycle.real.test.ts", "src/cli/diagnosticsLifecycle.real.test.ts", "src/cli/daemonStop.test.ts"]) {
      expect(linux.slice(linux.indexOf("- name: Run selected daemon real-process tests"))).toContain(path)
    }
    expect(linux).toContain("pnpm --filter @alook/agent-driver exec vitest run --no-file-parallelism src/pack.test.ts")
    expect(linux).toContain("pnpm --filter @alook/daemon exec vitest run --no-file-parallelism src/version.packed.test.ts src/agent-driver-bundle.packed.test.ts src/cli/daemonSelfUpdate.real.test.ts")
    const phases = ["Run selected unit files", "Verify selected coverage", "Run selected daemon real-process tests", "Run selected package artifact tests", "Upload coverage"].map(phase => linux.indexOf("- name: " + phase))
    expect(phases.every((position, index) => position >= 0 && (!index || position > phases[index - 1]!))).toBe(true)
    expect(ciWorkflow).not.toMatch(/^  coverage:/m)
    expect(rootPackageJson.scripts).not.toHaveProperty("coverage:workers")
  })

  it("replaces platform mocks only after stronger workerd coverage exists", () => {
    const readRepo = (path: string) => readFileSync(
      resolve(import.meta.dirname, `../../${path}`),
      "utf8",
    )
    const wsRuntime = readRepo("src/ws-do/test-runtime/worker.runtime.test.ts")
    const webRuntime = readRepo("src/web/test-runtime/worker.runtime.test.ts")
    const emailNode = readRepo("src/email-worker/src/index.test.ts")
    const emailRuntime = readRepo("src/email-worker/test-runtime/worker.runtime.test.ts")
    const queueNode = readRepo("src/queue-worker/src/index.test.ts")
    const queueRuntime = readRepo("src/queue-worker/test-runtime/worker.runtime.test.ts")

    expect(existsSync(resolve(import.meta.dirname, "../../src/ws-do/src/rate-limit-do.test.ts"))).toBe(false)
    expect(wsRuntime).toContain("persists the counter across stubs for the same Durable Object id")
    expect(wsRuntime).toContain("resets expired storage and rejects invalid Durable Object requests")

    expect(existsSync(resolve(import.meta.dirname, "../../src/web/src/lib/worker-runtime.test.ts"))).toBe(false)
    expect(webRuntime).toContain("adds browser and CDN revalidation headers to public route %s")
    expect(webRuntime).toContain("forwards WebSocket upgrade %s through the configured service binding")

    expect(emailNode).not.toContain('describe("fetch() routing"')
    expect(emailNode).not.toContain('describe("IMAP management routes"')
    expect(emailRuntime).toContain("forwards status and sync routes to the real IMAP Durable Object")
    expect(emailRuntime).toContain("rejects unsupported methods, paths, and missing IMAP account ids")

    expect(queueNode).not.toContain("returns 400 on invalid JSON body")
    expect(queueNode).not.toContain("returns 405 for non-POST methods")
    expect(queueNode).not.toContain("returns 200 { status: ok } for GET /health")
    expect(queueRuntime).toContain("rejects invalid JSON and non-POST dev requests at the real entrypoint")
    expect(queueRuntime).toContain("loads production migrations and serves the production entrypoint")
  })
})

describe("Desktop window contract", () => {
  it("delegates external file drops to the webview attachment lifecycle", () => {
    const mainWindow = desktopConfig.app?.windows?.find((window) => window.label === "main")
    expect(mainWindow?.dragDropEnabled).toBe(false)
  })
})

describe("Desktop updater release", () => {
  it("keeps every build private until one publisher revalidates all four stages", () => {
    expect(autoTagReleaseWorkflow).toContain('--title "$TAG"')
    expect(desktopReleaseWorkflow.match(/contents: write/g)).toHaveLength(1)
    expect(desktopReleaseWorkflow).not.toContain("id-token: write")
    expect(desktopReleaseWorkflow).toContain("group: desktop-release-${{ github.ref }}")
    expect(desktopReleaseWorkflow).toContain("cancel-in-progress: false")
    expect(desktopReleaseWorkflow).toContain("needs: [build-unix, build-windows]")
    expect(desktopReleaseWorkflow).toMatch(/uses: actions\/upload-artifact@[a-f0-9]{40}(?:\s+#.*)?$/m)
    expect(desktopReleaseWorkflow).toMatch(/uses: actions\/download-artifact@[a-f0-9]{40}(?:\s+#.*)?$/m)
    expect(desktopReleaseWorkflow).toContain("pattern: desktop-release-*")
    expect(desktopReleaseWorkflow).toContain("merge-multiple: false")
    expect(desktopReleaseWorkflow).toContain("desktop-release-artifacts.mjs aggregate")
    expect(desktopReleaseWorkflow).toContain("desktop-release-artifacts.mjs verify-published")
    expect(desktopReleaseWorkflow).toContain("desktop-release-artifacts.mjs assert-publishable")
    expect(desktopReleaseWorkflow).toContain("for attempt in {1..30}")
    expect(desktopReleaseWorkflow).toContain('releases/tags/$TAG')
    expect(desktopReleaseWorkflow).toContain('git fetch --force --no-tags origin "refs/tags/$TAG:refs/tags/$TAG"')
    expect(desktopReleaseWorkflow).toContain('git rev-parse "$TAG^{commit}"')
    expect(desktopReleaseWorkflow).toContain('[[ "$tag_commit" == "$GITHUB_SHA" ]]')
    expect(desktopReleaseWorkflow).not.toContain("--clobber")
    expect(desktopReleaseArtifacts).toContain("Desktop release namespace is immutable and must start empty")
    expect(desktopReleaseArtifacts).toContain("unexpected desktop asset candidates")
    expect(desktopReleaseWorkflow).not.toContain("releaseId:")
    expect(desktopReleaseWorkflow).not.toContain("uploadUpdaterJson")
    expect(desktopReleaseWorkflow).not.toContain("tagName:")
    expect(desktopReleaseWorkflow).not.toContain("releaseName:")
    expect(desktopReleaseWorkflow).not.toContain("releaseBody:")
    expect(desktopReleaseWorkflow).not.toContain("releaseDraft:")
    expect(desktopReleaseWorkflow).not.toContain("prerelease:")
    const aggregate = desktopReleaseWorkflow.indexOf("desktop-release-artifacts.mjs aggregate")
    const releaseLookup = desktopReleaseWorkflow.indexOf("Resolve existing release after every verification gate")
    const binaryUpload = desktopReleaseWorkflow.indexOf("Upload verified binary and signature assets")
    const metadataUpload = desktopReleaseWorkflow.indexOf("Upload latest.json last")
    expect(aggregate).toBeLessThan(releaseLookup)
    expect(releaseLookup).toBeLessThan(binaryUpload)
    expect(binaryUpload).toBeLessThan(metadataUpload)
  })

  it("builds exact self-contained updater assets and one deterministic eleven-key latest.json", () => {
    expect(desktopConfig.bundle?.createUpdaterArtifacts).toBe(true)
    expect(desktopConfig.plugins?.updater?.endpoints).toEqual([
      "https://alook.ai/api/desktop/update/{{target}}/{{arch}}/{{current_version}}?bundle_type={{bundle_type}}",
    ])
    expect(desktopReleaseWorkflow).toContain("TAURI_SIGNING_PRIVATE_KEY:")
    expect(desktopReleaseWorkflow).not.toContain("v1Compatible")
    expect(desktopReleaseArtifacts).not.toContain(".nsis.zip")
    expect(desktopReleaseArtifacts).not.toContain(".msi.zip")
    for (const platform of [
      "darwin-aarch64",
      "darwin-aarch64-app",
      "darwin-x86_64",
      "darwin-x86_64-app",
      "linux-x86_64",
      "linux-x86_64-appimage",
      "linux-x86_64-deb",
      "linux-x86_64-rpm",
      "windows-x86_64",
      "windows-x86_64-msi",
      "windows-x86_64-nsis",
    ]) {
      expect(desktopReleaseArtifacts).toContain(`"${platform}"`)
    }
    expect(desktopUpdateRoute).toContain('"darwin-aarch64-app"')
    expect(desktopUpdateRoute).toContain('"linux-x86_64-appimage"')
    expect(desktopUpdateRoute).toContain('"linux-x86_64-deb"')
    expect(desktopUpdateRoute).toContain('"linux-x86_64-rpm"')
    expect(desktopUpdateRoute).toContain('"windows-x86_64-msi"')
    expect(desktopUpdateRoute).toContain('"windows-x86_64-nsis"')
  })

  it("uses an inline unsigned-build overlay without mutating tracked configuration", () => {
    expect(desktopBuildScript).toContain(
      `--config '{"bundle":{"createUpdaterArtifacts":false}}'`,
    )
    expect(desktopBuildScript).not.toContain("tauri.conf.json")
    expect(desktopBuildScript).not.toMatch(/\b(?:cp|mv|sed)\b/)
    expect(desktopBuildScript).not.toContain(".bak")
  })

  it("keeps local ad-hoc signing while release builds use Developer ID notarization", () => {
    expect(desktopMacConfig.bundle?.macOS?.signingIdentity).toBe("-")
    expect(desktopMacConfig.bundle?.macOS?.hardenedRuntime).toBe(true)
    expect(desktopMacConfig.bundle?.macOS?.entitlements).toBeUndefined()
    expect(existsSync(desktopEntitlementsPath)).toBe(false)
    expect(desktopReleaseWorkflow).toContain("APPLE_CERTIFICATE:")
    expect(desktopReleaseWorkflow).toContain("APPLE_CERTIFICATE_PASSWORD:")
    expect(desktopReleaseWorkflow).toContain("APPLE_SIGNING_IDENTITY:")
    expect(desktopReleaseWorkflow).toContain("APPLE_API_ISSUER:")
    expect(desktopReleaseWorkflow).toContain("APPLE_API_KEY_PATH:")
    expect(desktopReleaseWorkflow).toContain("Clean temporary macOS signing material")
    expect(desktopReleaseWorkflow).toContain("if: always() && runner.os == 'macOS'")
    const persistedMacCleanupPath = desktopReleaseWorkflow.indexOf('echo "ALOOK_MACOS_P12_PATH=$p12_path"')
    const firstMacSecretWrite = desktopReleaseWorkflow.indexOf("base64 -D > \"$p12_path\"")
    expect(persistedMacCleanupPath).toBeGreaterThan(-1)
    expect(persistedMacCleanupPath).toBeLessThan(firstMacSecretWrite)
    expect(desktopReleaseWorkflow).not.toContain("ALOOK_MACOS_KEYCHAIN_PASSWORD=")
    expect(desktopMacVerifier).toContain("codesign --verify --deep --strict")
    expect(desktopMacVerifier).toContain("flags=.*runtime")
    expect(desktopMacVerifier).toContain("xcrun stapler validate")
    expect(desktopMacVerifier).toContain("spctl --assess --type execute")
    expect(desktopMacVerifier).toContain("CFBundleShortVersionString")
    expect(desktopMacVerifier).toContain("com.apple.security.get-task-allow")
    expect(desktopMacVerifier).toContain("verify-minisign.mjs")
    expect(desktopReleaseWorkflow).toContain("EXPECTED_VERSION:")
    expect(desktopReleaseWorkflow).toContain("Developer ID signed")
    expect(desktopReleaseWorkflow).not.toContain("ad-hoc signed and are not notarized")
    expect(desktopReleaseWorkflow).not.toContain("Privacy & Security")
  })

  it("publishes Windows without Azure while retaining exact-byte updater verification", () => {
    expect(desktopReleaseWorkflow).not.toContain("AZURE_")
    expect(desktopReleaseWorkflow).not.toContain("ALOOK_ARTIFACT_SIGNING")
    expect(desktopReleaseWorkflow).not.toContain("azure/login@")
    expect(desktopReleaseWorkflow).not.toContain("tauri.windows.signing.conf.json")
    expect(desktopReleaseWorkflow).not.toContain("EXPECTED_PUBLISHER")
    expect(desktopReleaseWorkflow).toContain("args: --target x86_64-pc-windows-msvc")
    expect(desktopReleaseWorkflow).toContain("not Authenticode code-signed")
    expect(desktopReleaseWorkflow).not.toContain("Authenticode signed with SHA-256")
    expect(desktopWindowsVerifier).toContain("desktop-release-artifacts.mjs")
    expect(desktopWindowsVerifier).toContain("verify-minisign.mjs")
    expect(desktopWindowsVerifier).toContain('foreach ($installer in @($msi, $nsis))')
    expect(desktopWindowsVerifier).not.toContain("ExpectedPublisher")
    expect(desktopWindowsVerifier).not.toContain("Assert-Authenticode")
    expect(desktopWindowsVerifier).not.toContain("signtool.exe")
    for (const removed of [
      "scripts/ci/desktop-signing-dependencies.json",
      "scripts/ci/prepare-desktop-windows-signing.ps1",
      "scripts/ci/sign-desktop-windows.ps1",
      "src/desktop/src-tauri/tauri.windows.signing.conf.json",
    ]) {
      expect(existsSync(resolve(repositoryRoot, removed))).toBe(false)
    }
  })
})

describe("Desktop image clipboard", () => {
  const writeImagePermission = "clipboard-manager:allow-write-image"

  it("registers the maintained plugin only in the desktop dependency chain", () => {
    expect(desktopCargoManifest).toMatch(
      /\[target\."cfg\(not\(any\(target_os = \\"android\\", target_os = \\"ios\\"\)\)\)"\.dependencies\][\s\S]*tauri-plugin-clipboard-manager = "2"/,
    )
    expect(desktopRustEntry).toMatch(
      /#\[cfg\(desktop\)\]\s*\{[\s\S]*\.plugin\(tauri_plugin_clipboard_manager::init\(\)\)[\s\S]*run_desktop\(builder\);/,
    )
    expect(desktopRustEntry.match(/tauri_plugin_clipboard_manager::init/g)).toHaveLength(1)
  })

  it("authorizes configured app documents through one local image-write capability", () => {
    expect(desktopConfig.build).toMatchObject({
      devUrl: "http://localhost:3000/c",
      frontendDist: "alook-recovery://localhost/bootstrap",
    })
    expect(desktopCapability).toMatchObject({
      identifier: "desktop-capability",
      windows: ["main"],
      platforms: ["linux", "macOS", "windows"],
      local: true,
      remote: { urls: ["https://alook.ai"] },
      permissions: [writeImagePermission, "desktop-commands"],
    })
    expect(desktopDevConfig.app.security.capabilities).toEqual([
      "desktop-capability",
      "external-links",
      expect.objectContaining({
        identifier: "window-lifecycle-dev",
        local: true,
        windows: ["main"],
        platforms: ["android", "iOS"],
        remote: { urls: ["http://localhost:3000"] },
        permissions: ["core:event:allow-listen", "core:event:allow-unlisten"],
      }),
      expect.objectContaining({ identifier: "native-oauth-dev", local: true, remote: { urls: ["http://localhost:3000"] }, permissions: ["native-oauth"] }),
      expect.objectContaining({
        identifier: "mobile-share-image-dev",
        local: true,
        platforms: ["android", "iOS"],
        remote: { urls: ["http://localhost:3000"] },
        permissions: ["allow-mobile-share-image-copy", "allow-mobile-share-image-save"],
      }),
      expect.objectContaining({
        identifier: "mobile-system-notification-dev",
        local: true,
        platforms: ["android", "iOS"],
        remote: { urls: ["http://localhost:3000"] },
        permissions: ["mobile-system-notification"],
      }),
      expect.objectContaining({
        identifier: "native-back-dev",
        local: true,
        windows: ["main"],
        platforms: ["android"],
        remote: { urls: ["http://localhost:3000"] },
        permissions: ["core:app:allow-register-listener", "core:app:allow-remove-listener"],
      }),
      "file-save",
      expect.objectContaining({
        identifier: "file-save-dev",
        local: true,
        windows: ["main"],
        remote: { urls: ["http://localhost:3000"] },
        permissions: ["allow-file-save-begin", "allow-file-save-write-chunk", "allow-file-save-commit", "allow-file-save-cancel"],
      }),
    ])
  })
})

describe("Mobile release availability", () => {
  it("publishes --mobile bumps to TestFlight and keeps manual uploads opt-in", () => {
    expect(existsSync(mobileReleaseWorkflowPath)).toBe(true)
    expect(desktopIosConfig.identifier).toBe("ai.alook.ios")
    expect(iosProject).toContain("PRODUCT_BUNDLE_IDENTIFIER: ai.alook.ios")
    expect(iosProject).not.toContain("PRODUCT_BUNDLE_IDENTIFIER: ai.alook.desktop")
    expect(iosProject).toContain("CODE_SIGN_STYLE: Manual")
    expect(iosProject).toContain("CODE_SIGN_IDENTITY: Apple Distribution")
    expect(iosProject).toContain("PROVISIONING_PROFILE_SPECIFIER: Alook iOS App Store Connect")
    expect(iosProject).toContain("iOS: 15.0")
    expect(iosProject).toContain("ITSAppUsesNonExemptEncryption: false")
    expect(iosProject).not.toContain("iOS: 14.0")
    expect(iosPodfile).toContain("platform :ios, '15.0'")
    expect(iosPodfile).not.toContain("platform :ios, '14.0'")
    expect(iosProject).not.toContain("${FORCE_COLOR}")
    expect(iosExportOptions).toContain("<string>app-store-connect</string>")
    expect(iosExportOptions).toContain("<string>manual</string>")
    expect(iosExportOptions).toContain("<key>ai.alook.ios</key>")
    expect(iosExportOptions).toContain("<string>Alook iOS App Store Connect</string>")
    expect(mobileReleaseWorkflow).toMatch(/^  workflow_dispatch:/m)
    expect(mobileReleaseWorkflow).toMatch(/^  push:/m)
    expect(mobileReleaseWorkflow).toContain('branches: [main]')
    expect(mobileReleaseWorkflow).toContain('src/desktop/.deploy-version-mobile')
    expect(mobileReleaseWorkflow).not.toMatch(/^  pull_request:/m)
    expect(mobileReleaseWorkflow).toContain("default: false")
    expect(mobileReleaseWorkflow).toContain("github.event_name == 'push' || inputs.upload == true")
    expect(mobileReleaseWorkflow).toContain("Verify automatic TestFlight release version")
    expect(mobileReleaseWorkflow).toContain('requested_version=$(tr -d')
    expect(mobileReleaseWorkflow).toContain("APPLE_DEVELOPMENT_TEAM:")
    expect(mobileReleaseWorkflow).toContain("IOS_CERTIFICATE:")
    expect(mobileReleaseWorkflow).toContain("IOS_CERTIFICATE_PASSWORD:")
    expect(mobileReleaseWorkflow).toContain("IOS_MOBILE_PROVISION:")
    expect(mobileReleaseWorkflow).toContain("pnpm tauri ios init --ci --skip-targets-install")
    expect(mobileReleaseWorkflow).toContain('security import "$certificate_path"')
    expect(mobileReleaseWorkflow).toContain('install -m 600 "$profile_source"')
    expect(mobileReleaseWorkflow).toContain("unset IOS_CERTIFICATE IOS_CERTIFICATE_PASSWORD")
    expect(mobileReleaseWorkflow).toContain("pnpm tauri ios build")
    expect(mobileReleaseWorkflow).toContain("--export-method app-store-connect")
    expect(mobileReleaseWorkflow).toContain('bundleVersion\\\":\\\"${GITHUB_RUN_NUMBER}')
    expect(mobileReleaseWorkflow).toContain("CFBundleShortVersionString")
    expect(mobileReleaseWorkflow).toContain("CFBundleVersion")
    expect(mobileReleaseWorkflow).toContain('info["CFBundleURLTypes"] ==')
    expect(mobileReleaseWorkflow).toContain("codesign -d --entitlements :-")
    expect(mobileReleaseWorkflow).toContain('entitlements["application-identifier"]')
    expect(mobileReleaseWorkflow).toContain("5RF24VHDQB.ai.alook.ios")
    expect(mobileReleaseWorkflow).toContain(
      'entitlements["com.apple.developer.team-identifier"]',
    )
    expect(mobileReleaseWorkflow).toContain(
      'entitlements["com.apple.developer.associated-domains"]',
    )
    expect(mobileReleaseWorkflow).toContain("applinks:auth.alook.ai")
    expect(mobileReleaseWorkflow).toContain(
      'entitlements["aps-environment"] == "production"',
    )
    expect(mobileReleaseWorkflow).toContain("xcrun altool --upload-app")
    expect(mobileReleaseWorkflow).toMatch(/uses: actions\/upload-artifact@[a-f0-9]{40}(?:\s+#.*)?$/m)
    expect(bumpScript).toContain('args.includes("--mobile")')
    expect(bumpScript).toContain("src/desktop/.deploy-version-mobile")
    expect(bumpScript).toContain("automatic TestFlight upload")
    expect(bumpScript).toContain("iOS CFBundleShortVersionString")
  })

  it("restores Firebase client configuration after Android init and before compiling", () => {
    const init = mobileReleaseWorkflow.indexOf("pnpm tauri android init")
    const restore = mobileReleaseWorkflow.indexOf("./scripts/ci/prepare-android-firebase.mjs")
    const build = mobileReleaseWorkflow.indexOf("pnpm tauri android build")
    expect(mobileReleaseWorkflow).toContain("ANDROID_GOOGLE_SERVICES_JSON: ${{ secrets.ANDROID_GOOGLE_SERVICES_JSON }}")
    expect(restore).toBeGreaterThan(init)
    expect(build).toBeGreaterThan(restore)
  })

  it("keeps signed Android APK downloads on --mobile GitHub releases", () => {
    expect(desktopAndroidConfig.identifier).toBe("ai.alook.android")
    expect(androidGradle).toContain('namespace = "ai.alook.android"')
    expect(androidGradle).toContain('applicationId = "ai.alook.android"')
    expect(androidGradle).toContain('signingConfig = signingConfigs.getByName("release")')
    expect(androidMainActivity).toContain("package ai.alook.android")
    expect(mobileReleaseWorkflow).toContain("build-android:")
    expect(mobileReleaseWorkflow).toContain(
      "if: github.event_name == 'push' || inputs.android == true",
    )
    expect(mobileReleaseWorkflow).toContain(
      'yes | "$sdkmanager" --licenses >/dev/null || [[ ${PIPESTATUS[1]} -eq 0 ]]',
    )
    expect(mobileReleaseWorkflow).toContain('test -x "$ndk_home/ndk-build"')
    expect(mobileReleaseWorkflow).toContain("ANDROID_KEYSTORE:")
    expect(mobileReleaseWorkflow).toContain("ANDROID_KEYSTORE_PASSWORD:")
    expect(mobileReleaseWorkflow).toContain("ANDROID_KEY_ALIAS:")
    expect(mobileReleaseWorkflow).toContain("ANDROID_KEY_PASSWORD:")
    expect(mobileReleaseWorkflow).toContain("aarch64-linux-android,armv7-linux-androideabi")
    expect(mobileReleaseWorkflow).toContain('sdk_selection="$(node scripts/ci/android-toolchain.mjs)"')
    expect(mobileReleaseWorkflow).toContain('"$sdkmanager" "${sdk_components[@]}"')
    expect(mobileReleaseWorkflow).toContain('ndk_home="$ANDROID_HOME/ndk/${sdk_components[2]#ndk;}"')
    expect(mobileReleaseWorkflow).toContain("pnpm tauri android init --ci --skip-targets-install")
    expect(mobileReleaseWorkflow).toContain("pnpm tauri android build")
    expect(mobileReleaseWorkflow).toContain("--target aarch64 armv7")
    expect(mobileReleaseWorkflow).toContain("package: name='ai.alook.android'")
    expect(mobileReleaseWorkflow).toContain("apksigner verify --verbose --print-certs")
    expect(mobileReleaseWorkflow).toContain('aapt dump xmltree "$apk_source" AndroidManifest.xml')
    expect(mobileReleaseWorkflow).toContain("android:autoVerify")
    expect(mobileReleaseWorkflow).toContain('(\"host\", \"auth.alook.ai\")')
    expect(mobileReleaseWorkflow).toContain('(\"path\", \"/auth/native/return\")')
    expect(mobileReleaseWorkflow).toContain('(\"scheme\", \"ai.alook\")')
    expect(mobileReleaseWorkflow).toContain('(\"path\", \"/native/return\")')
    expect(mobileReleaseWorkflow).toContain("gh release upload")
    expect(mobileReleaseWorkflow).toContain("Alook_${EXPECTED_VERSION}_android.apk")
    expect(mobileReleaseWorkflow).toContain('gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json body')
    expect(mobileReleaseWorkflow).toContain('cat >> "$notes_file" <<EOF')
    expect(mobileReleaseWorkflow).toContain('<!-- alook-android-download -->')
    expect(mobileReleaseWorkflow).toContain("## Android")
    expect(mobileReleaseWorkflow).toContain("[Download signed APK](${base}/${APK_NAME})")
    expect(mobileReleaseWorkflow).toContain('gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --notes-file "$notes_file"')
  })
})

describe("Native OAuth association contract", () => {
  it("keeps the return domain, mobile identities, and standalone Worker route aligned", () => {
    expect(nativeOauthContract).toContain(
      'NATIVE_OAUTH_RETURN_ORIGIN = "https://auth.alook.ai"',
    )
    expect(nativeOauthContract).toContain(
      'NATIVE_OAUTH_RETURN_PATH = "/auth/native/return"',
    )
    expect(nativeOauthAuthWorker).toContain('AUTH_WORKER_HOST = "auth.alook.ai"')
    expect(nativeOauthAuthWorker).toContain('AUTH_WORKER_RETURN_PATH = "/auth/native/return"')
    expect(nativeOauthAuthConfig).toContain('name = "alook-auth"')
    expect(nativeOauthAuthConfig).toMatch(
      /\[\[routes\]\][\s\S]*pattern = "auth\.alook\.ai"[\s\S]*custom_domain = true/,
    )
    expect(nativeOauthWebConfig).not.toContain("auth.alook.ai")
    expect(nativeOauthWebRuntime).not.toContain("auth.alook.ai")

    expect(desktopIosConfig.identifier).toBe("ai.alook.ios")
    expect(iosProject).toContain("DEVELOPMENT_TEAM: 5RF24VHDQB")
    expect(nativeOauthAuthWorker).toContain("5RF24VHDQB.ai.alook.ios")
    expect(nativeOauthAuthWorker).toContain('"/": AUTH_WORKER_RETURN_PATH')

    expect(desktopAndroidConfig.identifier).toBe("ai.alook.android")
    expect(nativeOauthAuthWorker).toContain('package_name: "ai.alook.android"')
    expect(nativeOauthAuthWorker).toContain(
      "9D:C6:ED:E9:4B:A6:63:EE:C9:EC:98:FF:7B:AF:D5:5E:24:8B:6C:4B:C2:15:7F:CF:04:2D:F5:9B:0E:41:08:06",
    )
  })

  it("restores the main Web association behavior and excludes the auth host from OpenNext", () => {
    expect(nativeOauthMainAasaRoute).toContain('appIDs: ["TEAM_ID.ai.alook.app"]')
    expect(nativeOauthMainAasaRoute).toContain('paths: ["*"]')
    expect(nativeOauthMainAssetLinksRoute).toContain('package_name: "ai.alook.app"')
    expect(nativeOauthMainAssetLinksRoute).toContain('sha256_cert_fingerprints: ["__PLACEHOLDER__"]')
    expect(nativeOauthWebConfig).not.toContain('pattern = "auth.alook.ai"')
    expect(nativeOauthWebRuntime).not.toContain("NATIVE_OAUTH")
  })

  it("keeps the auth Worker telemetry-free, binding-free, and in its own CI dry-run", () => {
    expect(nativeOauthAuthConfig).toMatch(/\[observability\]\nenabled = false\nhead_sampling_rate = 0/)
    expect(nativeOauthAuthConfig).toMatch(/\[observability\.logs\]\nenabled = false\ninvocation_logs = false/)
    expect(nativeOauthAuthConfig).toMatch(/\[observability\.traces\]\nenabled = false\nhead_sampling_rate = 0/)
    expect(nativeOauthAuthConfig).not.toMatch(/\[(?:assets|vars|d1_databases|r2_buckets|kv_namespaces|services|queues|durable_objects)/)
    expect(nativeOauthAuthWorker).not.toMatch(/(?:console\.|@opennextjs|next\/server|cloudflare:workers)/)

    const authBuild = ciJob("auth-build")
    expect(authBuild).toContain("if: needs.scope.outputs.run_auth_build == 'true'")
    expect(authBuild).toContain("CI_PROJECTION_NAME: run_auth_build")
    expect(authBuild).toContain("pnpm --filter @alook/web build:auth")
    expect(authBuild).not.toContain("deploy:auth")
    expect(directWorkerModules[3].packageJson.scripts["build:auth"])
      .toContain("wrangler deploy --dry-run --config auth/wrangler.toml")
    expect(directWorkerModules[3].packageJson.scripts["build:auth"])
      .toContain("--outdir dist")
    expect(directWorkerModules[3].packageJson.scripts["build:auth"])
      .not.toContain("--outdir auth/dist")
    expect(directWorkerModules[3].packageJson.scripts["test:auth"]).toContain("auth/vitest.config.ts")
    expect(directWorkerModules[3].packageJson.scripts["test:auth:runtime"]).toContain("auth/vitest.runtime.config.mts")
  })
})