openclaw/test/scripts/source-file-scan-cache.test.ts
Peter Steinberger c2680f16f3
test(ui,gateway,scripts,cron): remove low-value tests (batch d468) (#182588)
* test(ui): remove redundant q0178 e2e layers

Port q0178 commits e8ece787a126 and 82f207be9dfe onto the campaign lane. The first commit is already present as 0ddc2945d0b8; preserve that cleanup and apply the remaining test deletions and consolidations.

Resolve CI timing and ownership inventory conflicts by keeping the lane removals of browser-talk-microphone-lifetime and browser-talk-ordering. All scoped test files match the shard final state; no lane-added cases or assertions differ from the shard parent.

CI-only validation: oxlint, oxfmt --check, and working-tree/index git diff --check exit 0. Independent review found no actionable issues. Tests, coverage, Testbox, and check-changed were not run.

* test(gateway): deslop q0191 tests

Remove the materialization spy layer from destination-authority: the retained destination preparation scenario checks the persisted required-profile error, reconciling placement, unchanged clone inventory, and absence of a bound worktree. Reuse the placement owner and provider connection fixture in inference-authority.

Keep every authority and lifecycle scenario: clone-lease policy changes, accepted-result teardown, transaction/commit admission, failed-placement recovery, and inference claim/run revocation before and after credential exchange. These distinct boundaries prevent an honest 40% reduction.

CI-only validation: oxfmt, git diff --check, and plain oxlint passed. No tests or coverage run; hosted CI owns runtime proof.

* test(gateway): remove duplicate q0191 e2e layers

Delete inference-authority.e2e.test.ts: credential exchange and non-installation after revocation stay in simple-completion-runtime.generation.test.ts (keeps required-worker authority live through each phase). Real plugin HTTP authentication stays in simple-completion-runtime.plugin-scope.test.ts. Admitted model reuse and closed-owner rejection stay in inference-runtime.test.ts; persisted claim and delegated lifetime checks stay in placement-turn-authority.test.ts. These retain the contracts introduced in c18456cce9.

Drop repeated accepted-result destination variants: placement-dispatch-move-recovery.test.ts retains Stop settlement with attached/destroyed sources, accepted-checkpoint preservation, and torn-down destination policy checks at transaction/commit. Retain the real late-policy-during-destruction case, clone-lease authority change, and failed-placement transaction/commit cases. Repository restoration stays covered by session-repository-materialization.test.ts. Trim setup-only metadata assertions and the unused allocation marker.

Original shard: 1133 lines; final: 677 (40.2% reduction). No config lists reference the deleted file. CI-only: oxfmt, plain oxlint, and git diff --check passed; no tests, builds, or coverage were run.

* test(ui): deslop q0193 tests

Remove duplicated Workboard page recovery and locale scenarios; their full contracts remain in workboard-lazy-page.e2e.test.ts and workboard-locale.e2e.test.ts.

Session search and history remain in session-transcript-search.e2e.test.ts (searches once on submit, shows provenance, and opens the matching chat); roster filtering remains in session-management.archive.e2e.test.ts (never deletes a hidden thread selected before changing the roster search).

Child failure retention, stable alert identity, and explicit retry remain in app-sidebar.sessions.test.ts via app-sidebar-cases/child-session-errors.ts and app-sidebar.child-snapshot-freshness.test.ts (retains a queued child refresh failure until explicit retry).

Keep bottom/right/main terminal destination gating; remove optional screenshot scaffolding and repeat theme/docking playback. Main-to-right persistence remains in terminal-panel.test.ts; light/dark startup remains in theme-boot.e2e.test.ts. Shrink only deleted-file routing entries.

CI-only validation: plain oxlint, oxfmt, and git diff --check passed. No tests, coverage, builds, or Testbox commands run. Shard test LOC 1012 -> 607; declarations 12 -> 8; statically expanded cases 16 -> 10.

* test(scripts): deslop q0192 tests

Consolidate docs heading exclusions and XCTest expected-result construction. Keep all cases and distinct failure paths; route the release run-id success case through its required-id boundary. Remove unused release fixture prose and inline its single-use workflow fixture.

* test(scripts): consolidate q0192 fixtures and branch cases

Remove the OpenShell build-source assertion and command argument inventories; retain checksum pinning, failure ordering, installed bytes, and cleanup. Build behavior remains owned by prepare-vitest-runtime and build-all tests.

Replace the XCTest method inventory with synthetic identities and keep one representative per rejection branch. Retain log truncation in the JSONL lifecycle case, inaccessible command lines in the process-tree scan, and Windows routes in the docs-map scenario. Compact dreaming row fixtures and gateway error expectations without changing their cases.

* test(scripts): drop duplicate q0192 missing-result checks

The ios-screenshot-evidence test "requires all four native test results even when the summary passed" already exercises requireExactTestResults through collectIosScreenshotEvidence and covers the result-count rejection. Keep duplicate identities, malformed root objects, and malformed node objects in the parser suite.

* test(scripts): deslop q0190 tests

Remove the copied SQLite scenario/row inventory while retaining all 12 benchmark executions and query-plan, schema and timing checks. Reuse the query-plan type.

Consolidate UTF-8 tail proof into the existing formatDocs failure case; format-generated-module.test.ts also retains the shared output-tail boundary. Keep the exact multibyte truncation assertion without a redundant Node subprocess.

* test(scripts): consolidate q0190 owner-boundary proof

Replace task-by-mode config replays with branch representatives for direct/code, node/QuickJS, empty/populated tools and the real fanout patch. Keep allowedTools distinct from requiredTools.

Ratchet file loading remains covered by the large Git snapshot case; count increases/decreases remain covered by check-assertion-safety-ratchet.test.ts (blocks new debt and prunes reduced counts), with path loading covered by check-max-lines-ratchet.test.ts. Keep parser comments, malformed input, framing, and sort proof here.

Build argument rejection remains in build-all.test.ts (parses build-all CLI args before any build work); retain the real inherited-owner failed-build flow. Installer support wording remains in install-sh.test.ts (offers support in human footer and errors) and install-cli.test.ts. Remove copied benchmark metadata without removing its runtime smoke or plan checks.

* test(scripts): trim q0190 duplicate fixture layers

Keep the real failed-build child and inherited artifact claim, but hold parent ownership in the existing test harness instead of another embedded Node launcher. Propagate command errors inside ownership before releasing.

Retain one policy symlink escape case for the shared readSource realpath branch instead of replaying installer-file and parent-directory variants. Keep trusted assembly cleanup and standalone execution checks.

Check Podman error categories rather than copied full diagnostics; retain every invalid-config path, original bytes, permissions, and fallback-call assertions.

* test(ui): remove redundant q0182 e2e layers

Keep face selection and closure in dashboard-presentation-defaults.test.ts, chat-page-retained-sessions.test.ts, and chat-page-close-route.test.ts. Keep hydration ordering and hidden work in chat-pane-connection-lifecycle.test.ts, chat-pane-session-hydration.test.ts, and chat-branch-freshness.test.ts.

Keep presence deduplication in viewer-facepile.test.ts and chat-pane-header.test.tsx, and durable membership in chat-details-people.test.tsx and chat-details-session.test.ts. Keep expired outbox retention in chat-incognito-expired.test.ts and shared copy/discard behavior in chat-view.test.ts and chat-message.test.tsx. Keep usage failure/recovery in model-providers-page.usage.test.ts.

Retain the Incognito action and auth-alert browser flows and the actual Chromium credentialed manifest fetch. Remove only stale routing/timing entries. Static checks only; hosted CI owns test execution.

* test(cron): deslop q0194 tests

Remove the alert policy replay: service.failure-alert.test.ts retains incident threshold, cooldown and opt-out coverage; server-cron-notifications.test.ts retains dispatch and transport contracts. The remaining delivery E2E cases retain real HTTP and alert-state persistence.

Remove duplicate timeout and execution-denial diagnostic scenarios. isolated-agent/run.meta-error-status.test.ts retains the nested-lane timeout; isolated-agent.helpers.test.ts retains typed fatal denial; run-diagnostics.test.ts retains failure-signal extraction. Remaining diagnostics E2E cases retain event/history propagation, and the delivery E2E retains the authoritative watchdog timeout.

Reuse cronTestInput without changing fixture defaults. Preserve the distinct two-service reload and real child-process retirement scenarios. CI-only: oxfmt, plain oxlint and git diff --check passed; tests and coverage intentionally not run. Reduction: 1128 to 1010 lines, below 40% to preserve distinct behavior.

* test(cron): remove duplicate q0194 e2e layers

Remove the fallback-owner and skipped-alert replays. Keepers: service.failure-alert-notifications.test.ts routes rejected alerts through real session admission; service.failure-alert.test.ts covers skipped routing; service/failure-alerts.persistence.test.ts covers durable skipped-alert state; gateway/server-cron-notifications.test.ts covers admission refusal, webhook settlement and message encoding. The retained providerless/watchdog E2E still crosses real HTTP.

Remove the local-provider preflight replay and its unused endpoint fixture. Keepers: isolated-agent/model-preflight.runtime.test.ts covers unavailable endpoints and diagnostics; isolated-agent.model-preflight.test.ts covers skip versus fallback; service.failure-alert.test.ts covers blocked-local-provider outcomes. Remaining diagnostics E2E cases preserve event/history propagation.

Delete session-reaper.worker-placement.e2e.test.ts. Keepers: service.remove-session-cleanup.test.ts covers delayed active-run cleanup and replacement fencing; gateway/server.sessions.automation-worker-placement.test.ts covers idle and active run-alias reclamation; gateway/server-worker-placement-cancel.test.ts covers killed terminal persistence before reclaim; agents/cli-runner.spawn.test.ts covers managed CLI cancellation; isolated-agent/run.fast-mode.test.ts covers delete-after-run session cleanup; service/run-recovery.test.ts and gateway/server-cron.drain.test.ts cover one-shot deletion, retained history and binding removal. No path-list references remain.

Original shard: 1128 lines. Final: 564 lines (-50%). No production or shared support changes. CI-only: oxfmt, plain oxlint and git diff --check passed; no tests, builds or coverage commands run.

* test(ui): deslop q0196 tests

Keep the current Chrome explicit-inspection and disabled-profile scenario; the legacy bridge action is covered by pages/apps/chrome-setup.test.tsx (offers only advertised Mac actions or the released legacy install) and app/native-device-settings.test.ts.

Keep one authored Mermaid alternatives E2E and share its metadata assertion. Theme isolation remains in components/markdown-mermaid.runtime.browser.test.ts (keeps concurrent diagram themes independent in the warm renderer); expansion gestures remain in e2e/chat-mermaid-expand.e2e.test.ts. Remove unasserted screenshot captures.

Compact build identity assertions without removing Unicode, pointer-lifecycle, or reload checks. Drop the sidebar storage-shape assertion while retaining reload persistence proof. CI-only: oxfmt, diff-check and plain oxlint passed; no tests or coverage run. Retain distinct reconnect, model recovery, and sidebar group-order paths rather than force the 40 percent line target.

* test(ui): remove redundant q0196 e2e layers

Delete sidebar-plugin-order: sidebar-customization covers plugin pinning and move-up, sidebar-rail covers native drag and keyboard/context-menu ordering without session writes, and session-management.groups covers header drag ordering and reload persistence. Remove only its owner-watch and timing entries.

Keep the unique named-preview and shared-description Mermaid contract. Real-renderer metadata stays covered by markdown-mermaid.runtime.browser.test.ts (keeps untrusted alternatives inert and retires metadata when the source changes); expanded metadata by markdown-mermaid.test.ts (keeps escaped metadata as text and replaces expanded alternatives with their image); gesture/focus behavior by chat-mermaid-expand.e2e.test.ts.

Preserve the #148843 agent-switch rejection/retry/external-refresh regression. Its no-switch replay is covered by model-providers-page.actions.test.ts and model-providers-page.test.ts rejection cases. Structured patch serialization remains covered by config-mutation.test.ts and model-providers-page.test.ts; remove repeated request bookkeeping and reuse the config fixture. Inline the single-use build flow and remove overwritten Chrome fixture fields.

CI-only: plain oxlint, oxfmt and diff-check passed; no test or coverage runs. Combined q0196 test LOC: 668 to 397 (40.6 percent reduction).

* test(scripts): deslop q0195 tests

Exercise erasable syntax, ignored generated trees, ordered parser errors and runtime dependency diagnostics through one CLI fixture instead of replaying the parser through a separate subprocess API.

Shipped-name removal remains covered by test/scripts/plugin-sdk-shipped-surface.test.ts. Simulator command execution and selection remain covered by test/scripts/ios-lifecycle-workflow.test.ts and admission by test/scripts/ci-workflow-complete.test.ts; retain generic logging and failure-artifact guards here.

CI-only validation: targeted plain oxlint, oxfmt and git diff --check passed. No tests or coverage runs. Shard LOC 1006 -> 931; retains unique release, redaction, package and lifecycle contracts rather than meeting the 40 percent target by dropping them.

* test(scripts): remove redundant q0195 tooling layers

Remove the npm-install replay: check-openclaw-package-tarball.test.ts covers missing UI and omitted inventory entries; postinstall-bundled-plugins.test.ts covers authoritative-inventory preservation and pruning.

Remove the compiler-command lifetime replay: managed-child-process.test.ts verifies stopped groups including live sibling threads, and managed-child-process.drain.test.ts joins groups and child close after leader exit. Keep real SDK collection and approval exposure guards.

Keep env scanning and per-section caps here; inventory-report-cli.test.ts owns argument errors and unlimited output, and test-skip-inventory.test.ts owns first-seen grouping. Keep one erasability fixture per traversal/parser branch and one Android class/closed-transport representative. Monthly/year-boundary arithmetic remains in openclaw-npm-extended-stable-release.test.ts; retain the parent live-main pre-publication boundary here.

CI-only: plain oxlint, oxfmt, and diff check pass; no test or coverage runs. Original shard 1006 lines -> 681 (32.3 percent reduction). Further cuts were not justified for the remaining independent lifecycle, transport, and publication contracts.

* test(e2e): deslop q0199 tests

Share launcher invocation and output assertions across the existing four provenance and lifecycle cases. Inline the single-use session-end plugin fixture and reuse automatic temporary-directory cleanup. Preserve cold abort and real SQLite contention interleavings unchanged.

* test(e2e): remove redundant q0199 proof layers

Remove the opt-in nine-transaction Doctor replay. Its 25ms contention retry is covered by openclaw-state-lease-heartbeat.diagnostics.test.ts (still retries SQLite contention); real contention and past-expiry ownership are covered by openclaw-state-lease-heartbeat.test.ts, with Doctor settlement covered by state-migrations.plugin-doctor.test.ts.

Use the existing minimal OpenAI Responses fixture for cold cancellation. Keep the same held response, first chat RPC, cancellation wire outcomes and exact request count. Reduce launcher cases to checkout provenance and pending-lifecycle success/failure, using mismatched source/build metadata throughout. Drop session-create setup shape assertions owned by server.sessions.create.dispatch.test.ts; retain the real reset hook and SIGTERM completion proof.

* test(scripts): deslop q0197 tests

Remove the duplicated model configuration layer from the agent-turn suite. cross-os-release-model-config.test.ts retains the same four provider/adapter paths and fail-fast ordering regression through runModelsSet and runInstalledModelsSet.

Share quota-wait setup while retaining exhausted and positive-but-insufficient cases, including exact-threshold readiness. Preserve distinct signing, isolation, compiler, installer and timeout contracts in the remaining shard files.

CI-only campaign: local oxfmt, oxlint and diff checks passed; runtime tests and coverage deferred to hosted CI.

* test(scripts): collapse repeated q0197 branches

Exercise release agent turns at runReleaseAgentTurn rather than replaying transport wiring. cross-os-release-model-config.test.ts retains both adapters' command, environment, cwd and timeout contracts.

Keep one installer predecessor-selection success and one below-reserve quota wait. These inputs exercise array-index selection and the same quota comparison, not release-format parsing or separate exhaustion branches.

Keep the stricter side-parent unsigned-commit case. pr-baseline-signing.test.ts, 'recovers and republishes the same signed candidate', retains the interrupted restoration and completed-continuation replay removed from the incoming-authority scenario.

CI-only: oxfmt, plain oxlint and diff checks passed. No tests or coverage run. Total shard reduction is 1083 to 875 lines; remaining unique isolation, compiler, signing and process-lifecycle contracts prevent the requested 40 percent cut.

* test(scripts): consolidate q0197 owner-boundary proof

Remove the supplementary catalog subprocess replay. The owner regression in src/plugins/provider-live-catalog-cache.test.ts, added by 1780bb4faf, proves close-time eviction and in-flight non-repopulation; DeepInfra catalog/proxy behavior remains in the extension suites.

Retain diagnostics redaction and deadline ordering, while dropping wrapper trailer replays covered by run-vitest-bounded.test.ts (joins fresh children and preserves cancel), vitest-worker-shutdown.test.ts (direct SIGTERM), and run-vitest-progress.test.ts (real no-output termination). Timer normalization remains in packages/normalization-core/src/number-coercion.test.ts.

Merge baseline publication cases into pr-baseline-incoming.test.ts without moving Vitest projects. Share direct/external-signing flow assertions, retain all publication authority faults, reduce installer inputs to distinct selector branches, and use smaller filesystem and command-log fixtures. Production and shared helpers are unchanged.

CI-only validation: plain oxlint, oxfmt and git diff --check passed. No tests or coverage executed. Original shard 1083 lines; final 646 lines (40.35 percent reduction).

* test(ui): deslop q0198 tests

Reuse presentation assertions and locators without dropping distinct browser regressions. Remove the duplicate Inbox frame probe between identical loaded states; retain navigation, reconnect, and pending-refresh probes.

CI-only: plain oxlint, oxfmt, and diff checks passed; runtime proof deferred to hosted CI. Shard lines: 724 to 696. All 7 declarations / 9 expanded cases retained; no safe whole-scenario deletion found.

* test(scripts): deslop q0200 tests

Factor repeated CPU-profile nodes and interval expectations without dropping attribution, clipping, selector, or error assertions. Share the old-release poison script fixture.

Remove direct malformed-SHA replays: write-build-info's retained 'preserves GIT_COMMIT then GIT_SHA explicit input precedence' case reaches the same normalizeBuildCommit rejection through resolveBuildInfo. Keep the remaining release, parser, concurrency, and lifecycle boundaries. CI-only validation: plain oxlint, oxfmt, and diff check; runtime proof deferred to hosted CI.

* test(scripts): remove redundant q0200 proof layers

Replace the per-child workflow source inventory with one frozen-target/trusted-ref invariant; retain executable extended-stable ref validation. Child dispatch execution remains in package-acceptance-workflow.test.ts (adopts and validates the exact run; dispatches CI scope).

Keep database CLI partitioning/forwarding while leaving weighted placement to postgres-conformance-shards.test.ts. Remove duplicate wrapper selection variants and sample-summary replay (control-ui-cold-load-trace.test.ts owns sample weighting). Factor manifest variants and websocket cleanup; preserve distinct error and lifecycle paths.

CI-only: oxfmt, diff check, and plain oxlint passed. No tests or coverage run. The 40 percent line target remains unmet; no production or helper files changed.

* test(scripts): compact q0200 fixtures and assertions

Replace per-file scan gates with a held-first/read-refill interleaving that retains concurrency bounds, out-of-order completion, sorted results, and cancellation cleanup. Remove unused CPU nodes from the clipping fixture. Consolidate build identity branch setup and dated-scan containment assertions without dropping their outcomes.

No production or helper edits. Plain oxlint, formatting, and diff checks passed; no tests or coverage run under CI-only mode. The remaining unique owner proof does not support the requested 40 percent reduction.

* test(ui): deslop q0201 tests

Keep all 13 expanded cases and distinct browser behaviors. Reuse the owned page lifecycle, trim unused worktree response data, and simplify check refresh fixtures.

Assert compact cron requests on both pages directly instead of measuring reconstructed fixture bytes. Retain startup admission, pagination, attention classification, geometry, and voice disclosure proof. CI-only campaign: oxlint, oxfmt, and diff checks passed; no tests executed.

* test(ui): consolidate q0201 e2e proof layers

Remove the panel reflow replay: chat-panel-layout preserves live content and saved geometry across layouts; chat-transcript-geometry-updates commits settled widths; chat-worked-for-visualization keeps virtual rows apart. Remove its owner-watch and timing entries only.

Worktree default and explicit-base submission remain covered by worktrees-page: leaves base resolution to the Gateway, and locks the create draft until create settles. Keep the responsive hub geometry scenario.

Keep compact cron requests on both pages in E2E. Sidebar-attention-store holds automatic inventory until chat is ready and reconciles both pages; sidebar-attention-items and cron-status retain failed, paused, auto-disabled, running and overdue classification.

Keep browser-only update geometry, voice disclosure/reload/search, atomic Draft submission and reader navigation. Update-confirmation.runtime owns revision metadata; panel-refresh-status owns hard-error/stale presentation; chat-composer-capability-menu owns menu views and override pills. Consolidate unmarked speech into retained voice history; chat-thread-grouping owns separate backend answers.

CI-only: no tests or coverage run. Plain oxlint, oxfmt and git diff --check passed. Shard test LOC: 826 to 490; prior commit preserved.

* test: preserve distinct coverage and repair d468 fixture types

* test: retain SQLite benchmark workload cardinalities
2026-10-24 13:15:08 +00:00

97 lines
3.2 KiB
TypeScript

import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, expect, it } from "vitest";
import { collectSourceFileContents } from "../../scripts/lib/source-file-scan-cache.mts";
import { createDeferred } from "../helpers/promise.js";
const tempDirs: string[] = [];
let pendingScan: ReturnType<typeof collectSourceFileContents> | undefined;
async function sourceFixture(files: Record<string, string>) {
const repoRoot = await mkdtemp(path.join(os.tmpdir(), "openclaw-source-scan-"));
tempDirs.push(repoRoot);
await mkdir(path.join(repoRoot, "src"));
for (const [name, content] of Object.entries(files)) {
await writeFile(path.join(repoRoot, "src", name), content, "utf8");
}
return (overrides: Partial<Parameters<typeof collectSourceFileContents>[0]>) =>
collectSourceFileContents({
repoRoot,
scanRoots: ["src"],
scanExtensions: new Set([".ts"]),
ignoredDirNames: new Set(),
...overrides,
});
}
afterEach(async () => {
// Native test timeout releases held reads; join them before removing their files.
await Promise.allSettled(pendingScan ? [pendingScan] : []);
pendingScan = undefined;
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});
it("bounds reads, refills the pool, and returns sorted content despite a held first read", async ({
signal,
}) => {
const names = ["a.ts", "b.ts", "c.ts", "d.ts"];
const fixture = await sourceFixture(Object.fromEntries(names.map((name) => [name, "source"])));
const held = createDeferred();
const refilled = createDeferred();
let active = 0;
let maximum = 0;
const release = () => held.resolve();
signal.throwIfAborted();
signal.addEventListener("abort", release, { once: true });
const scan = (pendingScan = fixture({
maxConcurrentReads: 2,
statFile: (file) => {
maximum = Math.max(maximum, ++active);
return stat(file);
},
readFile: async (file) => {
const name = path.basename(file);
if (name === names[0]) {
await held.promise;
}
active--;
if (name === names.at(-1)) {
refilled.resolve();
}
return `content:${name}`;
},
}));
try {
await refilled.promise;
signal.throwIfAborted();
expect(maximum).toBe(2);
expect(active).toBe(1);
release();
const files = await scan;
expect(files.map((file) => file.relativeFile)).toEqual(names.map((name) => `src/${name}`));
expect(files.map((file) => file.content)).toEqual(names.map((name) => `content:${name}`));
} finally {
signal.removeEventListener("abort", release);
release();
await scan;
}
});
it.each<[string, string, number, number]>([
["before reading", "x".repeat(32), 32, 0],
["after reading", "small", 16, 1],
])("rejects oversized sources %s", async (_phase, content, bytes, calls) => {
const scan = await sourceFixture({ "oversized.ts": content });
let readCalls = 0;
await expect(
scan({
maxFileBytes: 8,
readFile: async () => {
readCalls += 1;
return "x".repeat(16);
},
}),
).rejects.toThrow(`source scan file exceeds 8 byte limit: src/oversized.ts (${bytes} bytes)`);
expect(readCalls).toBe(calls);
});