test: remove 158 low-value tests (#39483)

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
OrcaWin
2026-11-07 04:18:13 -08:00
committed by GitHub
co-authored by OrcaWin
parent 27a724e303
commit cecfa9865d
40 changed files with 5 additions and 4760 deletions
-3
View File
@@ -571,9 +571,6 @@ jobs:
node config/scripts/test-runtime/execution-policy/run-vitest.mjs run --config config/vitest.config.ts
--maxWorkers=4 --isolate --retry=0 --bail=0
config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs
config/scripts/mobile-web/check-entry/mobile-test-change-scope.test.mjs
config/scripts/ci/unit-selection/win32-test-lane-registration.test.mjs
config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-boundary.test.ts
# Report failure through the separate required check without blocking unrelated consumers.
- name: Smoke process-host package on Node 18
@@ -901,7 +901,6 @@
"src/main/ai-vault/structured-session-ownership-client-audience.test.ts": 1092,
"src/main/ai-vault/structured-session-ownership.test.ts": 1191,
"src/main/amp/hook-service.test.ts": 68,
"src/main/antigravity/antigravity-acp-runtime-probe.test.ts": 470,
"src/main/antigravity/antigravity-browser-helper.test.ts": 161,
"src/main/antigravity/antigravity-chat-sign-in.test.ts": 1497,
"src/main/antigravity/antigravity-sign-in-callback.test.ts": 59,
@@ -2828,7 +2827,6 @@
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-close-aborts-start.test.ts": 1806,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-codex-held-goal.test.ts": 2081,
"src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-command-publication.test.ts": 1350,
"src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-command-readers.test.ts": 567,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption-budget.test.ts": 4134,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-create-adoption.test.ts": 1670,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-current-requests.test.ts": 3325,
@@ -2883,15 +2881,12 @@
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-running-operation-order.test.ts": 2006,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-send-open-stale-turn.test.ts": 2301,
"src/main/native-chat/agent-session-wire/delivery/testing/structured-agent-session-send-settlement.test.ts": 197,
"src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-shown-work.test.ts": 567,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-stale-turn-open.test.ts": 2210,
"src/main/native-chat/agent-session-wire/termination/testing/structured-agent-session-stale-turn-verdict.test.ts": 305,
"src/main/native-chat/agent-session-wire/termination/testing/structured-agent-session-stale-verdict-persistence.test.ts": 972,
"src/main/native-chat/agent-session-wire/termination/testing/structured-agent-session-stale-verdict-prompts.test.ts": 665,
"src/main/native-chat/agent-session-wire/startup/testing/structured-agent-session-start-flight.test.ts": 48,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-startup-attempt-reports.test.ts": 1857,
"src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed-clock.test.ts": 827,
"src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed-conversation-name.test.ts": 938,
"src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed-launch-directory.test.ts": 856,
"src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed-stopping.test.ts": 831,
"src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed.test.ts": 1849,
@@ -2903,7 +2898,6 @@
"src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-subscriber-oversized-removal.test.ts": 717,
"src/main/native-chat/agent-session-wire/publication/subscribers/testing/structured-agent-session-subscriber-publication.test.ts": 732,
"src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-target-reconcile.test.ts": 786,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-task-queue.test.ts": 96,
"src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts": 5574,
"src/main/native-chat/agent-session-wire/operations/testing/structured-agent-session-thread-goal.test.ts": 3029,
"src/main/native-chat/agent-session-wire/journal-ingress/testing/structured-agent-session-transition-rollback.test.ts": 919,
@@ -8772,10 +8766,7 @@
"src/shared/bundled-web-client-manifest.test.ts": 66,
"src/shared/calm-status-reveal.test.ts": 49,
"src/shared/cheap-process-table-snapshot.test.ts": 84,
"src/shared/source-control/checks/logs/check-job-log-byte-cap.test.ts": 82,
"src/shared/source-control/checks/logs/check-job-log-excerpt.test.ts": 114,
"src/shared/source-control/checks/logs/check-job-log-marker-candidates.test.ts": 130,
"src/shared/source-control/checks/logs/check-job-log-performance-harness.test.ts": 456,
"src/shared/source-control/checks/logs/check-job-log-retention.test.ts": 451,
"src/shared/source-control/checks/logs/check-job-log-tail-slice.test.ts": 61,
"src/shared/source-control/checks/logs/check-job-log-text-performance.test.ts": 132,
@@ -8945,8 +8936,6 @@
"src/shared/github/pull-request-merge-methods.test.ts": 41,
"src/shared/github/repository-identity-key.test.ts": 39,
"src/shared/source-control/checks/gitlab/gitlab-job-log-excerpt.test.ts": 95,
"src/shared/source-control/checks/gitlab/gitlab-job-trace-check-details.test.ts": 69,
"src/shared/source-control/checks/gitlab/gitlab-pipeline-checks.test.ts": 40,
"src/shared/gitlab-projects.test.ts": 42,
"src/shared/grok-model-list-probe.test.ts": 54,
"src/shared/grok-session-paths.test.ts": 104,
@@ -8994,7 +8983,6 @@
"src/shared/keybindings-keyboard-layout.test.ts": 86,
"src/shared/keybindings-parse-cache.test.ts": 61,
"src/shared/keybindings-parsing.test.ts": 86,
"src/shared/keybindings-terminal-context.test.ts": 87,
"src/shared/keybindings-unassigned-actions.test.ts": 73,
"src/shared/kiro-home.test.ts": 39,
"src/shared/libproc-addon-worker-teardown.test.ts": 46,
@@ -9444,15 +9432,11 @@
"src/shared/skill-package-manifest.test.ts": 188,
"src/shared/skill-path-containment.test.ts": 49,
"src/shared/sleeping-record-legacy-pane-key.test.ts": 59,
"src/shared/source-control/ai/recipes/source-control-ai-actions.test.ts": 243,
"src/shared/source-control/ai/settings/source-control-ai-recipe-save.test.ts": 294,
"src/shared/source-control/ai/source-control-ai.test.ts": 249,
"src/shared/source-control/decisions/source-control-create-review-intent.test.ts": 54,
"src/shared/source-control/listing/source-control-discard-all-sequence.test.ts": 50,
"src/shared/source-control/listing/source-control-entry-actions.test.ts": 54,
"src/shared/source-control/listing/source-control-group-order.test.ts": 31,
"src/shared/source-control/decisions/source-control-next-step-decision.test.ts": 99,
"src/shared/source-control/ai/source-control-plan-contracts.test.ts": 343,
"src/shared/source-control/decisions/source-control-primary-action-decision.test.ts": 67,
"src/shared/source-control/recovery/source-control-push-failure.test.ts": 51,
"src/shared/source-control/listing/source-control-section-order.test.ts": 63,
@@ -6,7 +6,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/linear/linear-issue-detail-deadline.test.ts',
'tests/e2e/linear-cli-recovery.unit.test.ts',
'src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts',
'config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-boundary.test.ts',
'config/scripts/ci/workflow-contracts/cloud-security-history-workflow.test.mjs',
'src/main/ssh/legacy-relay/ssh-relay-endpoint-incumbent-shell.integration.test.ts',
'src/main/ssh/ssh-remote-commands.test.ts',
@@ -154,7 +153,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/native-chat/agent-session-journal/**/*.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts',
'src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed.test.ts',
'src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-feed-conversation-name.test.ts',
'src/main/runtime/agent-session/records/agent-session-conversation-name-store.test.ts',
'src/main/runtime/rpc/ws-transport.test.ts',
'src/main/runtime/rpc/dispatcher-transport-parity.test.ts',
@@ -23,42 +23,6 @@ afterEach(() => {
vi.clearAllMocks()
})
it('includes stderr delivered after the process exit', async () => {
vi.useFakeTimers()
const child = createFakePipedChild(9_999_999)
spawn.mockReturnValue(child)
const failure = probeAntigravityAcpServer(
'fixture-server',
'1.3.0',
new AbortController().signal
).catch((error: unknown) => error)
await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce())
// Stdout ends with the exit, so only stderr is still arriving when the probe reads it.
child.stdout.end()
child.emit('exit', 3, null)
await vi.advanceTimersByTimeAsync(PROVIDER_EXIT_OUTPUT_DRAIN_MS / 2)
child.stderr.end('late diagnostic\n')
await expect(failure).resolves.toMatchObject({
failure: { kind: 'exit', exit: { code: 3 }, stderr: 'late diagnostic' }
})
})
it('retains the initialize timeout when teardown cannot prove exit', async () => {
vi.useFakeTimers()
spawn.mockReturnValue(createFakePipedChild(9_999_999))
const failure = probeAntigravityAcpServer(
'fixture-server',
'1.3.0',
new AbortController().signal
).catch((error: unknown) => error)
await vi.waitFor(() => expect(spawn).toHaveBeenCalledOnce())
await vi.advanceTimersByTimeAsync(70_000)
await expect(failure).resolves.toMatchObject({
cause: { message: 'Its exit was not proven after the check' },
failure: { kind: 'timeout', timeoutMs: 60_000 }
})
})
it('bounds the stderr wait when an inherited pipe stays open', async () => {
vi.useFakeTimers()
const child = createFakePipedChild(9_999_999)
@@ -1,72 +0,0 @@
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import { probeAntigravityAcpServer } from './antigravity-acp-runtime-probe'
const folders: string[] = []
afterEach(async () => {
vi.unstubAllEnvs()
await Promise.all(folders.splice(0).map((f) => rm(f, { recursive: true, force: true })))
})
async function fakeServer(): Promise<string> {
const recording = await readFile(
new URL('../acp/fixtures/antigravity-v1-question.jsonl', import.meta.url),
'utf8'
)
const initialize = JSON.parse(recording.split('\n')[0]).message.result
const folder = await mkdtemp(join(tmpdir(), 'orca-antigravity-probe-test-'))
folders.push(folder)
const server = join(folder, 'agy_acp_server.par')
await writeFile(
server,
`#!${process.execPath}
const result = ${JSON.stringify(initialize)}
require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {
const { id, method } = JSON.parse(line)
if (method === 'initialize') process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\\n')
})
`
)
await chmod(server, 0o755)
return server
}
it.skipIf(process.platform === 'win32')(
'an install accepts only the pinned release, and only once its server stopped',
async () => {
vi.stubEnv('ELECTRON_RUN_AS_NODE', '1')
const signal = new AbortController().signal
const pinned = probeAntigravityAcpServer(await fakeServer(), '1.3.0', signal)
await expect(pinned).resolves.toBeUndefined()
const other = probeAntigravityAcpServer(await fakeServer(), '1.4.0', signal)
await expect(other).rejects.toMatchObject({
message: 'Antigravity could not start on this host.',
failure: { kind: 'version', answered: '1.3.0', expected: '1.4.0' }
})
}
)
it('does not report a missing executable as a runtime exit', async () => {
const folder = await mkdtemp(join(tmpdir(), 'orca-antigravity-probe-test-'))
folders.push(folder)
await expect(
probeAntigravityAcpServer(join(folder, 'missing-server'), '1.3.0', new AbortController().signal)
).rejects.toMatchObject({ failure: null })
})
it.skipIf(process.platform === 'win32')(
'a server that exits reports its code and stderr',
async () => {
const folder = await mkdtemp(join(tmpdir(), 'orca-antigravity-probe-test-'))
folders.push(folder)
const server = join(folder, 'agy_acp_server.par')
await writeFile(server, '#!/bin/sh\necho "libfoo.so: not found" >&2\nexit 3\n')
await chmod(server, 0o755)
const failed = probeAntigravityAcpServer(server, '1.3.0', new AbortController().signal)
await expect(failed).rejects.toMatchObject({
failure: { kind: 'exit', exit: { code: 3 }, stderr: 'libfoo.so: not found' }
})
}
)
@@ -5,7 +5,6 @@ import {
} from './structured-agent-session-host-test-data'
import {
acquire,
dispatch,
eventually,
heldBehindStart,
host,
@@ -19,76 +18,7 @@ import {
registerStartupAttemptHostTests()
it.each([false, true])(
'keeps current-generation reports across readiness (replaced=%s)',
async (replaced) => {
await store.replaceSessionOptions({
sessionId: SESSION,
fence: store.getRecord(SESSION)!.lease.runtimeFence,
permissionMode: 'own',
now: NOW
})
await restartWith(publishFirst)
const id = await heldBehindStart('hello')
const fence = store.getRecord(SESSION)!.lease.runtimeFence
const acquisitionGeneration = `generation-${acquire.mock.calls.length}`
const report = (
reportedOptions: { reportedPermissionMode?: string | null },
generation = acquisitionGeneration,
reportFence = fence
) =>
host.handleAdapterEvent({
type: 'options-reported',
sessionId: SESSION,
fence: reportFence,
acquisitionGeneration: generation,
reportedOptions
})
const early = report({ reportedPermissionMode: 'accept-edits' })
expect(host.readStatusSummary(SESSION)?.runtimePermission).toBeNull()
if (replaced) {
await host.close(SESSION, 'evict')
await early
await proveOpen()
await host.flushStreamedEvents(SESSION)
expect(host.readStatusSummary(SESSION)?.runtimePermission).toBeNull()
return
}
await proveOpen()
await early
await eventually(async () => expect((await submission(id))?.dispatchState).toBe('accepted'))
const current = () => host.readStatusSummary(SESSION)?.runtimePermission
expect(current()).toEqual({ fence, mode: 'accept-edits' })
await report({ reportedPermissionMode: 'full-access' }, 'foreign')
await report({ reportedPermissionMode: 'full-access' }, acquisitionGeneration, fence + 1)
await report({})
expect(current()).toEqual({ fence, mode: 'accept-edits' })
await report({ reportedPermissionMode: null })
expect(current()).toEqual({ fence, mode: null })
expect(store.getRecord(SESSION)?.permissionMode).toBe('own')
expect(dispatch).toHaveBeenCalledTimes(1)
await host.close(SESSION, 'evict')
expect(current()).toBeNull()
}
)
describe('what a started child reports', () => {
it('keeps provider reports out of the saved next-message choice', async () => {
await restartWith(publishFirst)
const id = await heldBehindStart('hello')
await proveOpen('reported')
await eventually(async () => expect((await submission(id))?.dispatchState).toBe('accepted'))
await host.handleAdapterEvent({
type: 'options-reported',
sessionId: SESSION,
fence: store.getRecord(SESSION)!.lease.runtimeFence,
acquisitionGeneration: `generation-${acquire.mock.calls.length}`,
reportedOptions: { model: 'from-settings' }
})
await host.flushStreamedEvents(SESSION)
expect(store.getRecord(SESSION)?.options).toBeUndefined()
})
it('preserves a later accepted pick when an older child reports options', async () => {
await restartWith(publishFirst)
const id = await heldBehindStart('hello')
@@ -1,59 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { StructuredAgentSessionTaskQueue } from '../structured-agent-session-task-queue'
function pendingChainCount(queue: StructuredAgentSessionTaskQueue): number {
return (queue as unknown as { chains: Map<string, Promise<void>> }).chains.size
}
describe('StructuredAgentSessionTaskQueue', () => {
it('deletes a successful settled tail', async () => {
const queue = new StructuredAgentSessionTaskQueue()
await expect(queue.serialize('session-1', async () => 'done')).resolves.toBe('done')
await Promise.resolve()
expect(pendingChainCount(queue)).toBe(0)
})
it('deletes a rejected settled tail without poisoning the next task', async () => {
const queue = new StructuredAgentSessionTaskQueue()
await expect(
queue.serialize('session-1', async () => {
throw new Error('failed')
})
).rejects.toThrow('failed')
await expect(queue.serialize('session-1', async () => 'recovered')).resolves.toBe('recovered')
await Promise.resolve()
expect(pendingChainCount(queue)).toBe(0)
})
it('does not let an earlier tail cleanup delete an overlapping replacement', async () => {
const queue = new StructuredAgentSessionTaskQueue()
const firstGate = Promise.withResolvers<void>()
const secondGate = Promise.withResolvers<void>()
const order: string[] = []
const first = queue.serialize('session-1', async () => {
order.push('first-start')
await firstGate.promise
order.push('first-end')
})
const second = queue.serialize('session-1', async () => {
order.push('second-start')
await secondGate.promise
order.push('second-end')
})
firstGate.resolve()
await first
expect(pendingChainCount(queue)).toBe(1)
await vi.waitFor(() => expect(order).toEqual(['first-start', 'first-end', 'second-start']))
secondGate.resolve()
await second
await Promise.resolve()
expect(order).toEqual(['first-start', 'first-end', 'second-start', 'second-end'])
expect(pendingChainCount(queue)).toBe(0)
})
})
@@ -64,28 +64,6 @@ describe('a message held behind a start that never answered, then the chat ends'
expect(await rig.restartOffers()).toEqual([])
})
it('is offered for resume after a quit once the start proved itself, as the control', async () => {
await rig.dispose()
rig = await createQueuedMessageTestRig({
restartable: true,
starting: true,
recoveryCapsule: true
})
await rig.host.close(SESSION, 'evict')
const sent = rig.send('may have run')
await sent.result
await rig.proveStart()
await eventually(async () =>
expect((await rig.submission(sent.id))?.handedOverAt).toBeDefined()
)
const id = sent.id
await rig.quitRestartHostProcess()
expect(await rig.restartOffers()).toEqual([
{ sessionId: SESSION, work: { kind: 'submission', id } }
])
})
it.each(['user-close', 'evict'] as const)(
'is a card after a %s, rejected as closed, held by the reopen until a turn',
async (cause) => {
@@ -175,17 +175,4 @@ describe('same-conversation clear', () => {
store.getOperationRow(caller.callerKey, params.envelope.clientOperationId)?.outcome.status
).toBe('succeeded')
})
it('refuses another clear while the first is in flight', async () => {
const [first, second] = await Promise.all([
host.conversationCommand(caller, commandParams('clear')),
host.conversationCommand(caller, commandParams('clear'))
])
expect(first).toMatchObject({ ok: true })
expect(second).toMatchObject({
ok: false,
refusal: { details: { reason: 'conversationCommandInFlight' } }
})
expect(await clearRows()).toHaveLength(1)
})
})
@@ -95,20 +95,4 @@ describe('resolved revisions', () => {
await expect(deferred.drained()).resolves.toEqual({ ok: true })
expect(rowText()).toBe('abc')
})
it('refuses a resolved write larger than the reservation it was admitted with', async () => {
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
const bytes = estimateStructuredAgentSessionItemBytes(ROW, text('a'))
deferred.sink.tryReviseResolvedItem?.(
bytes,
() => ({
identity: ROW,
body: text('a'.repeat(64))
}),
{ turnScope: AGENT_JOURNAL_THREAD_SCOPE }
)
deferred.bind(journalTarget())
await expect(deferred.drained()).resolves.toMatchObject({ ok: false })
expect(journal.itemBody(agentJournalItemKey(ROW))).toBeNull()
})
})
@@ -2,7 +2,6 @@ import { expect, it } from 'vitest'
import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key'
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
import { openTestJournalHostDatabase } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { createAgentSessionDeltaCoalescer } from '../../publication/subscribers/agent-session-delta-coalescer'
import {
failedTool,
@@ -47,23 +46,6 @@ BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`)
).toEqual([])
})
it('writes and announces nothing when a step resolves to nothing', async () => {
const { journal, deferred, sink, publishes, bind } = await rig()
bind()
sink.tryAppendTransition?.({
lifecycle: true,
publish: true,
steps: [
itemStep(() => null),
{ kind: 'settlement', settlementId: 'none', reservedBytes: 1, resolve: () => [] }
]
})
await deferred.drained()
expect(journal.snapshot().items).toEqual([])
expect(publishes).toEqual([])
})
it('lands a write a step issues while it runs after the whole transition', async () => {
const { journal, deferred, sink, bind } = await rig()
bind()
@@ -87,45 +69,3 @@ it('lands a write a step issues while it runs after the whole transition', async
['first', 'second', 'nested'].map((recordId) => agentJournalItemKey(identity(recordId)))
)
})
it('refuses, before writing anything, a settlement that names one item twice', async () => {
const { journal } = await rig()
const before = journal.cursor().sequence
const twice = identity('twice')
await expect(
journal.appendSteps([
{
kind: 'settlement',
batch: {
settlementId: 'twice',
fence: 1,
resolve: () => [failedTool(identity('once')), failedTool(twice), failedTool(twice)]
}
}
])
).rejects.toThrow('journal_resolved_lifecycle_batch_names_item_twice')
expect(journal.cursor().sequence).toBe(before)
})
it('reports unwritten streams and owes nothing once the caller marks them written', () => {
const emitted: string[] = []
const coalescer = createAgentSessionDeltaCoalescer({
emit: (_key, text) => {
emitted.push(text)
},
schedule: () => () => {}
})
coalescer.append('a', 'Hel')
coalescer.append('b', 'Wor')
coalescer.append('a', 'lo')
expect(coalescer.dirty().map(({ key, snapshot }) => [key, snapshot.text])).toEqual([
['a', 'Hello'],
['b', 'Wor']
])
coalescer.markFlushed('a')
coalescer.flushAll()
expect(emitted).toEqual(['Wor'])
expect(coalescer.dirty()).toEqual([])
})
@@ -1,11 +1,10 @@
import { expect, it, vi } from 'vitest'
import { expect, it } from 'vitest'
import { agentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key'
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
import { openTestJournalHostDatabase } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support'
import type { StructuredAgentSessionTransition } from '../structured-agent-session-transition'
import {
failedTool,
identity,
itemStep,
rig,
@@ -46,88 +45,6 @@ it('lands its steps back to back, each resolved after the one before it', async
expect(publishes).toHaveLength(1)
})
it('admitted whole is not executed whole: a failed step keeps the ones before it and fails the sink', async () => {
const { journal, deferred, sink, publishes, bind } = await rig()
bind()
sink.tryAppendTransition?.({
lifecycle: false,
publish: true,
steps: [
itemStep(() => ({ identity: identity('kept'), body: tool('read', 'running') })),
itemStep(() => {
throw new Error('resolver failed')
})
]
})
await expect(deferred.drained()).resolves.toMatchObject({ ok: false })
expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([
agentJournalItemKey(identity('kept'))
])
expect(publishes).toEqual([])
expect(
sink.tryAppendTransition?.({
lifecycle: false,
publish: false,
steps: [itemStep(() => null)]
})
).toEqual({ accepted: false, reason: 'failed' })
})
it('writes nothing after a step that overflows its reservation', async () => {
const { journal, deferred, sink, publishes, bind } = await rig()
bind()
const after = vi.fn(() => ({ identity: identity('third'), body: tool('read', 'running') }))
sink.tryAppendTransition?.({
lifecycle: false,
publish: true,
steps: [
itemStep(() => ({ identity: identity('first'), body: tool('read', 'running') })),
itemStep(
() => ({ identity: identity('second'), body: tool('x'.repeat(10_000), 'running') }),
64
),
itemStep(after)
]
})
await expect(deferred.drained()).resolves.toMatchObject({ ok: false })
expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([
agentJournalItemKey(identity('first'))
])
expect(after).not.toHaveBeenCalled()
expect(publishes).toEqual([])
})
it('opens no next-turn work after a settlement the journal refused', async () => {
const { journal, deferred, sink, bind } = await rig()
bind()
const old = identity('old-tool')
sink.tryAppendItem?.(old, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE })
await deferred.drained()
sink.tryAppendTransition?.({
lifecycle: true,
publish: true,
steps: [
itemStep(() => ({ identity: identity('before'), body: tool('read', 'completed') })),
{
kind: 'settlement',
settlementId: 'settle',
reservedBytes: 1,
resolve: () => [failedTool(old), failedTool(old)]
},
itemStep(() => ({ identity: identity('next-turn-work'), body: tool('read', 'running') }))
]
})
await expect(deferred.drained()).resolves.toMatchObject({ ok: false })
expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([
agentJournalItemKey(old),
agentJournalItemKey(identity('before'))
])
expect(journal.item(agentJournalItemKey(old))?.body).toMatchObject({ state: 'running' })
})
it('writes nothing after a step whose row the database refused', async () => {
const { root, journal, deferred, sink, bind } = await rig()
bind()
@@ -1,16 +1,9 @@
import { expect, it, vi } from 'vitest'
import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types'
import { createAgentSessionCurrentRequestsReader } from '../../../../../shared/agent-session/requests/agent-session-current-requests-reader'
import type {
AgentSessionCurrentRequestsMarker,
AgentSessionCurrentRequestsPiece
} from '../../../../../shared/agent-session/requests/agent-session-current-requests-wire'
import type { AgentSessionCurrentRequestsMarker } from '../../../../../shared/agent-session/requests/agent-session-current-requests-wire'
import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../../../../../shared/agent-session/requests/agent-session-current-requests-capability'
import {
EMPTY_STRUCTURED_AGENT_SESSION,
reduceStructuredAgentSession,
type StructuredAgentSessionState
} from '../../../../../shared/agent-session/structured-agent-session-reducer'
import { readCurrentRequestsPiece } from '../agent-session-current-requests'
const marker: AgentSessionCurrentRequestsMarker = {
@@ -64,76 +57,3 @@ it('pulls a greater-than-frame record and greater-than-window collection lossles
expect(error).not.toHaveBeenCalled()
reader.invalidate()
})
it('retires positive owner changes, rejects late reads, and relinquishes authority on unsupported openings', async () => {
let resolve: ((piece: AgentSessionCurrentRequestsPiece) => void) | undefined
const complete = vi.fn()
const reader = createAgentSessionCurrentRequestsReader({
read: () =>
new Promise((done) => {
resolve = done
}),
complete,
replaceMarker: vi.fn(),
error: vi.fn()
})
reader.observe(marker)
reader.invalidate()
resolve?.({ marker, json: JSON.stringify([]), nextCursor: null })
await Promise.resolve()
expect(complete).not.toHaveBeenCalled()
for (const items of [[], [prompt]]) {
let state: StructuredAgentSessionState = {
...EMPTY_STRUCTURED_AGENT_SESSION,
epoch: 'e',
fence: 1,
cursor: { epoch: 'e', sequence: 1 },
items: [prompt],
currentRequests: items,
requestMarker: marker,
requestAuthority: marker
}
const replacement = { ...marker, owner: 'host:fence-2', version: 'v2', revision: 2 }
state = reduceStructuredAgentSession(state, { type: 'requests-marker', marker: replacement })
expect(state.currentRequests).toEqual([])
state = reduceStructuredAgentSession(state, {
type: 'requests-complete',
marker,
items: [prompt]
})
expect(state.currentRequests).toEqual([])
const batch = {
type: 'batch' as const,
sessionId: 's',
fence: 2,
batch: { cursor: { epoch: 'e', sequence: 1 }, items: [], removedItemIds: [], submissions: [] }
}
state = reduceStructuredAgentSession(state, {
type: 'event',
event: batch,
opensSubscription: true
})
expect(state.currentRequests).toBeUndefined()
state = reduceStructuredAgentSession(state, { type: 'requests-marker', marker: replacement })
state = reduceStructuredAgentSession(state, {
type: 'event',
event: {
type: 'snapshot',
sessionId: 's',
fence: 2,
page: {
sessionId: 's',
epoch: 'e',
direction: 'tail',
items: [prompt],
removedItemIds: [],
submissions: [],
hasOlder: false,
hasNewer: false,
window: { oldest: null, newest: null, nextCursor: { epoch: 'e', sequence: 1 } }
}
}
})
expect(state.currentRequests).toBeUndefined()
}
})
@@ -1,151 +0,0 @@
// Command turns must not replace user-request summaries, resume markers or legacy labels.
import { describe, expect, it } from 'vitest'
import { agentJournalSubmissionKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key'
import type {
AgentJournalRenderItem,
AgentJournalSubmission
} from '../../../../../shared/agent-session/journal/agent-session-journal-types'
import { latestStructuredAgentSessionRequest } from '../../../../../shared/agent-session/requests/structured-agent-session-latest-request'
import { projectStructuredAgentSessionStatusSummary } from '../../../../../shared/agent-session/view/structured-agent-session-projection'
import { structuredAgentSessionWorkingAtStop } from '../../termination/structured-agent-session-working-at-teardown'
import {
childRecord,
journal,
NOW,
record,
SESSION,
TEARDOWN_CURRENT
} from '../../recovery/testing/structured-agent-session-restart-resume-test-harness'
const PROMPT = agentJournalSubmissionKey('prompt-1')
const COMMAND = agentJournalSubmissionKey('command-1')
const REAL_TURN = 'legacy:codex:session:turn-lifecycle%3Aturn-1'
const COMMAND_TURN = 'orca:command-turn%3Acommand-1'
let sequence = 0
function item(itemId: string, body: AgentJournalRenderItem['body'], scope?: string) {
sequence += 1
return {
itemId,
revision: 1,
body,
sequence,
observedAt: NOW,
turnScope: scope ? { kind: 'turn' as const, turnItemId: scope } : { kind: 'thread' as const }
}
}
function accepted(clientMessageId: string): AgentJournalSubmission {
return {
clientMessageId,
fence: 1,
payloadFingerprint: 'fp',
dispatchState: 'accepted',
providerItemId: null,
reason: null,
submittedAt: NOW,
resolvedAt: NOW
}
}
function compactedAfterARealTurn(commandState: 'running' | 'completed' = 'completed') {
sequence = 0
const items: AgentJournalRenderItem[] = [
item(PROMPT, {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text: 'List three fruits' }]
}),
item(REAL_TURN, {
kind: 'turn',
turnId: 'turn-1',
state: 'completed',
outcome: 'success',
userItemId: PROMPT,
startedAt: NOW,
completedAt: NOW + 1_000
}),
item(
'codex:answer',
{ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Apple, pear, fig' }] },
REAL_TURN
),
item(COMMAND, {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text: '/compact' }],
command: { name: 'compact' }
}),
item(COMMAND_TURN, {
kind: 'turn',
turnId: 'compact:command-1',
state: commandState,
userItemId: COMMAND,
startedAt: NOW + 5_000,
...(commandState === 'completed' ? { outcome: 'success', completedAt: NOW + 9_000 } : {})
}),
item(
'codex:summary',
{ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Summary of it all' }] },
COMMAND_TURN
),
item(
'orca:command-result%3Acommand-1',
{ kind: 'status', text: 'Conversation compacted.', presentation: 'compaction' },
COMMAND_TURN
)
]
return { items, submissions: [accepted('prompt-1'), accepted('command-1')] }
}
describe('the sidebar after /compact (B7)', () => {
it('keeps the last real prompt, its answer, its verdict and its instant', () => {
const { items, submissions } = compactedAfterARealTurn()
expect(projectStructuredAgentSessionStatusSummary(items, submissions)).toEqual({
status: 'idle',
latestPrompt: 'List three fruits',
lastAssistantMessage: 'Apple, pear, fig',
turnOutcome: 'success',
statusStartedAt: NOW + 1_000
})
})
})
describe('the completion feed around /compact (B6)', () => {
it.each(['running', 'completed'] as const)(
'keeps the last real turn latest while it is %s',
(state) => {
const { items, submissions } = compactedAfterARealTurn(state)
expect(latestStructuredAgentSessionRequest(items, submissions)).toMatchObject({
kind: 'turn',
id: 'turn-1',
turnState: 'completed',
outcome: 'success'
})
}
)
})
describe('restart resume around /compact (B14)', () => {
function markerFor(items: AgentJournalRenderItem[], tasks: boolean) {
return structuredAgentSessionWorkingAtStop({
sessionId: SESSION,
session: { journal: journal(items), child: { fence: 1, phase: 'ready' as const } },
getRecord: () => record(),
childWorkOpen: () => false,
childWork: () =>
tasks ? [childRecord({ id: 'task-a', kind: 'agent', description: 'Review' })] : [],
trigger: 'quit',
teardownId: TEARDOWN_CURRENT,
now: NOW
})
}
it('anchors a settled lead with live children on its last real turn', () => {
const marker = markerFor(compactedAfterARealTurn().items, true)
expect(marker?.work).toEqual({ kind: 'turn', id: 'turn-1' })
expect(marker?.latestUserItemId).toBe(PROMPT)
})
})
@@ -1,34 +0,0 @@
import { describe, expect, it } from 'vitest'
import { structuredAgentSessionShownStatus } from '../structured-agent-session-shown-work'
import {
childRecord,
submission
} from '../../recovery/testing/structured-agent-session-restart-resume-test-harness'
describe('whether a session shows as working', () => {
// Stale-fence sends must not create restart offers for otherwise idle chats.
it('does not count a send left pending under an older lease fence', () => {
const journal = { items: [], submissions: [submission('msg-1', 'pending')] }
expect(structuredAgentSessionShownStatus(journal, undefined, 2).state).toBe('done')
expect(structuredAgentSessionShownStatus(journal, undefined, 1).state).not.toBe('done')
})
it('counts a settled lead whose monitor still runs', () => {
const journal = { items: [], submissions: [] }
expect(
structuredAgentSessionShownStatus(
journal,
[
childRecord({
id: 'watch',
kind: 'monitor',
description: 'Watch CI',
state: 'monitoring'
})
],
1
).state
).not.toBe('done')
expect(structuredAgentSessionShownStatus(journal, [], 1).state).toBe('done')
})
})
@@ -1,131 +0,0 @@
import {
AGENT_JOURNAL_THREAD_SCOPE,
type AgentJournalItemBody
} from '../../../../../shared/agent-session/journal/agent-session-journal-types'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { AgentJournalItemIdentity } from '../../../../../shared/agent-session/journal/agent-session-journal-identity'
import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire'
import { createTrackedJournalOpener } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { StructuredAgentSessionStatusFeed } from '../structured-agent-session-status-feed'
import { indexedStatusFeedSession } from './structured-agent-session-status-feed-test-session'
import { createStructuredAgentSessionLogger } from '../../host/structured-agent-session-logger'
import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
const SESSION = 'clock-session'
const THREAD = 'thread-1'
let root: string
const journals = createTrackedJournalOpener()
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-status-feed-clock-'))
})
afterEach(async () => {
await journals.closeAll()
await rm(root, { recursive: true, force: true })
})
function codexItem(ordinal: number): AgentJournalItemIdentity {
return { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal }
}
function approval(title: string, answered = false): AgentJournalItemBody {
return {
kind: 'approval',
title,
detail: null,
options: [{ id: 'yes', label: 'Allow' }],
resolution: answered
? { state: 'resolved', selectedOptionId: 'yes', resolvedBy: 'user', resolvedAt: 2 }
: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null }
}
}
async function openFeed() {
let clock = 1_000
const journal = await journals.open({
identity: {
sessionId: SESSION,
workspaceId: 'workspace-1',
hostId: 'local',
agent: 'codex',
providerHandle: codexProviderHandle(THREAD)
},
now: () => (clock += 100),
stateDirectory: join(root, SESSION)
})
const feed = new StructuredAgentSessionStatusFeed({
logger: createStructuredAgentSessionLogger(),
sessions: new Map([[SESSION, indexedStatusFeedSession({ journal })]]),
getConversation: () => null,
now: () => clock
})
const published: AgentSessionStatusSummary[] = []
feed.subscribe({
id: 'list-1',
emit: (event) => {
if (event.type === 'status') {
published.push(event.session)
}
}
})
const write = async (identity: AgentJournalItemIdentity, body: AgentJournalItemBody) => {
await journal.appendItem(identity, body, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE })
feed.publish(SESSION, journal)
}
await write(
{ provider: 'orca', clientMessageId: 'prompt-1' },
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'go' }] }
)
return { published, write }
}
describe('status republication and the state clock', () => {
it('stays quiet for activity on a dated idle session, and speaks when the clock moves', async () => {
const { published, write } = await openFeed()
await write(codexItem(0), {
kind: 'turn',
turnId: 'turn-1',
state: 'completed',
completedAt: 1_150
})
const settled = published.length
expect(published.at(-1)).toMatchObject({ status: 'idle', statusStartedAt: 1_150 })
await write(codexItem(5), { kind: 'status', text: 'Subagent running' })
await write(codexItem(5), { kind: 'status', text: 'Subagent running' })
expect(published).toHaveLength(settled)
await write(codexItem(0), {
kind: 'turn',
turnId: 'turn-1',
state: 'completed',
completedAt: 1_900
})
expect(published.at(-1)).toMatchObject({ status: 'idle', statusStartedAt: 1_900 })
})
it('republishes an attention clock that moves while the session stays in attention', async () => {
const { published, write } = await openFeed()
await write(codexItem(0), {
kind: 'turn',
turnId: 'turn-1',
state: 'running',
startedAt: 1_100
})
await write(codexItem(1), approval('first'))
const first = published.at(-1)?.statusStartedAt
await write(codexItem(2), approval('second'))
const second = published.at(-1)
expect(second).toMatchObject({ status: 'attention', statusStartedAt: first })
await write(codexItem(1), approval('first', true))
expect(published.at(-1)).toMatchObject({ status: 'attention' })
expect(published.at(-1)?.statusStartedAt).toBeGreaterThan(first ?? Infinity)
})
})
@@ -1,136 +0,0 @@
import { agentSessionConversationView } from '../../../../../shared/agent-session/lifecycle/agent-session-conversation-view'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it } from 'vitest'
import { createTrackedJournalOpener } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { StructuredAgentSessionStatusFeed } from '../structured-agent-session-status-feed'
import { indexedStatusFeedSession } from './structured-agent-session-status-feed-test-session'
import { createStructuredAgentSessionLogger } from '../../host/structured-agent-session-logger'
import { agentSessionRecordFixture } from '../../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
import type { AgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-record'
import { codexProviderHandle } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
import type { AgentSessionStatusEvent } from '../../../../../shared/agent-session/agent-session-wire'
import type { StructuredChatNamingFailure } from '../../host/structured-agent-session-host-types'
const journals = createTrackedJournalOpener()
let directory: string
beforeEach(async () => {
directory = await mkdtemp(join(tmpdir(), 'orca-conversation-name-'))
})
afterEach(async () => {
await journals.closeAll()
await rm(directory, { recursive: true, force: true })
})
async function namedFeed() {
const journal = await journals.open({
identity: {
sessionId: 'session',
workspaceId: 'workspace-1',
hostId: 'local',
agent: 'codex',
providerHandle: codexProviderHandle('provider')
},
stateDirectory: directory,
now: () => 100
})
let record: AgentSessionRecord = { ...agentSessionRecordFixture(), sessionId: 'session' }
let failure: StructuredChatNamingFailure | undefined
const sessions = new Map([['session', indexedStatusFeedSession({ journal })]])
const feed = new StructuredAgentSessionStatusFeed({
sessions,
getConversation: (id) =>
id === record.sessionId ? agentSessionConversationView(record) : null,
namingFailure: () => failure,
now: () => 100,
logger: createStructuredAgentSessionLogger()
})
const events: AgentSessionStatusEvent[] = []
feed.subscribe({ id: 'vault', emit: (event) => events.push(event) })
feed.publish('session')
const name = (conversationName: string) => {
record = { ...record, conversationName }
feed.publishConversationName('session')
}
const fail = (next: StructuredChatNamingFailure) => {
failure = next
feed.publishConversationName('session')
}
const sleep = (sleptAt: number | undefined) => {
record = { ...record, sleptAt }
feed.publishRecordNotes('session')
}
return { feed, events, sessions, name, fail, sleep }
}
function lastName(events: readonly AgentSessionStatusEvent[]): string | undefined {
const event = events.at(-1)
return event?.type === 'status' ? event.session.conversationName : undefined
}
it('names a chat whose tab closed before naming finished, and keeps it for later subscribers', async () => {
const { feed, events, sessions, name } = await namedFeed()
feed.revokeLive('session')
sessions.clear()
name('Explain the parser')
expect(lastName(events)).toBe('Explain the parser')
const late: AgentSessionStatusEvent[] = []
feed.subscribe({ id: 'reloaded', emit: (event) => late.push(event) })
expect(late.at(-1)).toMatchObject({
type: 'snapshot',
sessions: [{ sessionId: 'session', conversationName: 'Explain the parser' }]
})
})
it('publishes cold names from durable records across a host restart without a status row', () => {
let record = { ...agentSessionRecordFixture(), conversationName: 'Before' }
const open = () =>
new StructuredAgentSessionStatusFeed({
sessions: new Map(),
getConversation: () => agentSessionConversationView(record),
listConversations: () => [agentSessionConversationView(record)],
now: () => 100,
logger: createStructuredAgentSessionLogger()
})
const feed = open()
const events: AgentSessionStatusEvent[] = []
feed.subscribe({ id: 'existing', emit: (event) => events.push(event) })
record = { ...record, conversationName: 'After' }
feed.publishConversationName(record.sessionId)
expect(events.at(-1)).toMatchObject({
type: 'snapshot',
sessions: [],
conversationNames: [{ sessionId: record.sessionId, conversationName: 'After' }]
})
expect(feed.readPublished(record.sessionId)).toBeUndefined()
const restarted: AgentSessionStatusEvent[] = []
open().subscribe({ id: 'reconnect', emit: (event) => restarted.push(event) })
expect(restarted[0]).toMatchObject({ conversationNames: [{ conversationName: 'After' }] })
expect(restarted.at(-1)).toMatchObject({ sessions: [] })
})
it('shows a closed chat its naming failure only while it keeps the name that failed', async () => {
const { feed, events, sessions, name, fail, sleep } = await namedFeed()
name('Explain the parser')
feed.revokeLive('session')
sessions.clear()
sleep(5)
expect(events.at(-1)).toMatchObject({ session: { sleptAt: 5 } })
fail({ message: 'Agent failed', failedAt: 5, forName: 'Explain the parser' })
expect(events.at(-1)).toMatchObject({
type: 'status',
session: {
conversationName: 'Explain the parser',
namingError: { message: 'Agent failed' },
sleptAt: 5
}
})
name('parser/explain')
expect(events.at(-1)).toMatchObject({ session: { conversationName: 'parser/explain' } })
expect(events.at(-1)).not.toHaveProperty('session.namingError')
expect(events.at(-1)).toMatchObject({ session: { sleptAt: 5 } })
sleep(undefined)
expect(events.at(-1)).not.toHaveProperty('session.sleptAt')
expect(lastName(events)).toBe('parser/explain')
})
@@ -1,237 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
getEffectiveKeybindingsForAction,
keybindingMatchesAction,
matchKeybindingDigitIndex
} from './keybindings'
describe('keybindings', () => {
it('keeps Orca-first terminal context backward compatible', () => {
const ctrlP = {
key: 'p',
code: 'KeyP',
control: true,
meta: false,
alt: false,
shift: false
}
expect(keybindingMatchesAction('worktree.quickOpen', ctrlP, 'linux')).toBe(true)
expect(
keybindingMatchesAction('worktree.quickOpen', ctrlP, 'linux', undefined, {
context: 'terminal',
terminalShortcutPolicy: 'orca-first'
})
).toBe(true)
expect(
keybindingMatchesAction('worktree.quickOpen', ctrlP, 'linux', undefined, {
context: 'terminal',
terminalShortcutPolicy: 'terminal-first'
})
).toBe(false)
expect(
keybindingMatchesAction(
'terminal.search',
{ key: 'f', code: 'KeyF', control: true, meta: false, alt: false, shift: false },
'linux',
undefined,
{ context: 'terminal', terminalShortcutPolicy: 'terminal-first' }
)
).toBe(false)
})
it.each(['darwin', 'linux', 'win32'] as const)(
'defers editing and history chords on %s while app focus retains them',
(platform) => {
const chords = [
{ action: 'terminal.search', key: 'f', code: 'KeyF', shift: false },
{ action: 'terminal.closePane', key: 'w', code: 'KeyW', shift: false },
{ action: 'tab.newTerminal', key: 't', code: 'KeyT', shift: false },
{ action: 'terminal.selectAll', key: 'a', code: 'KeyA', shift: platform !== 'darwin' },
{ action: 'terminal.splitRight', key: 'd', code: 'KeyD', shift: platform !== 'darwin' }
] as const
for (const chord of chords) {
const input = {
...chord,
meta: platform === 'darwin',
control: platform !== 'darwin',
alt: false
}
expect(
keybindingMatchesAction(chord.action, input, platform, undefined, {
context: 'terminal',
terminalShortcutPolicy: 'terminal-first'
})
).toBe(false)
expect(
keybindingMatchesAction(chord.action, input, platform, undefined, {
context: 'app',
terminalShortcutPolicy: 'terminal-first'
})
).toBe(true)
}
const historyInput = {
key: 'ArrowLeft',
code: 'ArrowLeft',
meta: platform === 'darwin',
control: platform !== 'darwin',
alt: true,
shift: false
}
expect(
keybindingMatchesAction('worktree.history.back', historyInput, platform, undefined, {
context: 'terminal',
terminalShortcutPolicy: 'terminal-first'
})
).toBe(false)
}
)
it('keeps floating workspace tab shortcuts active in app focus even with terminal-first policy configured', () => {
const panelFocus = {
context: 'app',
terminalShortcutPolicy: 'terminal-first'
} as const
expect(
keybindingMatchesAction(
'tab.rename',
{ key: 'r', code: 'KeyR', meta: true, control: false, alt: false, shift: false },
'darwin',
undefined,
panelFocus
)
).toBe(true)
expect(
matchKeybindingDigitIndex(
'tab.selectByIndex',
{ key: '4', code: 'Digit4', meta: false, control: false, alt: true, shift: false },
'linux',
undefined,
panelFocus
)
).toBe(3)
})
it('keeps terminal-allowed app shortcuts active in terminal-first mode', () => {
const deleteBinding = {
key: 'Backspace',
code: 'Backspace',
control: true,
meta: false,
alt: false,
shift: true
}
expect(
keybindingMatchesAction(
'floatingTerminal.toggle',
{ key: 'a', code: 'KeyA', control: true, meta: false, alt: true, shift: false },
'linux',
undefined,
{ context: 'terminal', terminalShortcutPolicy: 'terminal-first' }
)
).toBe(true)
expect(
keybindingMatchesAction(
'tab.previousRecent',
{ key: 'Tab', code: 'Tab', control: true, meta: false, alt: false, shift: false },
'linux',
undefined,
{ context: 'terminal', terminalShortcutPolicy: 'terminal-first' }
)
).toBe(true)
expect(
keybindingMatchesAction(
'workspace.delete',
deleteBinding,
'linux',
{ 'workspace.delete': ['Mod+Shift+Backspace'] },
{ context: 'terminal', terminalShortcutPolicy: 'terminal-first' }
)
).toBe(true)
expect(
keybindingMatchesAction(
'worktree.palette',
{ key: 'k', code: 'KeyK', control: false, meta: true, alt: false, shift: false },
'darwin',
undefined,
{ context: 'app', terminalShortcutPolicy: 'terminal-first' }
)
).toBe(true)
})
it('keeps terminal clipboard shortcuts platform-native without stealing bare Ctrl+A', () => {
expect(getEffectiveKeybindingsForAction('terminal.copySelection', 'darwin')).toEqual(['Mod+C'])
expect(getEffectiveKeybindingsForAction('terminal.copySelection', 'linux')).toEqual([
'Ctrl+Shift+C',
'Ctrl+C'
])
expect(getEffectiveKeybindingsForAction('terminal.selectAll', 'darwin')).toEqual(['Mod+A'])
expect(getEffectiveKeybindingsForAction('terminal.selectAll', 'linux')).toEqual([
'Ctrl+Shift+A'
])
expect(getEffectiveKeybindingsForAction('terminal.paste', 'darwin')).toEqual(['Mod+V'])
expect(getEffectiveKeybindingsForAction('terminal.paste', 'linux')).toEqual([
'Ctrl+V',
'Ctrl+Shift+V',
'Shift+Insert'
])
expect(
keybindingMatchesAction(
'terminal.copySelection',
{ key: 'c', code: 'KeyC', control: false, meta: true, alt: false, shift: false },
'darwin'
)
).toBe(true)
expect(
keybindingMatchesAction(
'terminal.copySelection',
{ key: 'c', code: 'KeyC', control: true, meta: false, alt: false, shift: true },
'linux'
)
).toBe(true)
expect(
keybindingMatchesAction(
'terminal.copySelection',
{ key: 'c', code: 'KeyC', control: true, meta: false, alt: false, shift: false },
'linux'
)
).toBe(true)
expect(
keybindingMatchesAction(
'terminal.selectAll',
{ key: 'a', code: 'KeyA', control: false, meta: true, alt: false, shift: false },
'darwin'
)
).toBe(true)
expect(
keybindingMatchesAction(
'terminal.selectAll',
{ key: 'a', code: 'KeyA', control: true, meta: false, alt: false, shift: true },
'linux'
)
).toBe(true)
expect(
keybindingMatchesAction(
'terminal.selectAll',
{ key: 'a', code: 'KeyA', control: true, meta: false, alt: false, shift: false },
'linux'
)
).toBe(false)
expect(
keybindingMatchesAction(
'terminal.paste',
{ key: 'v', code: 'KeyV', control: true, meta: false, alt: false, shift: false },
'linux'
)
).toBe(true)
expect(
keybindingMatchesAction(
'terminal.paste',
{ key: 'Insert', code: 'Insert', control: false, meta: false, alt: false, shift: true },
'linux'
)
).toBe(true)
})
})
@@ -1,31 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
approvedOrcaHookContentHashes,
MAX_APPROVED_ORCA_HOOK_HASHES,
withOrcaHookScriptConfirmed
} from './orca-hook-trust-entries'
import type { PersistedTrustedOrcaHooks } from './orca-yaml-hook-types'
describe('approved setup hash history', () => {
it('keeps the latest approvals up to the cap, newest first', () => {
let trust: PersistedTrustedOrcaHooks = {}
const hashes = Array.from({ length: MAX_APPROVED_ORCA_HOOK_HASHES + 3 }, (_, i) => `hash-${i}`)
for (const hash of hashes) {
trust = withOrcaHookScriptConfirmed(trust, 'repo', 'setup', hash, 1)
}
const approved = approvedOrcaHookContentHashes(trust, 'repo', 'setup')
expect(MAX_APPROVED_ORCA_HOOK_HASHES).toBe(20)
expect(approved).toHaveLength(MAX_APPROVED_ORCA_HOOK_HASHES)
expect(approved[0]).toBe(hashes.at(-1))
expect(approved).not.toContain('hash-0')
})
it('moves a re-approved older script to the front without duplicating it', () => {
let trust: PersistedTrustedOrcaHooks = {}
for (const hash of ['a', 'b', 'c', 'a']) {
trust = withOrcaHookScriptConfirmed(trust, 'repo', 'setup', hash, 1)
}
expect(approvedOrcaHookContentHashes(trust, 'repo', 'setup')).toEqual(['a', 'c', 'b'])
})
})
@@ -1,60 +0,0 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createSecureFileContentCache } from './runtime-environment-store-read-cache'
let dir: string
let files: { path: string; maxBytes: number }[]
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'orca-env-cache-'))
files = [
{ path: join(dir, 'store.json'), maxBytes: 1024 },
{ path: join(dir, 'sidecar.json'), maxBytes: 1024 }
]
writeFileSync(files[0]!.path, '{"a":1}', { mode: 0o600 })
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
})
// Windows never reuses reads (ACLs are invisible to the snapshot), so there is no cache to exercise.
describe.skipIf(process.platform === 'win32')('secure file content cache', () => {
it('computes from the bytes it keys on and reuses them only while they are unchanged', () => {
const cache = createSecureFileContentCache<{ texts: (string | null)[] }>()
const compute = vi.fn((texts: (string | null)[]) => ({ texts }))
const fallback = vi.fn(() => ({ texts: [] }))
const read = () => cache.read(dir, dir, files, compute, fallback)
read().texts.push('mutated')
expect(read()).toEqual({ texts: ['{"a":1}', null] })
expect(compute).toHaveBeenCalledTimes(1)
// Same size, new bytes: what a stat signature on a coarse-timestamp filesystem could miss.
writeFileSync(files[0]!.path, '{"a":2}')
expect(read()).toEqual({ texts: ['{"a":2}', null] })
writeFileSync(files[1]!.path, '{}', { mode: 0o600 })
expect(read()).toEqual({ texts: ['{"a":2}', '{}'] })
expect(read()).toEqual({ texts: ['{"a":2}', '{}'] })
expect(compute).toHaveBeenCalledTimes(3)
expect(fallback).not.toHaveBeenCalled()
})
it('never caches a failed compute and uses the plain reader for an unreadable file', () => {
const cache = createSecureFileContentCache<number>()
const compute = vi
.fn<() => number>()
.mockImplementationOnce(() => {
throw new Error('invalid')
})
.mockReturnValue(1)
const fallback = vi.fn(() => 2)
expect(() => cache.read(dir, dir, files, compute, fallback)).toThrow('invalid')
expect(cache.read(dir, dir, files, compute, fallback)).toBe(1)
writeFileSync(files[0]!.path, 'x'.repeat(2048))
expect(cache.read(dir, dir, files, compute, fallback)).toBe(2)
expect(cache.read(dir, dir, files, compute, fallback)).toBe(2)
expect(compute).toHaveBeenCalledTimes(2)
})
})
@@ -14,34 +14,6 @@ const pairingCode = encodePairingOffer(offer)
const capable = [PAIRING_TICKET_EXCHANGE_RUNTIME_CAPABILITY]
describe('exchangeRemotePairingTicket', () => {
it('returns a code carrying a freshly generated token after the host accepts it', async () => {
const send = vi.fn().mockResolvedValue({ ok: true, result: { deviceId: 'd' } })
const saved = await exchangeRemotePairingTicket({
pairingCode,
offer,
hostCapabilities: capable,
send
})
const savedOffer = parsePairingCode(saved)!
expect(savedOffer).toMatchObject({ endpoint: offer.endpoint, publicKeyB64: offer.publicKeyB64 })
expect(savedOffer.deviceToken).toMatch(/^[0-9a-f]{48}$/)
expect(send).toHaveBeenCalledWith(
expect.objectContaining({ credential: { kind: 'token', deviceToken: 'link-token' } }),
'pairing.exchangeTicket',
{ deviceToken: savedOffer.deviceToken },
expect.any(Number)
)
// Signs in with the new token right away, so the host retires the link before any downgrade.
expect(send).toHaveBeenLastCalledWith(
expect.objectContaining({
credential: { kind: 'token', deviceToken: savedOffer.deviceToken }
}),
'status.get',
undefined,
expect.any(Number)
)
})
it('keeps the new token when the follow-up sign-in fails', async () => {
const send = vi
.fn()
@@ -55,20 +27,4 @@ describe('exchangeRemotePairingTicket', () => {
})
expect(parsePairingCode(saved)?.deviceToken).toMatch(/^[0-9a-f]{48}$/)
})
it('keeps the original code for older hosts, refusals and transport errors', async () => {
const never = vi.fn()
await expect(
exchangeRemotePairingTicket({ pairingCode, offer, hostCapabilities: undefined, send: never })
).resolves.toBe(pairingCode)
expect(never).not.toHaveBeenCalled()
for (const send of [
vi.fn().mockResolvedValue({ ok: false, error: { code: 'internal_error', message: 'no' } }),
vi.fn().mockRejectedValue(new Error('timed out'))
]) {
await expect(
exchangeRemotePairingTicket({ pairingCode, offer, hostCapabilities: capable, send })
).resolves.toBe(pairingCode)
}
})
})
@@ -1,18 +0,0 @@
import { describe, expect, it } from 'vitest'
import { WorktreeCreate } from './worktree-create-params'
describe('WorktreeCreate approvedSetupHashes', () => {
it('trims a long list instead of refusing the create', () => {
const hashes = Array.from({ length: 70 }, (_, i) => `hash-${i}`)
const parsed = WorktreeCreate.parse({ repo: 'repo', approvedSetupHashes: hashes })
expect(parsed.approvedSetupHashes).toEqual(hashes.slice(0, 64))
})
it('drops malformed entries so they can never match', () => {
const parsed = WorktreeCreate.parse({
repo: 'repo',
approvedSetupHashes: ['ok', 7, 'x'.repeat(129)]
})
expect(parsed.approvedSetupHashes).toEqual(['ok'])
})
})
@@ -1,247 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { FolderWorkspace } from '../folder-workspaces/folder-workspace-types'
import type { ProjectGroup } from '../project-group-types'
import type { Repo } from '../repo-types'
import type { WorkspaceLineage } from '../worktree/lineage-types'
import type { Worktree } from '../worktree/types'
import type { WorktreeWithInlineLineage } from '../worktree/workspace-lineage-graph'
import { getWorktreeHostIdentity } from '../worktree/host-qualified-identity'
import { cloneDefaultWorkspaceStatuses } from '../workspace-statuses'
import {
folderWorkspaceToWorktree,
getFolderWorkspaceWorktree
} from '../folder-workspaces/folder-workspace-worktree'
import { planSidebarRows } from './sidebar-row-plan'
import { resolveSidebarLineageParentIdentities } from './worktree-lineage-projection'
import type { Row, WorktreeGroupBy } from './row-types'
const group: ProjectGroup = {
id: 'group-1',
name: 'Multi repo',
parentPath: '/work/multi',
parentGroupId: null,
createdFrom: 'manual',
tabOrder: 0,
isCollapsed: false,
color: null,
createdAt: 0,
updatedAt: 0
}
const repo: Repo = {
id: 'repo-1',
path: '/work/multi/api',
displayName: 'api',
badgeColor: '#000000',
addedAt: 0,
projectGroupId: group.id
}
const folder: FolderWorkspace = {
id: 'f-1',
projectGroupId: group.id,
name: 'Release',
folderPath: '/work/multi',
linkedTask: null,
comment: '',
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 0,
createdAt: 0,
updatedAt: 0
}
const row = (id: string): Worktree => ({
id,
instanceId: `${id}#instance`,
repoId: repo.id,
path: `/work/multi/${id}`,
branch: `refs/heads/${id}`,
head: 'abc',
isBare: false,
isMainWorktree: false,
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
comment: '',
isUnread: false,
isPinned: false,
displayName: id,
sortOrder: 0,
lastActivityAt: 0
})
const nested = row('nested')
const other = row('other')
const folderRecord: WorkspaceLineage = {
childWorkspaceKey: `worktree:${nested.id}`,
childInstanceId: nested.instanceId,
parentWorkspaceKey: 'folder:f-1',
parentInstanceId: 'f-1',
origin: 'manual',
capture: { source: 'manual-action', confidence: 'explicit' },
createdAt: 1
}
function plan(
groupBy: WorktreeGroupBy,
record: WorkspaceLineage | undefined,
worktrees: Worktree[] = [nested, other],
hidden: Worktree[] = [],
repos: Repo[] = [repo],
folders: FolderWorkspace[] = [folder],
groups: ProjectGroup[] = [group]
): Row[] {
const rows = new Map(
[...worktrees, ...hidden, ...folders.map((entry) => getFolderWorkspaceWorktree(entry))].map(
(entry) => [getWorktreeHostIdentity(entry), entry]
)
)
return planSidebarRows({
groupBy,
sortBy: 'name',
worktrees,
repoMap: new Map(repos.map((entry) => [entry.id, entry])),
prGroupOf: () => 'in-progress',
workspaceStatuses: cloneDefaultWorkspaceStatuses(),
projectOrderBy: 'manual',
lineageById: {},
lineageParentIdentities: resolveSidebarLineageParentIdentities({}, rows, undefined, (entry) =>
entry.id === nested.id ? record : undefined
),
worktreeMap: new Map([...worktrees, ...hidden].map((entry) => [entry.id, entry])),
nestLineage: true,
projectGroups: groups,
placeholderRepoIds: new Set(),
importedWorktreesByRepo: new Map(),
newExternalWorktreesInboxByRepo: new Map(),
pendingCreations: [],
folderWorkspaces: folders,
defaultHostId: 'local',
hostLabelById: new Map([
['local', 'Local Mac'],
['runtime:env-1', 'windows 2']
]),
pinnedDisplayPolicy: 'single-location',
filterRepoIds: []
}).render(new Set())
}
function shape(rows: Row[]): string[] {
return rows.flatMap((entry) =>
entry.type === 'header'
? [`header ${entry.label ?? entry.key} ${entry.count}`]
: entry.type === 'folder-workspace'
? [`folder ${entry.folderWorkspace.name} children=${entry.lineageChildCount ?? 0}`]
: entry.type === 'item'
? [`${' '.repeat(entry.depth)}${entry.worktree.id}`]
: []
)
}
describe('folder workspaces as sidebar parents', () => {
it('nests a folder child under the folder in its project group, header counts unchanged', () => {
expect(shape(plan('repo', folderRecord))).toEqual([
'header Multi repo 2',
'folder Release children=1',
' nested',
'header api 2',
'other'
])
})
it('keeps a project whose only workspace sits under the folder, and its count', () => {
expect(shape(plan('repo', folderRecord, [nested]))).toEqual([
'header Multi repo 2',
'folder Release children=1',
' nested',
'header api 1'
])
})
it('leaves the child in its project when it has no folder parent', () => {
expect(shape(plan('repo', undefined))).toEqual([
'header Multi repo 2',
'folder Release children=0',
'header api 2',
'nested',
'other'
])
})
it('nests under the folder without grouping', () => {
expect(shape(plan('none', folderRecord))).toEqual([
'header all 3',
'other',
'folder Release children=1',
' nested'
])
})
it('nests by lane under status grouping, as worktree parents do', () => {
const done = { ...nested, workspaceStatus: 'completed' }
expect(shape(plan('workspace-status', folderRecord, [done, other]))).toEqual([
'header In progress 2',
'other',
'folder Release children=0',
'header Done 1',
'nested'
])
})
it('groups a row under a hidden folder child by its own project', () => {
const web: Repo = { ...repo, id: 'repo-2', path: '/work/multi/web', displayName: 'web' }
const archived = { ...nested, isArchived: true }
const grandchild: WorktreeWithInlineLineage = {
...row('grandchild'),
repoId: web.id,
lineage: {
worktreeId: 'grandchild',
worktreeInstanceId: 'grandchild#instance',
parentWorktreeId: nested.id,
parentWorktreeInstanceId: 'nested#instance',
origin: 'manual',
capture: { source: 'manual-action', confidence: 'explicit' },
createdAt: 1
}
}
expect(shape(plan('repo', folderRecord, [grandchild, other], [archived], [repo, web]))).toEqual(
[
'header Multi repo 3',
'folder Release children=0',
'header web 1',
'grandchild',
'header api 1',
'other'
]
)
})
it('ignores a record saved for an earlier workspace at the same path', () => {
expect(shape(plan('none', { ...folderRecord, childInstanceId: 'old#instance' }))).toEqual([
'header all 3',
'nested',
'other',
'folder Release children=0'
])
})
it('names the machine on a folder card when workspaces span machines', () => {
const remoteFolder = { ...folder, executionHostId: 'runtime:env-1' as const }
const folderRow = plan('none', undefined, [other], [], [repo], [remoteFolder]).find(
(entry) => entry.type === 'folder-workspace'
)
expect(folderRow?.type === 'folder-workspace' && folderRow.hostContextLabel).toBe('windows 2')
})
it('puts an unstamped folder card on its group machine, matching its label', () => {
const remoteGroup = { ...group, executionHostId: 'runtime:env-1' }
const folderRow = plan('none', undefined, [other], [], [repo], [folder], [remoteGroup]).find(
(entry) => entry.type === 'folder-workspace'
)
expect(folderRow?.type === 'folder-workspace' && folderRow.hostContextLabel).toBe('windows 2')
expect(
folderRow?.type === 'folder-workspace' &&
folderWorkspaceToWorktree(folderRow.folderWorkspace).hostId
).toBe('runtime:env-1')
})
})
@@ -8,16 +8,8 @@ import { ALL_GROUP_KEY } from './group-keys'
import type { HostSectionRow } from './host-section-rows'
import { normalizePairedServerRow } from './paired-server-rows'
import type { SidebarFeedDomains } from './sidebar-feed-domains'
import {
indexSidebarFeed,
rankSidebarFeedWorktrees,
withHeldProjectRecency,
type SidebarFeedIndex
} from './sidebar-feed-index'
import {
buildSidebarFeedRows,
planSidebarFeedRows,
renderSidebarFeedRows,
type SidebarFeedCatalog,
type SidebarFeedView
} from './sidebar-feed-rows'
@@ -119,15 +111,6 @@ describe('buildSidebarFeedRows keeps same-id workspaces on two hosts apart', ()
lineageById: {}
})
it.each(['recent', 'name'] as const)('orders each twin by its own %s stamp', (sortBy) => {
const built = buildSidebarFeedRows(domains({ workspaces }), catalog(repos), view({ sortBy }))
expect(outline(built.sectionRows)).toEqual([
'ssh:box|r::/w/same@0',
'local|r::/w/other@0',
'local|r::/w/same@0'
])
})
it('keeps a sleeping row the host retains through a rebind gap', () => {
const built = buildSidebarFeedRows(
domains({
@@ -179,36 +162,6 @@ describe('buildSidebarFeedRows keeps same-id workspaces on two hosts apart', ()
expect(outline(built.sectionRows)).toEqual(['local|r::/w/same@0'])
})
it('lanes each twin by its own PR', () => {
const review = new Map([
[
composeWorktreeHostIdentity('ssh:box', 'r::/w/same'),
{ provider: 'github' as const, reviewState: 'merged' }
]
])
const built = buildSidebarFeedRows(
domains({ workspaces, review }),
catalog(repos),
view({ groupBy: 'pr-status' })
)
const laneOf = (identity: string) => {
let lane = ''
for (const row of built.sectionRows) {
if (row.type === 'header') {
lane = row.key
} else if (
row.type === 'item' &&
`${row.worktree.hostId ?? ''}|${row.worktree.id}` === identity
) {
return lane
}
}
return null
}
expect(laneOf('ssh:box|r::/w/same')).not.toEqual(laneOf('local|r::/w/same'))
expect(laneOf('local|r::/w/same')).toEqual(laneOf('local|r::/w/other'))
})
it('gives each twin’s row its own host’s registration of the repo', () => {
const built = buildSidebarFeedRows(domains({ workspaces }), catalog(repos), view())
const repoOf = (hostId: string) =>
@@ -222,32 +175,6 @@ describe('buildSidebarFeedRows keeps same-id workspaces on two hosts apart', ()
})
})
describe('repo sections respect manual workspace order', () => {
it('interleaves primaries by manual rank but keeps them first under automatic sorting', () => {
const repos = [repo('r')]
const rows = [
worktree('r::/w/main-a', { isMainWorktree: true, manualOrder: 30, lastActivityAt: 30 }),
worktree('r::/w/feature', { manualOrder: 20, lastActivityAt: 20 }),
worktree('r::/w/main-b', { isMainWorktree: true, manualOrder: 10, lastActivityAt: 10 })
]
const workspaces = buildWorkspaceRows({
worktrees: rows,
folderWorkspaces: [],
repos,
lineageById: {}
})
const renderedIds = (sortBy: SidebarFeedView['sortBy']) =>
buildSidebarFeedRows(
domains({ workspaces }),
catalog(repos),
view({ groupBy: 'repo', sortBy })
).sectionRows.flatMap((row) => (row.type === 'item' ? [row.worktree.id] : []))
expect(renderedIds('manual')).toEqual(['r::/w/main-a', 'r::/w/feature', 'r::/w/main-b'])
expect(renderedIds('recent')).toEqual(['r::/w/main-a', 'r::/w/main-b', 'r::/w/feature'])
})
})
describe('buildSidebarFeedRows nests each paired server’s own lineage', () => {
const serverRows = (hostId: 'runtime:a' | 'runtime:b', recentAt: number) =>
[
@@ -318,78 +245,6 @@ function projectGroup(id: string, parentGroupId: string | null): ProjectGroup {
}
}
describe('buildSidebarFeedRows host sections', () => {
it('repeats a nested project group’s whole path in each host it spans', () => {
const repos = [
repo('near', { displayName: 'near', projectGroupId: 'H' }),
repo('far', { displayName: 'far', connectionId: 'box', projectGroupId: 'H' })
]
const workspaces = buildWorkspaceRows({
worktrees: [worktree('near::/w/a'), worktree('far::/w/b', { hostId: 'ssh:box' })],
folderWorkspaces: [],
repos,
lineageById: {}
})
const built = buildSidebarFeedRows(
domains({ workspaces }),
catalog(repos, [projectGroup('G', null), projectGroup('H', 'G')]),
view({ groupBy: 'repo', visibleWorkspaceHostIds: ['local', 'ssh:box'] })
)
expect(outline(built.sectionRows)).toEqual([
'## This computer',
'# G@0',
'# H@1',
'# near@2',
'|near::/w/a@0',
'## box',
'# G@0',
'# H@1',
'# far@2',
'ssh:box|far::/w/b@0'
])
})
})
describe('the desktop’s hover hold over the shared builder', () => {
const repos = [repo('a'), repo('b')]
const feedAt = (bRecent: number): SidebarFeedDomains =>
domains({
workspaces: buildWorkspaceRows({
worktrees: [
worktree('a::/w/1', { lastActivityAt: 100 }),
worktree('b::/w/2', { lastActivityAt: bRecent })
],
folderWorkspaces: [],
repos,
lineageById: {}
})
})
const recentView = view({ groupBy: 'repo', sortBy: 'recent', projectOrderBy: 'recent' })
const itemsOf = (rows: readonly HostSectionRow[]) =>
outline(rows).filter((line) => !line.startsWith('#'))
it('keeps project sections where they were while the pointer is over the list', () => {
const engagedAt = indexSidebarFeed(feedAt(50), repos)
const heldRanks = rankSidebarFeedWorktrees(engagedAt, 'recent')
const live = feedAt(200)
const liveIndex = indexSidebarFeed(live, repos)
const shown = (index: SidebarFeedIndex) =>
itemsOf(
renderSidebarFeedRows(
planSidebarFeedRows(live, index, catalog(repos), recentView, heldRanks),
recentView,
new Set()
).sectionRows
)
// Held workspace ranks alone let B's project jump above A's.
expect(shown(liveIndex)).toEqual(['|b::/w/2@0', '|a::/w/1@0'])
expect(shown(withHeldProjectRecency(liveIndex, engagedAt))).toEqual([
'|a::/w/1@0',
'|b::/w/2@0'
])
})
})
describe('buildSidebarFeedRows reads a row’s own registration of a repo two hosts register', () => {
it('files and counts an unqualified local row under this computer, not the server', () => {
// The server's registration of `r` comes last, so a lookup by repo id alone finds it.
@@ -1,54 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { CommitMessageDraftContext } from '../generation/commit-message-generation'
import {
formatLinkedIssueTemplateValue,
withLinkedIssueDraftContext
} from './source-control-ai-action-variables'
import { renderSourceControlActionCommandTemplate } from './source-control-ai-actions'
describe('formatLinkedIssueTemplateValue', () => {
it('renders anything that is not a positive integer as an empty string', () => {
// Corrupt issue numbers must not produce references like Fixes #-7 or Fixes #1e+21.
for (const value of [
0,
-7,
12.9,
1e21,
null,
undefined,
Number.NaN,
Number.POSITIVE_INFINITY
]) {
expect(formatLinkedIssueTemplateValue(value)).toBe('')
}
})
it('expands both brace forms and never leaves the token literal', () => {
const template = 'Fixes #{linkedIssue} / {{ linkedIssue }}'
expect(
renderSourceControlActionCommandTemplate(template, {
linkedIssue: formatLinkedIssueTemplateValue(42)
})
).toBe('Fixes #42 / 42')
expect(
renderSourceControlActionCommandTemplate(template, {
linkedIssue: formatLinkedIssueTemplateValue(null)
})
).toBe('Fixes # / ')
})
})
describe('withLinkedIssueDraftContext', () => {
it('attaches only positive integers and leaves the context untouched otherwise', () => {
const context: CommitMessageDraftContext = {
branch: 'main',
stagedSummary: 'M a.ts',
stagedPatch: 'diff'
}
expect(withLinkedIssueDraftContext(context, 42)).toEqual({ ...context, linkedIssue: 42 })
for (const value of [null, undefined, Number.NaN, 0, -7, 12.9]) {
expect(withLinkedIssueDraftContext(context, value)).toBe(context)
}
})
})
@@ -1,128 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
normalizeSourceControlAiActionDefaults,
readSourceControlActionDefault,
renderSourceControlActionCommandTemplate,
setSourceControlActionAgentDefault
} from './source-control-ai-actions'
import { resolveSourceControlActionSessionOptions } from './source-control-action-launch-preferences'
describe('source-control AI launch action defaults', () => {
it('trims command templates and CLI args only when reading them', () => {
const defaults = normalizeSourceControlAiActionDefaults({
fixCommitFailure: {
agentId: 'claude',
commandInputTemplate: ' {basePrompt} ',
agentArgs: ' --model sonnet '
}
})
expect(defaults?.fixCommitFailure?.commandInputTemplate).toBe(' {basePrompt} ')
expect(defaults?.fixCommitFailure?.agentArgs).toBe(' --model sonnet ')
expect(readSourceControlActionDefault(defaults, 'fixCommitFailure')).toEqual({
agentId: 'claude',
commandInputTemplate: '{basePrompt}',
agentArgs: '--model sonnet'
})
})
it('keeps a saved action model and drops a malformed one', () => {
expect(
normalizeSourceControlAiActionDefaults({
fixChecks: {
agentId: 'codex',
launchPreferences: { model: ' gpt-5.6-terra ', effort: 'high' }
},
resolveConflicts: { agentId: 'claude', launchPreferences: { model: ' ', effort: 'high' } },
resolveComments: { agentId: 'claude', launchPreferences: 'opus' }
})
).toEqual({
fixChecks: {
agentId: 'codex',
launchPreferences: {
agentId: 'codex' as const,
modelSelection: {
base: 'default',
model: { agentId: 'codex', value: 'gpt-5.6-terra' },
options: { effort: { agentId: 'codex', value: 'high' } }
}
}
},
resolveConflicts: {
agentId: 'claude',
launchPreferences: {
agentId: 'claude',
modelSelection: {
base: 'default',
options: { effort: { agentId: 'claude', value: 'high' } }
}
}
},
resolveComments: { agentId: 'claude' }
})
})
it('keeps a permission mode the agent offers, with or without a model', () => {
const defaults = normalizeSourceControlAiActionDefaults({
fixChecks: { agentId: 'opencode', launchPreferences: { permissionMode: 'full-access' } },
fixCommitFailure: { agentId: 'codex', launchPreferences: { permissionMode: 'accept-edits' } },
fixPushFailure: {
agentId: 'codex',
launchPreferences: { model: 'gpt-5.6-terra', options: { permissionMode: 'full-access' } }
}
})
expect(defaults).toEqual({
fixChecks: {
agentId: 'opencode',
launchPreferences: { agentId: 'opencode', permissionMode: 'full-access' }
},
fixCommitFailure: { agentId: 'codex' },
fixPushFailure: { agentId: 'codex' }
})
expect(resolveSourceControlActionSessionOptions(defaults?.fixChecks ?? {}, 'opencode')).toEqual(
{
permissionMode: 'full-access'
}
)
})
it('drops the saved model when the action changes agent', () => {
const defaults = {
fixChecks: {
agentId: 'codex' as const,
launchPreferences: { agentId: 'codex' as const, model: 'gpt-5.6-terra' }
}
}
expect(setSourceControlActionAgentDefault(defaults, 'fixChecks', 'codex')).toEqual(defaults)
expect(setSourceControlActionAgentDefault(defaults, 'fixChecks', 'claude')).toEqual({
fixChecks: { agentId: 'claude' }
})
})
it('gives the saved model and effort only to the recipe agent', () => {
const recipe = {
agentId: 'codex' as const,
launchPreferences: {
agentId: 'codex' as const,
model: 'gpt-5.6-terra',
options: { effort: 'high' }
}
}
expect(resolveSourceControlActionSessionOptions(recipe, 'codex')).toEqual({
model: 'gpt-5.6-terra',
effort: 'high'
})
expect(resolveSourceControlActionSessionOptions(recipe, 'claude')).toBeUndefined()
})
it('leaves inherited prototype names visible instead of rendering function source', () => {
expect(
renderSourceControlActionCommandTemplate('use {constructor} and {toString}', {
thing: 'CI'
})
).toBe('use {constructor} and {toString}')
})
})
@@ -1,115 +0,0 @@
import { expect, it } from 'vitest'
import {
COMMIT_MESSAGE_AGENT_SPECS,
listCommitMessageAgentIds
} from '../generation/commit-message-agent-spec'
import { removeSourceControlAiArgumentFlag } from './source-control-ai-argument-flags'
it('removes each text CLI model/effort spelling without changing unrelated Arguments', () => {
const flags: Record<string, { model: string[]; effort: string[] }> = {
omp: {
model: ['--model provider/model', '--model=provider/model'],
effort: ['--thinking high']
},
claude: {
model: ['--model opus', '--model=opus'],
effort: ['--effort high', '--effort=high']
},
codex: {
model: ['--model next', '-m next', '--model=next', '-c model="next"'],
effort: [
'-c model_reasoning_effort="low"',
'--config model_reasoning_effort=high',
'--config=model_reasoning_effort=high'
]
},
opencode: {
model: ['-m provider/model', '--model=provider/model'],
effort: ['--variant high', '--variant=high']
},
opencode2: {
model: ['--model provider/model#high', '-m=provider/model#high'],
effort: ['--model provider/model#high', '--model=provider/model']
},
pi: { model: ['--model provider/model'], effort: ['--thinking high', '--thinking=high'] },
amp: { model: ['--mode smart', '--mode=deep'], effort: ['--effort high'] },
cursor: { model: ['--model auto', '--model=auto'], effort: [] },
kimi: { model: ['--model kimi-code/k3', '-m kimi-code/k3'], effort: [] },
muse: {
model: ['--model next'],
effort: ['--reasoning-effort high', '--reasoning-effort=high']
},
dsh: { model: [], effort: [] },
copilot: { model: ['--model gpt-5.4'], effort: ['--effort high'] },
antigravity: { model: ['--model next'], effort: ['--effort high'] },
jcode: { model: ['--model next'], effort: [] }
}
expect(Object.keys(flags).sort()).toEqual(listCommitMessageAgentIds().sort())
for (const spec of Object.values(COMMIT_MESSAGE_AGENT_SPECS)) {
if (!spec) {
continue
}
for (const field of ['model', 'effort'] as const) {
expect(spec[field === 'model' ? 'modelFlag' : 'effortFlag'].length > 0).toBe(
flags[spec.id][field].length > 0
)
for (const argument of flags[spec.id][field]) {
expect(
removeSourceControlAiArgumentFlag(`${argument} --other 'keep quoted'`, spec, field)
).toEqual({
agentArgs: "--other 'keep quoted'",
unrecognized: false
})
}
}
}
const codex = COMMIT_MESSAGE_AGENT_SPECS.codex!
expect(
removeSourceControlAiArgumentFlag(
'-c sandbox_mode="read-only" --config model_reasoning_effort=low --model keep',
codex,
'effort'
)
).toEqual({
agentArgs: '-c sandbox_mode="read-only" --model keep',
unrecognized: false
})
for (const agentArgs of ['--model', '--model= --other keep', '--model "unfinished']) {
expect(removeSourceControlAiArgumentFlag(agentArgs, codex, 'model')).toEqual({
agentArgs,
unrecognized: true
})
}
const quotedOperand = '--append-system-prompt "--model" --model opus -- tail --model keep'
expect(
removeSourceControlAiArgumentFlag(quotedOperand, COMMIT_MESSAGE_AGENT_SPECS.claude!, 'model')
).toEqual({
agentArgs: '--append-system-prompt "--model" -- tail --model keep',
unrecognized: false
})
})
it('requires an equals delimiter before treating a Codex config operand as an owned field', () => {
const spec = COMMIT_MESSAGE_AGENT_SPECS.codex!
for (const [field, nearMatch, key] of [
['model', '-c models --verbose', 'model'],
['effort', '--config model_reasoning_efforts --verbose', 'model_reasoning_effort']
] as const) {
expect(removeSourceControlAiArgumentFlag(nearMatch, spec, field)).toEqual({
agentArgs: nearMatch,
unrecognized: false
})
const mixed = `-c '${key}s' --config '${key} = high' --verbose`
expect(removeSourceControlAiArgumentFlag(mixed, spec, field)).toEqual({
agentArgs: `-c '${key}s' --verbose`,
unrecognized: false
})
for (const operand of [key, `${key}=`]) {
const agentArgs = `--config '${operand}' --verbose`
expect(removeSourceControlAiArgumentFlag(agentArgs, spec, field)).toEqual({
agentArgs,
unrecognized: true
})
}
}
})
@@ -1,90 +0,0 @@
import { expect, it } from 'vitest'
import { saveSourceControlAiActionModelChoice } from './source-control-ai-action-model-choice'
import {
addSourceControlAiModelEdit,
replaySourceControlAiModelEdits,
type SourceControlAiModelEdit,
type SourceControlAiModelEdits
} from './source-control-ai-action-model-edits'
import type { GlobalSettings } from '../../../global-settings-types'
import { getDefaultSourceControlAiSettings } from './source-control-ai-settings'
import type { SourceControlAiModelChoice } from './source-control-ai-settings-types'
import type { TuiAgent } from '../../../agent-launch/catalog/tui-agent'
type Edit = { agentId: TuiAgent; change: SourceControlAiModelEdit }
const START: SourceControlAiModelChoice = {
selectedModelByAgent: { codex: 'gpt-5.4', copilot: 'gpt-5.4' },
// Only the saved choice still names this host; Save must keep covering it.
selectedModelByAgentByHost: { 'ssh:saved-only': { codex: 'gpt-5.4' }, local: { copilot: 'x' } },
selectedThinkingByModel: { 'gpt-5.4': 'medium' }
}
const REGISTERED = ['ssh:registered']
const DESTINATIONS = [...REGISTERED, 'ssh:saved-only']
function settingsWith(
choice: SourceControlAiModelChoice | undefined
): Pick<GlobalSettings, 'sourceControlAi'> {
return {
sourceControlAi: {
...getDefaultSourceControlAiSettings(),
modelOverridesByOperation: choice ? { commitMessage: choice } : {}
}
}
}
function applyInOrder(edits: readonly Edit[]): SourceControlAiModelChoice | undefined {
return edits.reduce<SourceControlAiModelChoice | undefined>((choice, edit) => {
const saved = saveSourceControlAiActionModelChoice({
target: { type: 'global' },
settings: settingsWith(choice),
actionId: 'commitMessage',
hostKeys: DESTINATIONS,
...edit
})
if (!('sourceControlAi' in saved)) {
throw new Error('Expected a global save')
}
return saved.sourceControlAi.modelOverridesByOperation?.commitMessage
}, START)
}
function replayReceipt(edits: readonly Edit[]): SourceControlAiModelChoice | undefined {
const receipt = edits.reduce<SourceControlAiModelEdits>(
(folded, edit) => addSourceControlAiModelEdit(folded, edit.agentId, edit.change),
[]
)
return replaySourceControlAiModelEdits({
target: { type: 'global' },
settings: settingsWith(START),
actionId: 'commitMessage',
edits: receipt,
hostKeys: REGISTERED
})
}
const EDITS: Edit[] = (['codex', 'copilot'] as const).flatMap((agentId) => [
...['gpt-5.4', 'gpt-5.5', undefined].map((value) => ({
agentId,
change: { field: 'model' as const, value }
})),
...['gpt-5.4', 'gpt-5.5'].flatMap((modelId) =>
['low', 'high', undefined].map((value) => ({
agentId,
change: { field: 'effort' as const, modelId, value }
}))
)
])
function sequences(length: number): Edit[][] {
return length
? sequences(length - 1).flatMap((head) => EDITS.map((edit) => [...head, edit]))
: [[]]
}
it('saving the folded menu edits equals applying every edit in order', () => {
// Every sequence of up to three edits, including agents sharing one model's effort.
for (const sequence of [1, 2, 3].flatMap(sequences)) {
expect(replayReceipt(sequence), JSON.stringify(sequence)).toEqual(applyInOrder(sequence))
}
})
@@ -1,406 +0,0 @@
import { saveSourceControlAiActionModelChoice } from './source-control-ai-action-model-choice'
import { describe, expect, it } from 'vitest'
import { getDefaultSettings } from '../../../constants'
import {
saveSourceControlActionRecipe,
toSourceControlAiRepoUpdate
} from './source-control-ai-recipe-save'
import {
getDefaultSourceControlAiSettings,
normalizeSourceControlAiSettings
} from './source-control-ai-settings'
import { mergeLegacyCommitMessageAiIntoSourceControlAi } from './source-control-ai-legacy-reconciliation'
import { projectSourceControlAiToLegacyCommitMessageAi } from './source-control-ai-legacy-projection'
import { resolveSourceControlAiForOperation } from '../source-control-ai-operation-resolution'
import type { GlobalSettings } from '../../../global-settings-types'
import type { SourceControlAiSettings } from './source-control-ai-settings-types'
import type { Repo } from '../../../repo-types'
function settings(): GlobalSettings {
const base = getDefaultSettings('/tmp')
return {
...base,
defaultTuiAgent: 'codex',
sourceControlAi: {
...base.sourceControlAi!,
enabled: true,
agentId: 'codex',
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: {}
}
}
}
describe('source-control AI recipe saves', () => {
it('writes complete repo recipes and removes same-action legacy instructions', () => {
const result = saveSourceControlActionRecipe({
target: { type: 'repo', repoId: 'repo-1' },
settings: settings(),
repo: {
sourceControlAi: {
enabled: false,
instructionsByOperation: {
commitMessage: 'legacy commit',
pullRequest: 'legacy review'
},
prCreationDefaults: {
draft: true,
useTemplate: null
}
}
} satisfies Pick<Repo, 'sourceControlAi'>,
actionId: 'commitMessage',
recipe: {
agentId: 'claude',
commandInputTemplate: '{basePrompt}\n\nrepo',
agentArgs: ' --model sonnet '
}
})
expect(result).toEqual({
target: { type: 'repo', repoId: 'repo-1' },
update: {
sourceControlAi: {
enabled: false,
instructionsByOperation: {
pullRequest: 'legacy review'
},
actionOverrides: {
commitMessage: {
agentId: 'claude',
commandInputTemplate: '{basePrompt}\n\nrepo',
agentArgs: '--model sonnet'
},
pullRequest: {
commandInputTemplate: '{basePrompt}\n\nlegacy review'
}
},
prCreationDefaults: {
draft: true
}
}
}
})
})
it('keeps the action model when saving a repo recipe', () => {
const launchPreferences = {
agentId: 'codex' as const,
model: 'gpt-5.6-terra',
options: { effort: 'high' }
}
const result = saveSourceControlActionRecipe({
target: { type: 'repo', repoId: 'repo-1' },
settings: settings(),
repo: null,
actionId: 'fixChecks',
recipe: { agentId: 'codex', commandInputTemplate: '{basePrompt}', launchPreferences }
})
expect(result).toMatchObject({
update: {
sourceControlAi: {
actionOverrides: {
fixChecks: {
agentId: 'codex',
commandInputTemplate: '{basePrompt}',
launchPreferences: {
agentId: 'codex',
modelSelection: {
base: 'default',
model: { agentId: 'codex', value: 'gpt-5.6-terra' },
options: { effort: { agentId: 'codex', value: 'high' } }
}
}
}
}
}
}
})
})
it('clears empty repo source-control AI writes with the JSON boundary sentinel', () => {
expect(toSourceControlAiRepoUpdate({ prCreationDefaults: { draft: null } })).toEqual({
sourceControlAi: null
})
})
it('replaces global recipes so cleared CLI args do not survive', () => {
const currentSettings = settings()
currentSettings.sourceControlAi = {
...currentSettings.sourceControlAi!,
actions: {
pullRequest: {
agentId: 'codex',
commandInputTemplate: '{basePrompt}',
agentArgs: '--old-model'
}
}
}
const result = saveSourceControlActionRecipe({
target: { type: 'global' },
settings: currentSettings,
actionId: 'pullRequest',
recipe: {
agentId: 'claude',
commandInputTemplate: '{basePrompt}',
agentArgs: ''
}
})
if (!('sourceControlAi' in result)) {
throw new Error('Expected a global save result')
}
expect(result.sourceControlAi.actions?.pullRequest).toEqual({
agentId: 'claude',
commandInputTemplate: '{basePrompt}',
agentArgs: ''
})
})
it('writes empty repo CLI args so repository recipes can clear inherited args', () => {
const currentSettings = settings()
currentSettings.sourceControlAi = {
...currentSettings.sourceControlAi!,
actions: {
pullRequest: {
agentId: 'codex',
commandInputTemplate: '{basePrompt}',
agentArgs: '--global-model'
}
}
}
const result = saveSourceControlActionRecipe({
target: { type: 'repo', repoId: 'repo-1' },
settings: currentSettings,
repo: null,
actionId: 'pullRequest',
recipe: {
agentId: 'claude',
commandInputTemplate: '{basePrompt}',
agentArgs: ''
}
})
expect(result).toMatchObject({
update: {
sourceControlAi: {
actionOverrides: {
pullRequest: {
agentId: 'claude',
commandInputTemplate: '{basePrompt}',
agentArgs: ''
}
}
}
}
})
})
})
describe('text action model and effort writes', () => {
it('updates both scopes and known host maps, stripping only the matching flags from that scope', () => {
const settings = getDefaultSettings('/tmp')
const source = settings.sourceControlAi!
source.discoveredModelsByAgentByHost = { 'ssh:discovered': {} }
source.selectedModelByAgentByHost = { 'ssh:global': { claude: 'opus' } }
source.actions = { ...source.actions, branchName: { agentArgs: '--model global --trace' } }
const repo = {
sourceControlAi: {
actionOverrides: {
branchName: {
agentArgs:
'--model repo --config model_reasoning_effort=low -c sandbox_mode="read-only"'
}
},
modelOverridesByOperation: {
branchName: { selectedModelByAgentByHost: { 'ssh:saved': { claude: 'sonnet' } } }
}
}
}
const before = structuredClone({ settings, repo })
const global = saveSourceControlAiActionModelChoice({
target: { type: 'global' },
settings,
repo,
actionId: 'branchName',
agentId: 'codex',
change: { field: 'model', value: 'gpt-5.5' }
})
expect(global.target.type).toBe('global')
if (!('sourceControlAi' in global)) {
throw new Error('Expected global save')
}
expect(global.sourceControlAi.actions?.branchName?.agentArgs).toBe('--trace')
expect(global.sourceControlAi.modelOverridesByOperation?.branchName).toEqual({
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedModelByAgentByHost: {
'ssh:global': { codex: 'gpt-5.5' },
'ssh:discovered': { codex: 'gpt-5.5' }
}
})
const picked = saveSourceControlAiActionModelChoice({
target: { type: 'repo', repoId: 'repo' },
settings,
repo,
actionId: 'branchName',
agentId: 'codex',
change: { field: 'model', value: 'gpt-5.4' }
})
if (!('update' in picked) || !picked.update.sourceControlAi) {
throw new Error('Expected repo save')
}
expect(picked.update.sourceControlAi.actionOverrides?.branchName?.agentArgs).toBe(
'--config model_reasoning_effort=low -c sandbox_mode="read-only"'
)
expect(picked.update.sourceControlAi.modelOverridesByOperation?.branchName).toMatchObject({
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedModelByAgentByHost: {
'ssh:saved': { claude: 'sonnet', codex: 'gpt-5.4' },
'ssh:discovered': { codex: 'gpt-5.4' }
}
})
const effort = saveSourceControlAiActionModelChoice({
target: { type: 'repo', repoId: 'repo' },
settings,
repo: { sourceControlAi: picked.update.sourceControlAi },
actionId: 'branchName',
agentId: 'codex',
change: { field: 'effort', modelId: 'gpt-5.4', value: 'high' }
})
if (!('update' in effort) || !effort.update.sourceControlAi) {
throw new Error('Expected repo effort save')
}
expect(effort.update.sourceControlAi.actionOverrides?.branchName?.agentArgs).toBe(
'-c sandbox_mode="read-only"'
)
expect(
effort.update.sourceControlAi.modelOverridesByOperation?.branchName?.selectedThinkingByModel
).toEqual({ 'gpt-5.4': 'high' })
const cleared = saveSourceControlAiActionModelChoice({
target: { type: 'repo', repoId: 'repo' },
settings,
repo: { sourceControlAi: effort.update.sourceControlAi },
actionId: 'branchName',
agentId: 'codex',
change: { field: 'model', value: undefined }
})
if (!('update' in cleared) || !cleared.update.sourceControlAi) {
throw new Error('Expected repo clear')
}
expect(
cleared.update.sourceControlAi.modelOverridesByOperation?.branchName?.selectedModelByAgent
).toBeUndefined()
expect(
cleared.update.sourceControlAi.modelOverridesByOperation?.branchName
?.selectedModelByAgentByHost
).toEqual({ 'ssh:saved': { claude: 'sonnet' } })
// A composed `model#variant` operand stays with Arguments on an effort edit.
const variant = saveSourceControlAiActionModelChoice({
target: { type: 'global' },
settings: {
...settings,
sourceControlAi: {
...source,
actions: { branchName: { agentArgs: '--model provider/model#high --trace' } }
}
},
actionId: 'branchName',
agentId: 'opencode2',
change: { field: 'effort', modelId: 'opencode/gpt-5.4-mini', value: 'low' }
})
if (!('sourceControlAi' in variant)) {
throw new Error('Expected global effort save')
}
expect(variant.sourceControlAi.actions?.branchName?.agentArgs).toBe(
'--model provider/model#high --trace'
)
expect(variant.sourceControlAi.modelOverridesByOperation?.branchName).toEqual({
selectedThinkingByModel: { 'opencode/gpt-5.4-mini': 'low' }
})
expect({ settings, repo }).toEqual(before)
})
})
describe('text action model writes across hosts and editors', () => {
function pickCommitModel(source: SourceControlAiSettings, hostKeys?: string[]) {
const saved = saveSourceControlAiActionModelChoice({
target: { type: 'global' },
settings: { sourceControlAi: source },
actionId: 'commitMessage',
agentId: 'codex',
hostKeys,
change: { field: 'model', value: 'gpt-5.4-mini' }
})
if (!('sourceControlAi' in saved)) {
throw new Error('Expected global save')
}
return normalizeSourceControlAiSettings(saved.sourceControlAi)
}
function resolvedModel(source: SourceControlAiSettings, hostKey: string) {
const result = resolveSourceControlAiForOperation({
settings: {
sourceControlAi: source,
commitMessageAi: projectSourceControlAiToLegacyCommitMessageAi(source)
},
operation: 'commitMessage',
discoveryHostKey: hostKey
})
return result.ok && result.value.params.model
}
it('lets a later feature-wall pick take effect locally after a card pick', () => {
const source = getDefaultSourceControlAiSettings()
source.agentId = 'codex'
source.discoveredModelsByAgentByHost = { local: {}, 'ssh:one': {} }
source.selectedModelByAgentByHost = { local: { codex: 'gpt-5.6-terra' } }
source.modelOverridesByOperation = {
commitMessage: { selectedModelByAgentByHost: { local: { claude: 'opus' } } }
}
const picked = pickCommitModel(source)
expect(picked.modelOverridesByOperation?.commitMessage).toEqual({
selectedModelByAgent: { codex: 'gpt-5.4-mini' },
selectedModelByAgentByHost: {
local: { claude: 'opus' },
'ssh:one': { codex: 'gpt-5.4-mini' }
}
})
expect(resolvedModel(picked, 'local')).toBe('gpt-5.4-mini')
// The feature-wall card edits the legacy host-agnostic model, which reconciliation carries back.
const legacy = projectSourceControlAiToLegacyCommitMessageAi(picked)
const afterWall = mergeLegacyCommitMessageAiIntoSourceControlAi(picked, {
...legacy,
selectedModelByAgent: { ...legacy.selectedModelByAgent, codex: 'gpt-5.5' }
})
expect(resolvedModel(afterWall, 'local')).toBe('gpt-5.5')
expect(resolvedModel(afterWall, 'ssh:one')).toBe('gpt-5.4-mini')
expect(
afterWall.modelOverridesByOperation?.commitMessage?.selectedModelByAgentByHost?.local
).toEqual({ claude: 'opus' })
})
it('writes registered hosts without discovery so they keep the pick once Arguments lose the flag', () => {
const source = getDefaultSourceControlAiSettings()
source.agentId = 'codex'
source.actions = { commitMessage: { agentId: 'codex', agentArgs: '--model gpt-5.5 --trace' } }
const picked = pickCommitModel(source, ['local', 'runtime:env-1', 'ssh:box'])
expect(picked.actions?.commitMessage?.agentArgs).toBe('--trace')
for (const hostKey of ['local', 'runtime:env-1', 'ssh:box']) {
expect(resolvedModel(picked, hostKey)).toBe('gpt-5.4-mini')
}
const cleared = saveSourceControlAiActionModelChoice({
target: { type: 'global' },
settings: { sourceControlAi: picked },
actionId: 'commitMessage',
agentId: 'codex',
hostKeys: ['runtime:env-1'],
change: { field: 'model', value: undefined }
})
expect(
'sourceControlAi' in cleared &&
cleared.sourceControlAi.modelOverridesByOperation?.commitMessage
).toBeUndefined()
})
})
@@ -1,83 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getDefaultSettings } from '../../constants'
import { resolveSourceControlAiForOperation } from './source-control-ai-operation-resolution'
describe('source-control AI policy regressions', () => {
it('does not apply a local model choice to an SSH execution host', () => {
const settings = getDefaultSettings('/repo')
settings.defaultTuiAgent = 'codex'
settings.sourceControlAi = {
...settings.sourceControlAi!,
agentId: 'codex',
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedModelByAgentByHost: { local: { codex: 'gpt-5.4' } }
}
const result = resolveSourceControlAiForOperation({
settings,
operation: 'commitMessage',
discoveryHostKey: 'ssh:build-host'
})
expect(result).toMatchObject({
ok: true,
value: { params: { agentId: 'codex', model: 'gpt-5.6-terra' } }
})
})
it('keeps repo recipe and host model precedence scoped to one operation', () => {
const settings = getDefaultSettings('/repo')
settings.defaultTuiAgent = 'codex'
settings.agentCmdOverrides = { codex: ' managed-codex ' }
settings.sourceControlAi = {
...settings.sourceControlAi!,
agentId: 'codex',
selectedModelByAgent: { codex: 'gpt-5.4' },
instructionsByOperation: {
...settings.sourceControlAi!.instructionsByOperation,
commitMessage: 'global instruction'
}
}
const repo = {
sourceControlAi: {
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgentByHost: {
'ssh:build-host': { codex: 'gpt-5.4-mini' }
},
selectedThinkingByModel: { 'gpt-5.4-mini': 'xhigh' }
}
},
instructionsByOperation: { commitMessage: ' repo instruction ' },
actionOverrides: {
commitMessage: {
commandInputTemplate: '{basePrompt}\n\nRepo policy',
agentArgs: ' --json '
}
}
}
}
const result = resolveSourceControlAiForOperation({
settings,
repo,
operation: 'commitMessage',
discoveryHostKey: 'ssh:build-host'
})
expect(result).toMatchObject({
ok: true,
value: {
params: {
agentId: 'codex',
model: 'gpt-5.4-mini',
thinkingLevel: 'xhigh',
customPrompt: 'repo instruction',
commandInputTemplate: '{basePrompt}\n\nRepo policy',
agentArgs: '--json',
agentCommandOverride: 'managed-codex'
}
}
})
})
})
@@ -1,751 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getDefaultSettings } from '../../constants'
import {
clearSourceControlAiModelChoiceForHost,
readSourceControlAiModelChoiceForHost,
selectSourceControlAiModelChoiceForHost
} from './settings/source-control-ai-model-selection'
import { mergeLegacyCommitMessageAiIntoSourceControlAi } from './settings/source-control-ai-legacy-reconciliation'
import { normalizeRepoSourceControlAiOverrides } from './settings/source-control-ai-repo-settings'
import { projectSourceControlAiToLegacyCommitMessageAi } from './settings/source-control-ai-legacy-projection'
import {
resolveSourceControlAiForOperation,
resolveSourceControlAiActionModelDefault
} from './source-control-ai-operation-resolution'
import { resolveSourceControlAiPrCreationDefaults } from './source-control-ai-operation-policy'
import { sourceControlAiSettingsFromLegacy } from './settings/source-control-ai-settings'
import type {
RepoSourceControlAiOverrides,
SourceControlAiOperation
} from './settings/source-control-ai-settings-types'
import type { GlobalSettings } from '../../global-settings-types'
function settings(): GlobalSettings {
const base = getDefaultSettings('/tmp')
return {
...base,
defaultTuiAgent: 'codex' as const,
sourceControlAi: {
...base.sourceControlAi!,
enabled: true,
agentId: 'codex' as const,
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: { 'gpt-5.5': 'medium', 'gpt-5.4': 'high' },
instructionsByOperation: {
commitMessage: 'Global commit style',
pullRequest: 'Global PR style',
branchName: 'Global branch style'
}
}
}
}
function resolve(operation: SourceControlAiOperation, overrides?: RepoSourceControlAiOverrides) {
const result = resolveSourceControlAiForOperation({
settings: settings(),
repo: overrides ? { sourceControlAi: overrides } : null,
operation,
discoveryHostKey: 'local',
prCreationProductDefaults: {
draft: false,
useTemplate: false,
generateDetailsOnOpen: false,
openAfterCreate: false
}
})
expect(result.ok).toBe(true)
if (!result.ok) {
throw new Error(result.error)
}
return result.value
}
describe('source-control AI resolution', () => {
it('resolves generation config and PR defaults when Source Control AI actions are hidden', () => {
const base = settings()
base.sourceControlAi = {
...base.sourceControlAi!,
enabled: false,
prCreationDefaults: {
draft: true,
useTemplate: true,
generateDetailsOnOpen: false,
openAfterCreate: false
}
}
const generation = resolveSourceControlAiForOperation({
settings: base,
repo: null,
operation: 'pullRequest'
})
expect(generation.ok).toBe(true)
expect(generation.ok && generation.value.params.model).toBe('gpt-5.5')
expect(
resolveSourceControlAiPrCreationDefaults({
settings: base,
repo: {
sourceControlAi: {
prCreationDefaults: {
draft: null,
generateDetailsOnOpen: true,
openAfterCreate: true
}
}
},
prCreationProductDefaults: {
draft: false,
useTemplate: false,
generateDetailsOnOpen: false,
openAfterCreate: false
}
})
).toEqual({
draft: true,
useTemplate: true,
generateDetailsOnOpen: true,
openAfterCreate: true
})
})
it('resolves PR defaults even when generation config is invalid', () => {
const base = settings()
base.sourceControlAi = {
...base.sourceControlAi!,
agentId: 'custom',
customAgentCommand: '',
prCreationDefaults: {
draft: false,
useTemplate: true,
generateDetailsOnOpen: true,
openAfterCreate: false
}
}
const generation = resolveSourceControlAiForOperation({
settings: base,
repo: null,
operation: 'pullRequest'
})
expect(generation.ok).toBe(false)
expect(
resolveSourceControlAiPrCreationDefaults({
settings: base,
repo: { sourceControlAi: { prCreationDefaults: { draft: true } } }
})
).toEqual({
draft: true,
useTemplate: true,
generateDetailsOnOpen: true,
openAfterCreate: false
})
})
it('treats a normalized null agent as default instead of using stale legacy agent', () => {
const base = settings()
base.defaultTuiAgent = 'codex'
base.commitMessageAi = {
...base.commitMessageAi!,
agentId: 'claude',
selectedModelByAgent: { claude: 'opus' },
selectedThinkingByModel: { opus: 'max' }
}
base.sourceControlAi = {
...base.sourceControlAi!,
agentId: null,
selectedModelByAgent: { codex: 'gpt-5.4' }
}
const result = resolveSourceControlAiForOperation({
settings: base,
repo: null,
operation: 'commitMessage',
discoveryHostKey: 'local'
})
expect(result.ok && result.value.params.agentId).toBe('codex')
expect(result.ok && result.value.params.model).toBe('gpt-5.4')
})
it('lets a repo operation model override win over global operation override', () => {
const base = settings()
base.sourceControlAi!.modelOverridesByOperation = {
commitMessage: { selectedModelByAgent: { codex: 'gpt-5.4' } }
}
const result = resolveSourceControlAiForOperation({
settings: base,
repo: {
sourceControlAi: {
modelOverridesByOperation: {
commitMessage: { selectedModelByAgent: { codex: 'gpt-5.4-mini' } }
}
}
},
operation: 'commitMessage',
discoveryHostKey: 'local'
})
expect(result.ok && result.value.params.model).toBe('gpt-5.4-mini')
})
it('uses the repo custom command before the global custom command', () => {
const base = settings()
base.sourceControlAi = {
...base.sourceControlAi!,
actions: {
...base.sourceControlAi!.actions,
commitMessage: {
agentId: 'custom',
commandInputTemplate: '{basePrompt}'
}
},
customAgentCommand: 'global-agent {prompt}'
}
const result = resolveSourceControlAiForOperation({
settings: base,
repo: {
sourceControlAi: {
customAgentCommand: 'repo-agent {prompt}'
}
},
operation: 'commitMessage',
discoveryHostKey: 'local'
})
expect(result.ok && result.value.params.customAgentCommand).toBe('repo-agent {prompt}')
})
it('resolves thinking effort with override precedence and model default fallback', () => {
expect(resolve('commitMessage').params.thinkingLevel).toBe('medium')
expect(
resolve('commitMessage', {
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedThinkingByModel: { 'gpt-5.4': 'xhigh' }
}
}
}).params.thinkingLevel
).toBe('xhigh')
const base = settings()
base.sourceControlAi!.selectedThinkingByModel = {
'gpt-5.5': 'unsupported'
} as Record<string, string>
const result = resolveSourceControlAiForOperation({
settings: base,
repo: null,
operation: 'commitMessage',
discoveryHostKey: 'local'
})
expect(result.ok && result.value.params.thinkingLevel).toBe('low')
})
it('resolves repo instructions as replacement overrides, including explicit empty', () => {
expect(resolve('commitMessage').params.customPrompt).toBe('Global commit style')
expect(
resolve('commitMessage', {
instructionsByOperation: { commitMessage: null }
}).params.customPrompt
).toBe('Global commit style')
expect(
resolve('commitMessage', {
instructionsByOperation: { commitMessage: '' }
}).params.customPrompt
).toBe('')
expect(
resolve('commitMessage', {
instructionsByOperation: { commitMessage: 'Repo commit style' }
}).params.customPrompt
).toBe('Repo commit style')
expect(resolve('branchName').params.customPrompt).toBe('Global branch style')
expect(resolve('branchName').params.commandInputTemplate).toBe(
'Global branch style\n\n{basePrompt}'
)
expect(
resolve('branchName', {
instructionsByOperation: { branchName: 'Repo branch style' }
}).params.customPrompt
).toBe('Repo branch style')
expect(
resolve('branchName', {
instructionsByOperation: { branchName: 'Repo branch style' }
}).params.commandInputTemplate
).toBe('Repo branch style\n\n{basePrompt}')
})
it('maps legacy custom prompt to released split instructions', () => {
const migrated = sourceControlAiSettingsFromLegacy({
enabled: true,
agentId: 'codex',
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: {},
customPrompt: 'Legacy commit prompt',
customAgentCommand: ''
})
expect(migrated.instructionsByOperation.commitMessage).toBe('Legacy commit prompt')
expect(migrated.instructionsByOperation.pullRequest).toBe('')
expect(migrated.instructionsByOperation.branchName).toBe('Legacy commit prompt')
expect(migrated.actions?.commitMessage?.commandInputTemplate).toBe(
'{basePrompt}\n\nLegacy commit prompt'
)
expect(migrated.actions?.branchName?.commandInputTemplate).toBe(
'Legacy commit prompt\n\n{basePrompt}'
)
})
it('merges legacy commit-message updates without wiping PR-only settings', () => {
const base = settings().sourceControlAi!
const merged = mergeLegacyCommitMessageAiIntoSourceControlAi(base, {
enabled: false,
agentId: 'claude',
selectedModelByAgent: { claude: 'sonnet' },
selectedThinkingByModel: { sonnet: 'medium' },
customPrompt: 'Legacy commit prompt',
customAgentCommand: 'claude'
})
expect(merged).toMatchObject({
enabled: false,
agentId: 'claude',
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: { 'gpt-5.5': 'medium', 'gpt-5.4': 'high' },
customAgentCommand: 'claude',
instructionsByOperation: {
commitMessage: 'Legacy commit prompt',
pullRequest: 'Global PR style',
branchName: 'Global branch style'
}
})
expect(merged.modelOverridesByOperation?.commitMessage).toEqual({
selectedModelByAgent: { claude: 'sonnet' },
selectedThinkingByModel: { sonnet: 'medium' }
})
})
it('can map explicit legacy PR generation instructions for old runtime callers', () => {
const merged = mergeLegacyCommitMessageAiIntoSourceControlAi(
undefined,
{
enabled: true,
agentId: 'codex',
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: {},
customPrompt: 'Legacy PR prompt',
customAgentCommand: ''
},
{ pullRequestInstructionsFromLegacy: true }
)
expect(merged.instructionsByOperation.pullRequest).toBe('Legacy PR prompt')
})
it('projects commit-message operation model overrides into legacy settings', () => {
const legacy = projectSourceControlAiToLegacyCommitMessageAi({
...settings().sourceControlAi!,
selectedModelByAgent: { codex: 'gpt-5.5', claude: 'sonnet' },
selectedModelByAgentByHost: {
local: { codex: 'gpt-5.5' },
'ssh:conn-1': { codex: 'gpt-5.5', claude: 'sonnet' }
},
selectedThinkingByModel: {
'gpt-5.4': 'high',
'gpt-5.5': 'medium'
},
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedModelByAgentByHost: {
local: { codex: 'gpt-5.4' },
'ssh:conn-1': { codex: 'gpt-5.4-mini' }
},
selectedThinkingByModel: {
'gpt-5.4': 'xhigh',
'gpt-5.4-mini': 'medium'
}
},
pullRequest: {
selectedModelByAgent: { codex: 'gpt-5.2' },
selectedThinkingByModel: { 'gpt-5.2': 'low' }
}
}
})
expect(legacy.selectedModelByAgent).toMatchObject({
codex: 'gpt-5.4',
claude: 'sonnet'
})
expect(legacy.selectedModelByAgentByHost).toMatchObject({
local: { codex: 'gpt-5.4' },
'ssh:conn-1': { codex: 'gpt-5.4-mini', claude: 'sonnet' }
})
expect(legacy.selectedThinkingByModel).toMatchObject({
'gpt-5.4': 'xhigh',
'gpt-5.4-mini': 'medium',
'gpt-5.5': 'medium'
})
expect(legacy.selectedThinkingByModel['gpt-5.2']).toBeUndefined()
})
it('merges projected legacy commit-message models without changing PR defaults', () => {
const source = {
...settings().sourceControlAi!,
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: { 'gpt-5.5': 'medium' },
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedThinkingByModel: { 'gpt-5.4': 'high' }
}
}
}
const legacy = projectSourceControlAiToLegacyCommitMessageAi(source)
const merged = mergeLegacyCommitMessageAiIntoSourceControlAi(source, legacy)
expect(merged.selectedModelByAgent.codex).toBe('gpt-5.5')
expect(merged.modelOverridesByOperation?.commitMessage?.selectedModelByAgent?.codex).toBe(
'gpt-5.4'
)
const base = settings()
base.sourceControlAi = merged
expect(
resolveSourceControlAiForOperation({
settings: base,
repo: null,
operation: 'commitMessage',
discoveryHostKey: 'local'
})
).toMatchObject({ ok: true, value: { params: { model: 'gpt-5.4' } } })
expect(
resolveSourceControlAiForOperation({
settings: base,
repo: null,
operation: 'pullRequest',
discoveryHostKey: 'local'
})
).toMatchObject({ ok: true, value: { params: { model: 'gpt-5.5' } } })
})
it('does not synthesize a commit-message override from projected global defaults', () => {
const source = {
...settings().sourceControlAi!,
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: { 'gpt-5.5': 'medium' },
modelOverridesByOperation: undefined
}
const legacy = projectSourceControlAiToLegacyCommitMessageAi(source)
const merged = mergeLegacyCommitMessageAiIntoSourceControlAi(source, legacy)
expect(merged.selectedModelByAgent.codex).toBe('gpt-5.5')
expect(merged.modelOverridesByOperation?.commitMessage).toBeUndefined()
})
it('merges only rollback legacy model deltas into commit-message overrides', () => {
const source = {
...settings().sourceControlAi!,
selectedModelByAgent: { codex: 'gpt-5.5', claude: 'sonnet' },
selectedModelByAgentByHost: {
local: { codex: 'gpt-5.5', claude: 'sonnet' }
},
selectedThinkingByModel: {
'gpt-5.5': 'medium',
sonnet: 'high'
},
modelOverridesByOperation: undefined
}
const legacy = projectSourceControlAiToLegacyCommitMessageAi(source)
legacy.selectedModelByAgent = {
...legacy.selectedModelByAgent,
codex: 'gpt-5.4'
}
legacy.selectedModelByAgentByHost = {
...legacy.selectedModelByAgentByHost,
local: {
...legacy.selectedModelByAgentByHost?.local,
codex: 'gpt-5.4'
}
}
const merged = mergeLegacyCommitMessageAiIntoSourceControlAi(source, legacy)
expect(merged.selectedModelByAgent).toEqual({ codex: 'gpt-5.5', claude: 'sonnet' })
expect(merged.modelOverridesByOperation?.commitMessage).toEqual({
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedModelByAgentByHost: { local: { codex: 'gpt-5.4' } }
})
})
it('removes projected commit-message overrides cleared by legacy settings', () => {
const source = {
...settings().sourceControlAi!,
selectedModelByAgent: { codex: 'gpt-5.5' },
selectedThinkingByModel: { 'gpt-5.5': 'medium' },
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedThinkingByModel: { 'gpt-5.4': 'high' }
}
}
}
const legacy = projectSourceControlAiToLegacyCommitMessageAi(source)
delete legacy.selectedModelByAgent.codex
delete legacy.selectedThinkingByModel['gpt-5.4']
const merged = mergeLegacyCommitMessageAiIntoSourceControlAi(source, legacy)
expect(merged.modelOverridesByOperation?.commitMessage).toBeUndefined()
})
it('keeps existing per-action host picks on upgrade and derives the inherited row through the same resolver', () => {
const model = (input: GlobalSettings, hostKey: string) => {
const result = resolveSourceControlAiForOperation({
settings: input,
operation: 'commitMessage',
discoveryHostKey: hostKey
})
return result.ok && result.value.params.model
}
// A feature-wall pick reconciled into the Commit message entry stays local-only.
const wall = settings()
wall.sourceControlAi!.selectedModelByAgentByHost = { 'ssh:one': { codex: 'gpt-5.4' } }
const legacy = projectSourceControlAiToLegacyCommitMessageAi(wall.sourceControlAi!)
wall.sourceControlAi = mergeLegacyCommitMessageAiIntoSourceControlAi(wall.sourceControlAi!, {
...legacy,
selectedModelByAgent: { ...legacy.selectedModelByAgent, codex: 'gpt-5.4-mini' }
})
wall.commitMessageAi = projectSourceControlAiToLegacyCommitMessageAi(wall.sourceControlAi)
expect(wall.sourceControlAi.modelOverridesByOperation?.commitMessage).toEqual({
selectedModelByAgent: { codex: 'gpt-5.4-mini' }
})
expect([model(wall, 'local'), model(wall, 'ssh:one')]).toEqual(['gpt-5.4-mini', 'gpt-5.4'])
// A host-specific pick keeps winning over the host-agnostic one on that host.
const hosts = settings()
hosts.sourceControlAi!.modelOverridesByOperation = {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4-mini' },
selectedModelByAgentByHost: { local: { codex: 'gpt-5.5' }, 'ssh:box': { codex: 'gpt-5.4' } }
}
}
// A host the pick never covered keeps its own default.
expect([model(hosts, 'local'), model(hosts, 'ssh:box'), model(hosts, 'ssh:new')]).toEqual([
'gpt-5.5',
'gpt-5.4',
'gpt-5.6-terra'
])
const base = settings()
base.sourceControlAi!.modelOverridesByOperation = {
branchName: {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedThinkingByModel: { 'gpt-5.4': 'high' }
}
}
const choice = base.sourceControlAi!.modelOverridesByOperation.branchName
const input = { settings: base, operation: 'branchName' as const }
const repo = {
sourceControlAi: {
modelOverridesByOperation: {
branchName: { selectedModelByAgent: { codex: 'gpt-5.4-mini' } }
}
}
}
const repoDefault = resolveSourceControlAiActionModelDefault({ ...input, repo }, 'repo')
expect(repoDefault.ok && repoDefault.value.params).toMatchObject({
model: 'gpt-5.4',
thinkingLevel: 'high'
})
const inherited = resolveSourceControlAiActionModelDefault({ ...input, repo })
const withoutPicks = {
...base,
sourceControlAi: { ...base.sourceControlAi!, modelOverridesByOperation: undefined }
}
expect(inherited).toEqual(
resolveSourceControlAiForOperation({ ...input, settings: withoutPicks })
)
expect(base.sourceControlAi!.modelOverridesByOperation.branchName).toBe(choice)
base.sourceControlAi!.modelOverridesByOperation.commitMessage = {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedThinkingByModel: { 'gpt-5.4': 'high' }
}
base.commitMessageAi = projectSourceControlAiToLegacyCommitMessageAi(base.sourceControlAi!)
const commitDefault = resolveSourceControlAiActionModelDefault({
settings: base,
operation: 'commitMessage'
})
expect(commitDefault.ok && commitDefault.value.params).toMatchObject({
model: 'gpt-5.5',
thinkingLevel: 'medium'
})
const branchDefault = resolveSourceControlAiActionModelDefault({
settings: base,
operation: 'branchName'
})
expect(branchDefault.ok && branchDefault.value.params.model).toBe('gpt-5.5')
})
it('reads and selects host-scoped model choices with local fallback rules', () => {
const localChoice = selectSourceControlAiModelChoiceForHost(
undefined,
'local',
'codex',
'gpt-5.4'
)
expect(localChoice).toEqual({
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedModelByAgentByHost: { local: { codex: 'gpt-5.4' } }
})
const remoteChoice = selectSourceControlAiModelChoiceForHost(
localChoice,
'ssh:conn-1',
'codex',
'remote-model'
)
expect(readSourceControlAiModelChoiceForHost(remoteChoice, 'local', 'codex')).toBe('gpt-5.4')
expect(readSourceControlAiModelChoiceForHost(remoteChoice, 'ssh:conn-1', 'codex')).toBe(
'remote-model'
)
expect(
readSourceControlAiModelChoiceForHost(remoteChoice, 'ssh:conn-2', 'codex')
).toBeUndefined()
expect(
readSourceControlAiModelChoiceForHost(
{ selectedModelByAgent: { codex: 'global-model' } },
'local',
'codex'
)
).toBe('global-model')
})
it('clears only the selected host model override when inheriting', () => {
const cleared = clearSourceControlAiModelChoiceForHost(
{
selectedModelByAgent: { codex: 'local-model' },
selectedModelByAgentByHost: {
local: { codex: 'local-model' },
'ssh:conn-1': { codex: 'remote-model' }
},
selectedThinkingByModel: { 'remote-model': 'high' }
},
'local',
'codex'
)
expect(cleared).toEqual({
selectedModelByAgentByHost: {
'ssh:conn-1': { codex: 'remote-model' }
},
selectedThinkingByModel: { 'remote-model': 'high' }
})
})
it('normalizes repo overrides defensively and preserves explicit inherit sentinels', () => {
const normalized = normalizeRepoSourceControlAiOverrides({
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: {
codex: 'gpt-5.4',
claude: 42,
constructor: 'polluted'
},
selectedModelByAgentByHost: {
local: { codex: 'gpt-5.4' },
'ssh:conn-1': { codex: 'remote-model', claude: false },
malformed: 'not-a-record',
prototype: { codex: 'polluted' }
},
selectedThinkingByModel: {
'gpt-5.4': 'xhigh',
'remote-model': 'high',
bad: true,
constructor: 'polluted'
}
},
pullRequest: {
selectedModelByAgent: []
},
branchName: {
selectedModelByAgent: { codex: 'gpt-5.4' }
},
unknown: {
selectedModelByAgent: { codex: 'ignored' }
}
},
instructionsByOperation: {
commitMessage: null,
pullRequest: '',
branchName: 'branch style',
unknown: 'ignored'
},
prCreationDefaults: {
draft: true,
useTemplate: null,
generateDetailsOnOpen: 'yes',
openAfterCreate: false
}
})
expect(normalized).toEqual({
modelOverridesByOperation: {
commitMessage: {
selectedModelByAgent: { codex: 'gpt-5.4' },
selectedModelByAgentByHost: {
local: { codex: 'gpt-5.4' },
'ssh:conn-1': { codex: 'remote-model' }
},
selectedThinkingByModel: {
'gpt-5.4': 'xhigh',
'remote-model': 'high'
}
},
branchName: {
selectedModelByAgent: { codex: 'gpt-5.4' }
}
},
instructionsByOperation: {
commitMessage: null,
pullRequest: '',
branchName: 'branch style'
},
actionOverrides: {
pullRequest: {
commandInputTemplate: '{basePrompt}'
},
branchName: {
commandInputTemplate: 'branch style\n\n{basePrompt}'
}
},
prCreationDefaults: {
draft: true,
useTemplate: null,
openAfterCreate: false
}
})
expect(normalizeRepoSourceControlAiOverrides(null)).toBeUndefined()
expect(normalizeRepoSourceControlAiOverrides([])).toBeUndefined()
})
it('preserves repo null command templates without requiring another override field', () => {
expect(
normalizeRepoSourceControlAiOverrides({
instructionsByOperation: {
commitMessage: 'legacy repo style'
},
actionOverrides: {
commitMessage: {
commandInputTemplate: null
}
}
})
).toEqual({
instructionsByOperation: {
commitMessage: 'legacy repo style'
},
actionOverrides: {
commitMessage: {
commandInputTemplate: null
}
}
})
})
})
@@ -1,2 +0,0 @@
import './source-control-ai-policy-regression.spec'
import './recipes/source-control-ai-action-variables.spec'
@@ -1,9 +1,7 @@
import { describe, expect, it } from 'vitest'
import { gitLabJobTraceToLogExcerpt, toGitLabJobLogExcerptResult } from './gitlab-job-log-excerpt'
import { PR_CHECK_LOG_TAIL_BYTES } from '../logs/check-job-log-excerpt'
import { gitLabJobTraceToLogExcerpt } from './gitlab-job-log-excerpt'
const CSI_ERASE = '\u001b[0K'
const RESET = '\u001b[0;m'
const CR = '\r'
describe('gitLabJobTraceToLogExcerpt', () => {
@@ -21,70 +19,4 @@ describe('gitLabJobTraceToLogExcerpt', () => {
expect(excerpt).not.toContain('section_start')
expect(excerpt).not.toContain('section_end')
})
it('strips ANSI colour sequences', () => {
const excerpt = gitLabJobTraceToLogExcerpt(`${RESET}ERROR: Job failed${RESET}`)
expect(excerpt).toBe('ERROR: Job failed')
expect(excerpt).not.toContain('[0;m')
})
it('splits carriage-return progress output so the line tail still applies', () => {
const progress = Array.from({ length: 5_000 }, (_, index) => `downloading ${index}%`).join('\r')
const excerpt = gitLabJobTraceToLogExcerpt(`${progress}\nERROR: Job failed: exit code 1`)
expect(excerpt).toContain('ERROR: Job failed: exit code 1')
expect(excerpt).not.toContain('downloading 0%')
expect(excerpt.length).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES)
})
it('bounds a multi-megabyte trace below the 1 MB runtime transport frame cap', () => {
const huge = Array.from(
{ length: 60_000 },
(_, index) => `line ${index} ${'x'.repeat(60)}`
).join('\n')
const excerpt = gitLabJobTraceToLogExcerpt(huge)
expect(huge.length).toBeGreaterThan(1024 * 1024)
expect(Buffer.byteLength(excerpt, 'utf8')).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES)
expect(excerpt).toContain('line 59999')
})
it('preserves earlier error context buried under trailing noise', () => {
const trace = [
...Array.from({ length: 150 }, (_, index) => `Installing package ${index}`),
'ERROR: Job failed: exit code 1',
...Array.from({ length: 90 }, (_, index) => `Uploading artifact ${index}`)
].join('\n')
const excerpt = gitLabJobTraceToLogExcerpt(trace)
expect(excerpt).toContain('ERROR: Job failed: exit code 1')
expect(excerpt).toContain('Uploading artifact 89')
})
it('keeps the error tail and drops the head of a huge trace', () => {
const filler = `${'x'.repeat(200)}\n`.repeat(6_000) // ~1.2 MB, above the raw cap
const excerpt = gitLabJobTraceToLogExcerpt(`head marker\n${filler}ERROR: Job failed`)
expect(excerpt).toContain('ERROR: Job failed')
expect(excerpt).not.toContain('head marker')
})
it('returns an empty excerpt for a job that never produced a log', () => {
expect(gitLabJobTraceToLogExcerpt('')).toBe('')
expect(gitLabJobTraceToLogExcerpt(` \n${CSI_ERASE}\n `)).toBe('')
})
})
describe('toGitLabJobLogExcerptResult', () => {
it('bounds a successful trace and passes errors through untouched', () => {
const bounded = toGitLabJobLogExcerptResult({ ok: true, trace: `${RESET}done` })
expect(bounded).toEqual({ ok: true, trace: 'done' })
const failure = { ok: false, error: '403 Forbidden' } as const
expect(toGitLabJobLogExcerptResult(failure)).toBe(failure)
})
})
@@ -1,103 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
gitLabJobCanHaveTrace,
gitLabJobTraceToCheckRunDetails
} from './gitlab-job-trace-check-details'
import { gitLabPipelineJobsToPRChecks } from './gitlab-pipeline-checks'
import type { GitLabPipelineJob } from '../../../gitlab-types'
import type { PRCheckDetail } from '../../../github/check-types'
const STRINGS = { emptyTrace: 'No log is available for this GitLab job.' }
const failedJob: PRCheckDetail = {
name: 'Component Tests: Purchase API',
status: 'completed',
conclusion: 'failure',
url: 'https://gitlab.example.test/acme/orca/-/jobs/42',
gitlabJobId: 42
}
describe('gitLabJobTraceToCheckRunDetails', () => {
it('renders the trace as a single job log tail', () => {
const details = gitLabJobTraceToCheckRunDetails(
failedJob,
'FAIL src/purchase/refund.spec.ts\nERROR: Job failed: exit code 1',
STRINGS
)
expect(details.jobs).toHaveLength(1)
expect(details.jobs[0]?.id).toBe(42)
expect(details.jobs[0]?.conclusion).toBe('failure')
expect(details.jobs[0]?.logTail).toContain('ERROR: Job failed: exit code 1')
expect(details.summary).toBeNull()
})
it('copies a running row status and conclusion into both detail levels', () => {
const runningJob: PRCheckDetail = {
...failedJob,
status: 'in_progress',
conclusion: 'pending'
}
const details = gitLabJobTraceToCheckRunDetails(runningJob, 'boom', STRINGS)
expect(details.status).toBe('in_progress')
expect(details.conclusion).toBe('pending')
expect(details.jobs[0]?.status).toBe('in_progress')
expect(details.jobs[0]?.conclusion).toBe('pending')
})
it('explains an empty trace instead of falling back to "no inline details"', () => {
const manualJob: PRCheckDetail = {
name: 'deploy: production',
status: 'completed',
conclusion: 'neutral',
url: null,
gitlabJobId: 77
}
const details = gitLabJobTraceToCheckRunDetails(manualJob, '', STRINGS)
expect(details.jobs).toEqual([])
expect(details.summary).toBe(STRINGS.emptyTrace)
})
it('re-slices a raw trace from an older remote runtime that ignored logExcerpt', () => {
const raw = Array.from({ length: 5_000 }, (_, index) => `line ${index}`).join('\n')
const details = gitLabJobTraceToCheckRunDetails(failedJob, raw, STRINGS)
expect(details.jobs[0]?.logTail).toContain('line 4999')
expect(details.jobs[0]?.logTail).not.toContain('line 0\n')
})
})
describe('gitLabJobCanHaveTrace', () => {
// Never-started jobs have no trace; skip those requests. Main maps other missing-log 404s to empty traces.
const cases: { status: string; expected: boolean }[] = [
{ status: 'failed', expected: true },
{ status: 'success', expected: true },
{ status: 'running', expected: true },
{ status: 'canceled', expected: true },
{ status: 'created', expected: false },
{ status: 'pending', expected: false },
{ status: 'scheduled', expected: false },
{ status: 'manual', expected: false },
{ status: 'skipped', expected: false }
]
for (const { status, expected } of cases) {
it(`${expected ? 'requests' : 'skips'} a trace for a ${status} job`, () => {
const job = {
id: 5,
name: 'unit',
stage: 'test',
status,
webUrl: '',
duration: null
} satisfies GitLabPipelineJob
const [check] = gitLabPipelineJobsToPRChecks([job])
expect(gitLabJobCanHaveTrace(check)).toBe(expected)
})
}
})
@@ -1,131 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
getGitLabPipelineNotLatestCommitSha,
gitLabPipelineJobsToPRChecks
} from './gitlab-pipeline-checks'
import type { GitLabPipelineJob } from '../../../gitlab-types'
describe('gitLabPipelineJobsToPRChecks', () => {
it('maps GitLab pipeline jobs into right-panel check rows', () => {
const jobs: GitLabPipelineJob[] = [
{
id: 1,
name: 'unit',
stage: 'test',
status: 'failed',
webUrl: 'https://gitlab.com/acme/orca/-/jobs/1',
duration: 12,
startedAt: '2026-11-05T10:00:00Z',
finishedAt: '2026-11-05T10:00:12Z'
},
{
id: 2,
name: 'deploy',
stage: 'deploy',
status: 'manual',
webUrl: '',
duration: null
},
{
id: 3,
name: 'delayed deploy',
stage: 'deploy',
status: 'scheduled',
webUrl: 'https://gitlab.com/acme/orca/-/jobs/3',
duration: null
},
{
id: 4,
name: 'external callback',
stage: 'integration',
status: 'waiting_for_callback',
webUrl: 'https://gitlab.com/acme/orca/-/jobs/4',
duration: null
}
]
expect(gitLabPipelineJobsToPRChecks(jobs)).toEqual([
{
name: 'test: unit',
status: 'completed',
conclusion: 'failure',
url: 'https://gitlab.com/acme/orca/-/jobs/1',
startedAt: '2026-11-05T10:00:00Z',
completedAt: '2026-11-05T10:00:12Z',
gitlabJobId: 1
},
{
name: 'deploy: deploy',
status: 'completed',
conclusion: 'neutral',
url: null,
gitlabJobId: 2
},
{
name: 'deploy: delayed deploy',
status: 'queued',
conclusion: 'pending',
url: 'https://gitlab.com/acme/orca/-/jobs/3',
gitlabJobId: 3
},
{
name: 'integration: external callback',
status: 'queued',
conclusion: 'pending',
url: 'https://gitlab.com/acme/orca/-/jobs/4',
gitlabJobId: 4
}
])
})
it('omits the job id when GitLab does not report a usable one', () => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: legacy input intentionally omits a required ID.
const jobs = [
{ id: 0, name: 'zero', stage: '', status: 'failed', webUrl: '', duration: null },
{ name: 'missing', stage: '', status: 'failed', webUrl: '', duration: null }
] as unknown as GitLabPipelineJob[]
const checks = gitLabPipelineJobsToPRChecks(jobs)
expect(checks).toHaveLength(2)
expect(checks.map((check) => check.name)).toEqual(['zero', 'missing'])
// Why: the runtime RPC schema requires a positive int, so a falsy id must not be forwarded.
for (const check of checks) {
expect(check).not.toHaveProperty('gitlabJobId')
}
})
})
describe('getGitLabPipelineNotLatestCommitSha', () => {
const head = 'b'.repeat(40)
const older = 'a'.repeat(40)
const pipeline = { id: 7, status: 'failed' }
it('names the commit a branch or detached MR pipeline ran on once the head moves past it', () => {
expect(
getGitLabPipelineNotLatestCommitSha({ ...pipeline, sha: older, ref: 'feature' }, head)
).toBe(older)
expect(
getGitLabPipelineNotLatestCommitSha(
{ ...pipeline, sha: older, ref: 'refs/merge-requests/7/head' },
head
)
).toBe(older)
expect(
getGitLabPipelineNotLatestCommitSha({ ...pipeline, sha: head, ref: 'feature' }, head)
).toBeUndefined()
})
it('claims nothing for merge-commit pipelines or when either commit is unknown', () => {
for (const ref of ['refs/merge-requests/7/merge', 'refs/merge-requests/7/train']) {
expect(
getGitLabPipelineNotLatestCommitSha({ ...pipeline, sha: older, ref }, head)
).toBeUndefined()
}
expect(
getGitLabPipelineNotLatestCommitSha({ ...pipeline, ref: 'feature' }, head)
).toBeUndefined()
expect(
getGitLabPipelineNotLatestCommitSha({ ...pipeline, sha: older, ref: 'feature' }, undefined)
).toBeUndefined()
})
})
@@ -1,54 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import * as byteLimits from '../../../utf8-byte-limits'
import { PR_CHECK_LOG_TAIL_BYTES } from './check-job-log-excerpt'
import { PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR, sliceCheckLogTail } from './check-job-log-tail-slice'
describe('check log excerpt byte-cap work', () => {
afterEach(() => vi.restoreAllMocks())
it.each(['recent', 'earlier'] as const)('bounds byte counting for a long %s line', (position) => {
const longLine = `error: ${'x'.repeat(2 * 1024 * 1024)}`
const input = position === 'recent' ? longLine : `${longLine}\n${'recent\n'.repeat(100)}`
const byteLength = vi.spyOn(byteLimits, 'getUtf8ByteLength')
const output = sliceCheckLogTail(input)
const countedUnits = byteLength.mock.calls.reduce((total, [text]) => total + text.length, 0)
expect(countedUnits).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES)
expect(Buffer.byteLength(output)).toBe(PR_CHECK_LOG_TAIL_BYTES)
if (position === 'recent') {
expect(output).toBe('x'.repeat(PR_CHECK_LOG_TAIL_BYTES))
} else {
expect(output.endsWith(PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR)).toBe(true)
expect(output).toContain('\nrecent\n')
}
})
it.each(['x', 'é', '界', '😀', '\ud83d', '\udc00'])(
'preserves byte boundaries for %j',
(unit) => {
const width = new TextEncoder().encode(unit).byteLength
for (const delta of [-1, 0, 1]) {
const count = Math.floor(PR_CHECK_LOG_TAIL_BYTES / width) + delta
const input = unit.repeat(count)
const output = sliceCheckLogTail(input)
expect(output).toBe(
unit.repeat(Math.min(count, Math.floor(PR_CHECK_LOG_TAIL_BYTES / width)))
)
expect(new TextEncoder().encode(output).byteLength).toBeLessThanOrEqual(
PR_CHECK_LOG_TAIL_BYTES
)
}
}
)
it('retains earlier multibyte context whose byte count exceeds its code-unit count', () => {
const failure = `error: ${'界'.repeat(6000)}`
const input = `${failure}\n${'recent\n'.repeat(103)}`
const prefix = `${failure}\nrecent\nrecent\n${PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR}`
expect(prefix.length).toBeLessThan(PR_CHECK_LOG_TAIL_BYTES)
expect(Buffer.byteLength(prefix)).toBeGreaterThan(PR_CHECK_LOG_TAIL_BYTES)
expect(sliceCheckLogTail(input)).toBe(
byteLimits.clampUtf8TextTail(prefix, PR_CHECK_LOG_TAIL_BYTES).text
)
})
})
@@ -1,12 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createCheckLogFixture } from '../../../../../config/scripts/performance/check-job-log/check-job-log-test-fixture.mjs'
import { PR_CHECK_LOG_TAIL_BYTES, sanitizeCheckJobLogExcerpt } from './check-job-log-excerpt'
import * as ansi from '../../../ansi-escape-sequences'
import { sanitizeCheckJobLogExcerpt } from './check-job-log-excerpt'
import * as ownership from '../../../own-retained-string'
import * as bytes from '../../../utf8-byte-limits'
const limit = PR_CHECK_LOG_TAIL_BYTES
const fixture = createCheckLogFixture()
describe('bounded owned check log sanitation', () => {
afterEach(() => {
@@ -21,87 +15,4 @@ describe('bounded owned check log sanitation', () => {
const raw = '\ufeff👨\u200d👩\u200d👧\u200d👦 می\u200cروم \u202eerror\u202c\u200b\n'
expect(sanitizeCheckJobLogExcerpt(raw)).toBe('👨\u200d👩\u200d👧\u200d👦 می\u200cروم error\n')
})
it('bounds raw text before ANSI, counting or copying, with no refill', () => {
const strip = vi.spyOn(ansi, 'stripAnsiEscapeSequences')
const count = vi.spyOn(bytes, 'getUtf8ByteLength')
const own = vi.spyOn(ownership, 'ownRetainedString')
const input = `${'omitted'.repeat(limit)}${'\x1b[31m'.repeat(4000)}LAST`
const result = sanitizeCheckJobLogExcerpt(input)
expect(result).toBe('LAST')
expect(strip).toHaveBeenCalledTimes(1)
expect(
strip.mock.calls.every(([value]) => bytes.measureUtf8ByteLength(value).byteLength <= limit)
).toBe(true)
expect(count).not.toHaveBeenCalled()
expect(own).toHaveBeenLastCalledWith('LAST')
strip.mockClear()
own.mockClear()
})
it.each(['x', 'é', '界', '😀', '\ud800', '\udfff'])(
'preserves precise byte edges for %j',
(unit) => {
const width = bytes.getUtf8ByteLength(unit)
for (const delta of [-1, 0, 1]) {
const count = Math.floor((limit + delta) / width)
const padding = 'x'.repeat((limit + delta) % width)
const input = unit.repeat(count) + padding
expect(bytes.getUtf8ByteLength(input)).toBe(limit + delta)
expect(sanitizeCheckJobLogExcerpt(input)).toBe(
unit.repeat(count - (delta > 0 ? 1 : 0)) + padding
)
}
}
)
it.each([
['\x1b[31m', '[31m'],
['\x1b]body', ']body'],
['\x1bPbody', 'Pbody'],
['\x1b_body', '_body'],
['\x1b^body', '^body'],
['\x1bXbody', 'Xbody']
])('uses fresh state when the raw tail cuts an introducer %j', (sequence, fragment) => {
const retained = fragment + 'x'.repeat(limit - fragment.length)
expect(
sanitizeCheckJobLogExcerpt(
`${'omitted'.repeat(limit)}${sequence}${'x'.repeat(limit - fragment.length)}`
)
).toBe(retained)
})
it('owns without Buffer and preserves source lone surrogates', () => {
vi.stubGlobal('Buffer', undefined)
ownership.resetOwnRetainedStringCopier()
try {
expect(sanitizeCheckJobLogExcerpt(`${'x'.repeat(20000)}\ud800a\udfff\n`)).toBe(
`${'x'.repeat(limit - 8)}\ud800a\udfff\n`
)
} finally {
vi.unstubAllGlobals()
ownership.resetOwnRetainedStringCopier()
}
})
it.each([
['\x1b', ''],
['\x1b[31', '31'],
['\x9b31', '31'],
['\x1b]body\x1b', 'body'],
['\x9dbody', 'body'],
['\x1bPbody\x1b', 'body'],
['\x90body', 'body'],
['payload\x1b\\TAIL', 'payloadTAIL'],
['payload\x9cTAIL', 'payloadTAIL']
])('keeps literal fragments at a cut %j', (suffix, expected) => {
expect(sanitizeCheckJobLogExcerpt(suffix)).toBe(expected)
expect(sanitizeCheckJobLogExcerpt(`${'z'.repeat(2 * limit)}${suffix}`)).toBe(
`${'z'.repeat(limit - bytes.getUtf8ByteLength(suffix))}${expected}`
)
})
it('keeps failure diagnostic and nearby stack', () => {
const result = sanitizeCheckJobLogExcerpt(fixture.rawLog)
expect(result).toContain(fixture.expectedDiagnostic)
expect(result).toContain(fixture.expectedStackFrame)
expect(result).toContain(fixture.benignMarker)
expect(result).toContain(fixture.genericExitMarker)
expect(ansi.TERMINAL_CONTROL_CHARACTER_PATTERN.test(result)).toBe(false)
expect(sanitizeCheckJobLogExcerpt(result)).toBe(result)
})
})
@@ -1,139 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import * as ansi from '../../../ansi-escape-sequences'
import * as byteLimits from '../../../utf8-byte-limits'
import { createCheckLogFixture } from '../../../../../config/scripts/performance/check-job-log/check-job-log-test-fixture.mjs'
import { PR_CHECK_LOG_TAIL_BYTES } from './check-job-log-excerpt'
import { PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR, sliceCheckLogTail } from './check-job-log-tail-slice'
const trailing = Array.from({ length: 210 }, (_, index) => `recent ${index}`).join('\n')
const fixture = createCheckLogFixture()
const earlier = (line: string): string => `${line}\n${trailing}`
describe('bounded ANSI-aware marker candidates', () => {
afterEach(() => vi.restoreAllMocks())
it.each([
'##[error]',
'::error::',
'::error',
'error:',
'FAILED',
'exit code',
'ENOENT',
'EACCES',
'panic:',
'AssertionError'
])('recognizes interrupted and surrounded %s before recent lines', (marker) => {
for (const color of ['\x1b[31m', '\x9b31m']) {
const line = `unique ${color}${marker.slice(0, 3)}${color}${marker.slice(3)}\x1b[0m`
expect(sliceCheckLogTail(earlier(line))).toContain(`unique ${marker}`)
expect(sliceCheckLogTail(earlier(line))).toContain(PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR)
}
})
it.each(['\x1b]', '\x9d', '\x1bP', '\x90', '\x1b_', '\x9f', '\x1b^', '\x9e', '\x1bX', '\x98'])(
'ignores invisible markers in complete %j payloads',
(intro) => {
const input = earlier(`hidden ${intro}error: invisible\x1b\\ suffix`)
expect(sliceCheckLogTail(input)).not.toContain(PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR)
}
)
it.each([
['er', 'ror:'],
['::er', 'ror::'],
['er\x1b', '[31mror:'],
['::er\x1b[31m', 'ror::']
])('does not join independent %j/%j windows', (left, right) => {
const window = PR_CHECK_LOG_TAIL_BYTES / 2
const line = `${'x'.repeat(window - left.length)}${left}${'m'.repeat(20000)}${right}${'x'.repeat(window - right.length)}`
expect(sliceCheckLogTail(earlier(line))).not.toContain(PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR)
})
it.each(['prefix', 'tail', 'middle'] as const)(
'limits oversized %s markers to independent edges',
(position) => {
const marker = 'error: EDGE'
const line =
position === 'prefix'
? `${marker}${'x'.repeat(40000)}`
: position === 'tail'
? `${'x'.repeat(40000)} ${marker}`
: `${'x'.repeat(20000)} ${marker}${'x'.repeat(20000)}`
expect(sliceCheckLogTail(earlier(line)).includes(PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR)).toBe(
position !== 'middle'
)
}
)
it.each(['x', '界', '😀', '\ud800', '\udfff'])(
'bounds actual normalization and marker inputs for %j',
(unit) => {
const input = earlier(`error: ${unit.repeat(20000)}`)
const strip = vi.spyOn(ansi, 'stripAnsiEscapeSequences')
const count = vi.spyOn(byteLimits, 'getUtf8ByteLength')
const fit = vi.spyOn(byteLimits, 'isUtf8ByteLengthWithinLimit')
const test = RegExp.prototype.test
const matcherBytes: number[] = []
const pattern = vi.spyOn(RegExp.prototype, 'test').mockImplementation(function (
this: RegExp,
value: string
) {
if (this.source.includes('AssertionError')) {
matcherBytes.push(byteLimits.measureUtf8ByteLength(value).byteLength)
}
return test.call(this, value)
})
try {
const output = sliceCheckLogTail(input)
const normalized = strip.mock.calls.map(
([value]) => byteLimits.measureUtf8ByteLength(value).byteLength
)
expect(Math.max(...normalized)).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES)
expect(normalized.slice(0, -1).every((bytes) => bytes <= PR_CHECK_LOG_TAIL_BYTES / 2)).toBe(
true
)
expect(Math.max(...matcherBytes)).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES / 2)
expect(count.mock.calls.every(([value]) => value.length <= PR_CHECK_LOG_TAIL_BYTES)).toBe(
true
)
expect(fit.mock.calls.every(([, limit]) => limit === PR_CHECK_LOG_TAIL_BYTES)).toBe(true)
expect(byteLimits.measureUtf8ByteLength(output).byteLength).toBeLessThanOrEqual(
PR_CHECK_LOG_TAIL_BYTES
)
} finally {
strip.mockClear()
count.mockClear()
fit.mockClear()
pattern.mockRestore()
}
}
)
it('preserves failure context in recent and generated earlier modes', () => {
const recent = sliceCheckLogTail(fixture.rawLog)
expect(recent).toContain(fixture.expectedDiagnostic)
expect(recent).toContain(fixture.expectedStackFrame)
const rawRows = fixture.rawLog.split('\n')
const diagnostic =
rawRows.find((line) =>
ansi.stripAnsiEscapeSequences(line).includes(fixture.expectedDiagnostic)
) ?? ''
const frame = rawRows.find((line) => line.includes(fixture.expectedStackFrame)) ?? ''
const output = sliceCheckLogTail(`${diagnostic}\n${frame}\n${trailing}`)
expect(output).toContain(fixture.expectedDiagnostic)
expect(output).toContain(fixture.expectedStackFrame)
expect(output).toContain(PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR)
})
it.each(['\n', '\r\n', '\r'])(
'splits raw %j while preserving selection and trailing empty entry',
(separator) => {
const rows = [
'first',
'error: retained',
'',
...Array.from({ length: 210 }, (_, i) => `row ${i}`),
''
]
expect(sliceCheckLogTail(rows.join(separator))).toBe(sliceCheckLogTail(rows.join('\n')))
expect(sliceCheckLogTail(`a${separator}${separator}b${separator}`)).toBe('a\n\nb\n')
}
)
it('handles mixed CR/CRLF/LF without merging lines', () => {
expect(sliceCheckLogTail('a\rb\r\nc\n\r\nd\r')).toBe('a\nb\nc\n\nd\n')
})
})
@@ -1,721 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createHash } from 'node:crypto'
import {
auditResults,
prepareBenchmark,
runDescriptor
} from '../../../../../config/scripts/performance/check-job-log/check-job-log-byte-cap-benchmark.mjs'
import {
BASELINE_REF,
createManifest,
selectRequiredDescriptors
} from '../../../../../config/scripts/performance/check-job-log/check-job-log-performance-cases.mjs'
import { adverseCaseKey } from '../../../../../config/scripts/performance/check-job-log/check-job-log-watchdog-protocol.mjs'
const launcher = vi.hoisted(() => vi.fn())
vi.mock('@orca/process-host', () => ({ runProcess: launcher }))
afterEach(() => {
launcher.mockReset()
context.censoredBaselines?.clear()
vi.unstubAllEnvs()
})
const context = {
censoredBaselines: new Map(),
root: process.cwd(),
identity: {
baselineRef: BASELINE_REF,
baselineSourceHashes: { ansi: 'frozen' },
proposedSourceHashes: { ansi: 'current' }
},
bundles: {
'baseline-negative': { filename: 'baseline.mjs', hash: 'negative-bundle' },
baseline: { filename: 'baseline.mjs', hash: 'baseline-bundle' },
proposed: { filename: 'proposed.mjs', hash: 'proposed-bundle' }
}
}
const adverse = {
id: 'negative-case',
mode: 'direct',
arm: 'baseline',
family: 'osc',
width: 7,
bytes: 16384,
samples: 7,
sample: 0,
baselineTimeoutAllowed: true
}
const ready = (id = adverse.id, bundleHash = context.bundles['baseline-negative'].hash) => ({
type: 'ready',
identity: { ...context.identity, id, bundleHash },
runtime: { node: process.version, platform: process.platform, arch: process.arch, bun: false },
inputBytes: 16384,
codeUnits: 16384,
inputHash: createHash('sha256').update('x'.repeat(16384)).digest('hex')
})
const protocol = (records: unknown[]): string =>
`${records.map((record) => JSON.stringify(record)).join('\n')}\n`
const timeoutResult = () => ({
code: null,
signal: 'SIGTERM',
timedOut: true,
outputTruncated: false,
stderr: '',
stdout: protocol([ready(), { type: 'entered-strip', phase: 'warmup' }])
})
const watchdogExits = [
{ label: 'SIGTERM', signal: 'SIGTERM', code: null, accepted: true },
{ label: 'SIGKILL', signal: 'SIGKILL', code: null, accepted: true },
{ label: 'numeric one', signal: null, code: 1, accepted: false },
{ label: 'numeric two', signal: null, code: 2, accepted: false },
{ label: 'maximum safe integer', signal: null, code: Number.MAX_SAFE_INTEGER, accepted: false },
{ label: 'unsigned access violation', signal: null, code: 3221225477, accepted: false },
{ label: 'signed access violation', signal: null, code: -1073741819, accepted: false },
{ label: 'fractional code', signal: null, code: 1.5, accepted: false },
{ label: 'zero code', signal: null, code: 0, accepted: false },
{ label: 'null/null', signal: null, code: null, accepted: false },
{ label: 'unexpected signal', signal: 'SIGSEGV', code: null, accepted: false },
{ label: 'unexpected signal/code', signal: 'SIGSEGV', code: 1, accepted: false },
{ label: 'SIGINT', signal: 'SIGINT', code: null, accepted: false },
{ label: 'SIGTERM/code', signal: 'SIGTERM', code: 1, accepted: false },
{ label: 'SIGKILL/code', signal: 'SIGKILL', code: 2, accepted: false }
] as const
const adverseSlots = () =>
Array.from({ length: 7 }, (_, sample) => ({
...adverse,
id: sample ? `slot-${sample}` : adverse.id,
samples: 1,
sample
}))
const differentials = ['baseline', 'proposed'].map((arm) => ({
id: `diff-${arm}`,
mode: 'differential',
arm
}))
const differentialRecords = differentials.map((item) => ({
...item,
status: 'completed',
cases: 5126,
outputHash: 'same'
}))
const watchdog = { id: 'watchdog', mode: 'watchdog', arm: 'proposed' }
const terminationProtocol = (descriptor: typeof adverse | typeof watchdog, platform: string) =>
protocol([
{
...ready(
descriptor.id,
context.bundles[descriptor.mode === 'direct' ? 'baseline-negative' : 'proposed'].hash
),
runtime: { node: process.version, platform, arch: 'x64', bun: false }
},
{
type: descriptor.mode === 'direct' ? 'entered-strip' : 'entered',
phase: descriptor.mode === 'direct' ? 'warmup' : 'watchdog'
}
])
const malformedProtocols = (descriptor: typeof adverse | typeof watchdog) => {
const prework = ready(
descriptor.id,
context.bundles[descriptor.mode === 'direct' ? 'baseline-negative' : 'proposed'].hash
)
const entry = {
type: descriptor.mode === 'direct' ? 'entered-strip' : 'entered',
phase: descriptor.mode === 'direct' ? 'warmup' : 'watchdog'
}
const result = {
type: 'result',
id: descriptor.id,
mode: descriptor.mode,
arm: descriptor.arm,
inputIdentity: {
inputBytes: prework.inputBytes,
codeUnits: prework.codeUnits,
inputHash: prework.inputHash
}
}
return [
{ label: 'wrong result id', records: [prework, entry, { ...result, id: 'wrong' }] },
{ label: 'wrong result mode', records: [prework, entry, { ...result, mode: 'wrong' }] },
{ label: 'wrong result arm', records: [prework, entry, { ...result, arm: 'wrong' }] },
{ label: 'wrong result input', records: [prework, entry, { ...result, inputIdentity: {} }] },
{ label: 'duplicate ready', records: [prework, prework, entry] },
{
label: 'mismatched second ready',
records: [prework, { ...prework, identity: { ...prework.identity, id: 'wrong' } }, entry]
},
{ label: 'entry before ready', records: [entry, prework] },
{ label: 'duplicate result', records: [prework, entry, result, result] },
{ label: 'result before entry', records: [prework, result, entry] },
{ label: 'completed timeout', records: [prework, entry, result] },
{ label: 'duplicate entry', records: [prework, entry, entry] },
{
label: 'pre-call after strip entry',
records: [prework, entry, { type: 'entered', phase: 'warmup', warmup: 0 }]
},
{
label: 'invalid warmup index',
records: [prework, { type: 'entered', phase: 'warmup', warmup: -1 }, entry]
},
{
label: 'sample before warmups',
records: [prework, { type: 'entered', phase: 'sample', sample: 0 }, entry]
},
{ label: 'unknown entry', records: [prework, { ...entry, type: 'unknown' }, entry] },
{ label: 'invalid entry phase', records: [prework, { ...entry, phase: 'startup' }] },
{ label: 'null record', records: [prework, null, entry] },
{
label: 'truthy malformed runtime',
records: [
{ ...prework, runtime: { node: 'not-node', platform: 42, arch: {}, bun: 0 } },
entry
]
},
...[
{ node: 'not-node' },
{ node: 26 },
{ platform: 42 },
{ arch: {} },
{ bun: 0 },
{ bun: true },
{ platform: '' },
{ arch: '' }
].map((runtime) => ({
label: `invalid runtime ${Object.keys(runtime)[0]}=${JSON.stringify(Object.values(runtime)[0])}`,
records: [{ ...prework, runtime: { ...prework.runtime, ...runtime } }, entry]
}))
]
}
describe('performance watchdog failure precedence and completeness', () => {
it('prepares current implementation checks without Git history', async () => {
const prepared = await prepareBenchmark(process.cwd(), { compareBaseline: false })
try {
expect(launcher).not.toHaveBeenCalled()
expect(Object.keys(prepared.bundles).sort()).toEqual(['proposed', 'proposed-observed'])
expect(prepared.identity.baselineSourceHashes).toEqual({})
} finally {
await prepared.cleanup()
}
})
it('rejects changed historical source in the manual comparison', async () => {
const success = { code: 0, signal: null, timedOut: false, outputTruncated: false }
launcher.mockResolvedValueOnce({ ...success, stdout: 'changed historical ANSI source' })
await expect(prepareBenchmark()).rejects.toThrow(
'Baseline source changed: ansi-escape-sequences.ts'
)
expect(launcher).toHaveBeenCalledTimes(1)
})
describe.each(['adverse', 'watchdog'])('%s protocol framing', (branch) => {
const descriptor = branch === 'adverse' ? adverse : watchdog
it.each(malformedProtocols(descriptor))(
'rejects $label before timeout acceptance',
async (fixture) => {
launcher.mockResolvedValue({ ...timeoutResult(), stdout: protocol(fixture.records) })
await expect(runDescriptor(context, descriptor)).rejects.toThrow()
expect(context.censoredBaselines.size).toBe(0)
}
)
})
it.each(malformedProtocols(adverse))(
'$label cannot suppress later attempts or pass audit',
async (fixture) => {
const slots = adverseSlots()
const records: object[] = []
launcher.mockResolvedValue({ ...timeoutResult(), stdout: protocol(fixture.records) })
await expect(runDescriptor(context, slots[0])).rejects.toThrow()
records.push({ ...slots[0], status: 'failed' })
for (const slot of slots.slice(1)) {
launcher.mockResolvedValue({
...timeoutResult(),
stdout: terminationProtocol(slot, 'darwin')
})
records.push(await runDescriptor(context, slot))
}
expect(launcher).toHaveBeenCalledTimes(7)
expect(records.slice(1).every((record) => Object.hasOwn(record, 'watchdogTermination'))).toBe(
true
)
expect(context.censoredBaselines.size).toBe(0)
expect(() =>
auditResults([...slots, ...differentials], [...records, ...differentialRecords])
).toThrow('Failed descriptor')
}
)
it.each(['warmup', 'sample'])('preserves a verified partial %s strip entry', async (phase) => {
launcher.mockResolvedValue({
...timeoutResult(),
stdout: protocol([ready(), { type: 'entered-strip', phase }])
})
const record = await runDescriptor(context, adverse)
expect(record.status).toBe('baseline_timeout')
expect(record.samples).toEqual([])
expect(record.unavailableSamples).toBe(7)
expect(record.deadlineMs).toBe(10000)
expect(launcher).toHaveBeenCalledWith(
expect.objectContaining({
timeoutMs: 10000,
maxOutputBytes: 65536,
env: expect.objectContaining({ ORCA_BACKGROUND_LAUNCH: '1' })
})
)
})
it.each([
'startup',
'identity',
'truncated',
'stderr',
'crash',
'unexpected-signal',
'pre-call-only'
])('rejects %s failures rather than labeling them baseline timeouts', async (failure) => {
const result = timeoutResult()
if (failure === 'startup') {
result.stdout = ''
}
if (failure === 'identity') {
result.stdout = protocol([ready('wrong-case'), { type: 'entered-strip', phase: 'warmup' }])
}
if (failure === 'truncated') {
result.outputTruncated = true
}
if (failure === 'stderr') {
result.stderr = 'sentinel fixture construction failure'
}
if (failure === 'crash') {
result.timedOut = false
result.signal = 'SIGSEGV'
}
if (failure === 'unexpected-signal') {
result.signal = 'SIGSEGV'
}
if (failure === 'pre-call-only') {
result.stdout = protocol([ready(), { type: 'entered', phase: 'warmup' }])
}
launcher.mockResolvedValue(result)
await expect(runDescriptor(context, adverse)).rejects.toThrow()
})
it.each(['proposed', 'ordinary-baseline'])('rejects %s workload timeouts', async (arm) => {
const baseline = arm === 'ordinary-baseline'
const descriptor = {
...adverse,
arm: baseline ? 'baseline' : 'proposed',
baselineTimeoutAllowed: false
}
launcher.mockResolvedValue({
...timeoutResult(),
stdout: protocol([
ready(descriptor.id, context.bundles[baseline ? 'baseline' : 'proposed'].hash),
{ type: 'entered', phase: 'warmup', warmup: 0 }
])
})
await expect(runDescriptor(context, descriptor)).rejects.toThrow(
'Workload child failed or timed out'
)
})
it('censors only remaining slots of the exact verified initial adverse timeout', async () => {
const initial = { ...adverse, samples: 1 }
launcher.mockResolvedValue(timeoutResult())
await runDescriptor(context, initial)
const later = { ...initial, id: 'later-slot', sample: 1 }
const record = await runDescriptor(context, later)
expect(record).toMatchObject({
status: 'baseline_censored',
attempted: false,
initialTimeoutId: initial.id,
unavailableSamples: 1,
samples: []
})
expect(launcher).toHaveBeenCalledTimes(1)
expect(record).not.toHaveProperty('settlementMs')
launcher.mockResolvedValue({ ...timeoutResult(), stdout: '' })
await expect(runDescriptor(context, { ...later, bytes: 32768 })).rejects.toThrow()
expect(launcher).toHaveBeenCalledTimes(2)
})
it('audits seven logical adverse slots and their initial termination proof', async () => {
const slots = Array.from({ length: 7 }, (_, sample) => ({
...adverse,
id: sample ? `slot-${sample}` : adverse.id,
samples: 1,
sample
}))
launcher.mockResolvedValue(timeoutResult())
const records: Awaited<ReturnType<typeof runDescriptor>>[] = []
for (const slot of slots) {
records.push(await runDescriptor(context, slot))
}
const differentials = ['baseline', 'proposed'].map((arm) => ({
id: `diff-${arm}`,
mode: 'differential',
arm
}))
const results = [
...records,
...differentials.map((item) => ({
...item,
status: 'completed',
cases: 5126,
outputHash: 'same'
}))
]
const summary = auditResults([...slots, ...differentials], results)
expect(summary).toMatchObject({
descriptors: 9,
attemptedDescriptors: 3,
censoredSampleSlots: 6,
censoredBaselines: 1
})
expect(() =>
auditResults(
[...slots, ...differentials],
results.map((item) => (item.id === adverse.id ? { ...item, phase: 'startup' } : item))
)
).toThrow()
expect(() =>
auditResults(
[...slots, ...differentials],
results.map((item) =>
item.id === 'slot-1' ? { ...item, initialTimeoutId: 'missing' } : item
)
)
).toThrow('Missing verified initial')
})
describe.each(['win32', 'linux', 'darwin'])('%s watchdog evidence', (platform) => {
describe.each(['adverse', 'watchdog'])('%s classifier and parent audit', (mode) => {
it.each(watchdogExits)(
'classifies $label through the actual launcher result',
async (exit) => {
const descriptor = mode === 'adverse' ? adverse : watchdog
launcher.mockResolvedValue({
...timeoutResult(),
code: exit.code,
signal: exit.signal,
stdout: terminationProtocol(descriptor, platform)
})
if (exit.accepted) {
expect((await runDescriptor(context, descriptor)).status).toBe(
mode === 'adverse' ? 'baseline_timeout' : 'watchdog_passed'
)
} else {
await expect(runDescriptor(context, descriptor)).rejects.toThrow(
'Unverified watchdog termination'
)
expect(context.censoredBaselines.size).toBe(0)
}
}
)
it.each(watchdogExits)('audits independently constructed $label records', (exit) => {
const slots = adverseSlots()
const input = ready()
const initial = {
...slots[0],
status: 'baseline_timeout',
attempted: true,
phase: 'warmup',
deadlineMs: 10000,
settlementMs: 10001,
identity: input.identity,
runtime: { ...input.runtime, platform },
inputBytes: input.inputBytes,
codeUnits: input.codeUnits,
inputHash: input.inputHash,
watchdogTermination: { timedOut: true, signal: exit.signal, code: exit.code },
unavailableSamples: 1,
samples: []
}
const manifest = mode === 'adverse' ? slots : [watchdog]
const records =
mode === 'adverse'
? slots.map((slot) => ({
...initial,
...slot,
identity: { ...initial.identity, id: slot.id },
...(slot.sample
? {
status: 'baseline_censored',
attempted: false,
initialTimeoutId: initial.id
}
: {})
}))
: [
{
...watchdog,
status: 'watchdog_passed',
attempted: true,
settlementMs: initial.settlementMs,
identity: { ...input.identity, id: watchdog.id },
runtime: initial.runtime,
code: exit.code,
signal: exit.signal,
watchdogTermination: initial.watchdogTermination
}
]
const audit = () =>
auditResults([...manifest, ...differentials], [...records, ...differentialRecords])
if (exit.accepted) {
expect(audit().descriptors).toBe(manifest.length + 2)
} else {
expect(audit).toThrow('Unverified watchdog termination')
}
})
})
})
it.each(watchdogExits)(
'revalidates cached initial $label evidence before censoring',
async (exit) => {
const input = ready()
const initial = {
...adverse,
status: 'baseline_timeout',
attempted: true,
phase: 'warmup',
identity: input.identity,
runtime: input.runtime,
inputBytes: input.inputBytes,
codeUnits: input.codeUnits,
inputHash: input.inputHash,
deadlineMs: 10000,
settlementMs: 10001,
watchdogTermination: { timedOut: true, signal: exit.signal, code: exit.code }
}
context.censoredBaselines.set(adverseCaseKey(adverse), initial)
const run = runDescriptor(context, { ...adverse, id: 'cached-slot', samples: 1, sample: 1 })
if (exit.accepted) {
expect(await run).toMatchObject({ status: 'baseline_censored', attempted: false })
} else {
await expect(run).rejects.toThrow('Unverified watchdog termination')
}
expect(launcher).not.toHaveBeenCalled()
}
)
it.each(watchdogExits.filter((exit) => !exit.accepted))(
'an initial $label failure leaves all seven slots attempted',
async (exit) => {
for (const slot of adverseSlots()) {
launcher.mockResolvedValue({
...timeoutResult(),
code: exit.code,
signal: exit.signal,
stdout: terminationProtocol(slot, 'win32')
})
await expect(runDescriptor(context, slot)).rejects.toThrow(
'Unverified watchdog termination'
)
}
expect(launcher).toHaveBeenCalledTimes(7)
expect(context.censoredBaselines.size).toBe(0)
}
)
it.each(['adverse', 'watchdog'])(
'rejects every %s exit without a fired watchdog',
async (mode) => {
const descriptor = mode === 'adverse' ? adverse : watchdog
for (const exit of watchdogExits) {
launcher.mockResolvedValue({
...timeoutResult(),
timedOut: false,
code: exit.code,
signal: exit.signal,
stdout: terminationProtocol(descriptor, 'win32')
})
await expect(runDescriptor(context, descriptor)).rejects.toThrow()
}
expect(context.censoredBaselines.size).toBe(0)
}
)
it('audits the actual self-control record and rejects altered status or exit fields', async () => {
launcher.mockResolvedValue({
...timeoutResult(),
stdout: terminationProtocol(watchdog, 'win32')
})
const record = await runDescriptor(context, watchdog)
const manifest = [watchdog, ...differentials]
expect(auditResults(manifest, [record, ...differentialRecords]).descriptors).toBe(3)
for (const altered of [
{ ...record, status: 'completed' },
{ ...record, code: 1 },
{ ...record, signal: 'SIGSEGV' }
]) {
expect(() => auditResults(manifest, [altered, ...differentialRecords])).toThrow()
}
})
it('alternates seven parent-selected pairs at every direct size', () => {
const direct = createManifest().filter(
(item) => item.mode === 'direct' && item.family === 'plain'
)
for (let pair = 0; pair < direct.length; pair += 28) {
const sizes = direct.slice(pair, pair + 2).map((item) => item.bytes)
for (let sample = 0; sample < 7; sample++) {
const expectedArms = sample % 2 ? ['baseline', 'proposed'] : ['proposed', 'baseline']
const expectedSizes = sample % 2 ? sizes.toReversed() : sizes
expect(
direct
.slice(pair + sample * 4, pair + sample * 4 + 4)
.map((item) => [item.arm, item.bytes, item.sample, item.samples])
).toEqual(
expectedArms.flatMap((arm) => expectedSizes.map((bytes) => [arm, bytes, sample, 1]))
)
}
}
})
it('predeclares full proposed coverage before adverse baseline descriptors', () => {
const manifest = createManifest()
const firstBaseline = manifest.findIndex((item) => item.arm === 'baseline')
const lastCoverage = manifest.findLastIndex((item) => item.mode === 'coverage')
expect(lastCoverage).toBeLessThan(firstBaseline)
expect(new Set(manifest.map((item) => item.id)).size).toBe(manifest.length)
expect(
manifest
.filter((item) => item.baselineTimeoutAllowed)
.every(
(item) =>
item.arm === 'baseline' &&
item.mode === 'direct' &&
['osc', 'dcs', 'apc', 'pm', 'sos'].includes(item.family)
)
).toBe(true)
expect(
manifest.some(
(item) =>
item.mode === 'coverage' &&
item.bytes === 63 * 1024 * 1024 &&
item.width === 8 &&
item.position === 'earlier'
)
).toBe(true)
})
it('selects the required ordered 944 or 1004 descriptors with complete measurement groups', () => {
const full = createManifest({ capturePath: 'capture.stdout' })
const selected = selectRequiredDescriptors(full)
expect(selected).toHaveLength(1004)
expect(selectRequiredDescriptors(createManifest())).toHaveLength(944)
expect(full.filter((descriptor) => selected.includes(descriptor))).toEqual(selected)
const coverage = selected.filter((descriptor) => descriptor.mode === 'coverage')
const expectedCoverage = ['osc', 'dcs', 'apc', 'pm', 'sos'].flatMap((family) =>
[7, 8].flatMap((width) =>
[16384, 32768, 2 * 1024 * 1024, 63 * 1024 * 1024].flatMap((bytes) =>
['earlier', 'tail'].map((position) => [family, width, bytes, position])
)
)
)
expect(
coverage.map(({ family, width, bytes, position }) => [family, width, bytes, position])
).toEqual(expectedCoverage)
expect(coverage.every((descriptor) => descriptor.variant === 'unfinished')).toBe(true)
expect(selected.filter((descriptor) => descriptor.mode === 'counts')).toHaveLength(52)
expect(selected.filter((descriptor) => descriptor.mode === 'retention')).toHaveLength(7)
for (const family of ['fixture', 'actual']) {
expect(
selected.filter((descriptor) => descriptor.mode === 'cpu' && descriptor.family === family)
).toHaveLength(60)
}
for (const arm of ['baseline', 'proposed', 'baseline-bounded', 'full-log']) {
expect(
selected.filter((descriptor) => descriptor.mode === 'cpu' && descriptor.arm === arm)
).toHaveLength(40)
}
const direct = selected.filter((descriptor) => descriptor.mode === 'direct')
expect(direct.filter((descriptor) => descriptor.arm === 'baseline')).toHaveLength(280)
expect(
direct.filter((descriptor) => descriptor.arm === 'proposed' && descriptor.bytes <= 32768)
).toHaveLength(280)
expect(direct.filter((descriptor) => descriptor.bytes > 32768)).toHaveLength(140)
const groups = new Map<string, typeof direct>()
for (const descriptor of direct) {
const key = JSON.stringify([descriptor.arm, descriptor.family, descriptor.width])
groups.set(key, [...(groups.get(key) ?? []), descriptor])
}
for (const group of groups.values()) {
const sizes = [...new Set(group.map((descriptor) => descriptor.bytes))].sort(
(a, b) => Number(a) - Number(b)
)
expect(sizes.slice(0, 2)).toEqual([16384, 32768])
if (sizes.length > 2) {
expect(sizes.slice(2)).toEqual([31.5 * 1024 * 1024, 63 * 1024 * 1024])
}
for (const bytes of sizes) {
expect(
group
.filter((descriptor) => descriptor.bytes === bytes)
.map((descriptor) => descriptor.sample)
).toEqual([0, 1, 2, 3, 4, 5, 6])
}
}
})
it('fails missing records and never turns an ordinary failure into completed coverage', () => {
expect(() => auditResults([adverse], [])).toThrow('Incomplete')
expect(() => auditResults([adverse], [{ id: adverse.id, status: 'failed' }])).toThrow(
'Failed descriptor'
)
})
it('rejects extra, duplicate, unexpected records and duplicate manifest IDs explicitly', () => {
const record = { id: adverse.id, status: 'baseline_timeout' }
expect(() => auditResults([adverse], [record, record])).toThrow('duplicate descriptor')
expect(() => auditResults([adverse, { ...adverse, id: 'other' }], [record, record])).toThrow(
'duplicate descriptor'
)
expect(() => auditResults([adverse], [{ ...record, id: 'unexpected' }])).toThrow(
'Unexpected descriptor'
)
expect(() => auditResults([adverse, adverse], [record, record])).toThrow('Duplicate manifest')
})
it.each(['bytes', 'units', 'hash'])(
'rejects invalid pre-work input %s identities',
async (field) => {
const identity = ready()
if (field === 'bytes') {
identity.inputBytes++
}
if (field === 'units') {
identity.codeUnits = -1
}
if (field === 'hash') {
identity.inputHash = 'unverified'
}
launcher.mockResolvedValue({
...timeoutResult(),
stdout: protocol([identity, { type: 'entered-strip', phase: 'warmup' }])
})
await expect(runDescriptor(context, adverse)).rejects.toThrow()
}
)
it('validates completion input identity against the pre-work protocol', async () => {
const descriptor = { id: 'control', mode: 'control', arm: 'proposed' }
const prework = ready(descriptor.id, context.bundles.proposed.hash)
const inputIdentity = {
inputBytes: prework.inputBytes,
codeUnits: prework.codeUnits,
inputHash: prework.inputHash
}
launcher.mockResolvedValue({
...timeoutResult(),
timedOut: false,
code: 0,
signal: null,
stdout: protocol([prework, { type: 'result', ...descriptor, samples: [], inputIdentity }])
})
expect(await runDescriptor(context, descriptor)).toMatchObject({
...inputIdentity,
status: 'completed'
})
launcher.mockResolvedValue({
...timeoutResult(),
timedOut: false,
code: 0,
signal: null,
stdout: protocol([
prework,
{
type: 'result',
...descriptor,
samples: [],
inputIdentity: { ...inputIdentity, codeUnits: 1 }
}
])
})
await expect(runDescriptor(context, descriptor)).rejects.toThrow(
'Completion input identity changed'
)
})
})
@@ -3,61 +3,6 @@ import { PR_CHECK_LOG_TAIL_BYTES } from './check-job-log-excerpt'
import { PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR, sliceCheckLogTail } from './check-job-log-tail-slice'
describe('sliceCheckLogTail', () => {
it.each([1, 2, 3, 5, 7, 11, 31, 100])(
'preserves the newest 30 earlier context lines with errors every %i lines',
(spacing) => {
const lines = Array.from({ length: 500 }, (_, index) =>
index % spacing === 0 ? `error: failure ${index}` : `line ${index}`
)
const selected = new Set<number>()
for (let error = 0; error < 400; error += spacing) {
for (let offset = -2; offset <= 2; offset++) {
if (error + offset >= 0 && error + offset < 400) {
selected.add(error + offset)
}
}
}
const context = [...selected].sort((a, b) => a - b).slice(-30)
expect(sliceCheckLogTail(lines.join('\n'))).toBe(
[
...context.map((index) => lines[index]),
PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR,
...lines.slice(400)
].join('\n')
)
}
)
it('keeps the recent tail when no earlier error markers are present', () => {
const logLines = Array.from({ length: 210 }, (_, index) => `line ${index}`)
const sliced = sliceCheckLogTail(logLines.join('\n'))
expect(sliced).toContain('line 209')
expect(sliced).not.toContain('line 0')
expect(Buffer.from(sliced, 'utf8').byteLength).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES)
})
it('pulls earlier error lines into the excerpt when the recent tail is noisy', () => {
const noisyPrefix = Array.from({ length: 120 }, (_, index) => `Setting up package-${index}`)
const failure = '##[error]Process completed with exit code 236.'
const noisySuffix = Array.from({ length: 100 }, (_, index) => `Running trigger ${index}`)
const sliced = sliceCheckLogTail([...noisyPrefix, failure, ...noisySuffix].join('\n'))
expect(sliced).toContain(failure)
expect(sliced).toContain(PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR)
expect(sliced).toContain('Running trigger 39')
expect(sliced).not.toContain('Setting up package-0')
expect(Buffer.from(sliced, 'utf8').byteLength).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES)
})
it('caps a large multiline recent tail', () => {
const logLines = Array.from({ length: 220 }, (_, index) => `line ${index} ${'x'.repeat(120)}`)
const sliced = sliceCheckLogTail(logLines.join('\n'))
expect(sliced).toContain('line 219')
expect(Buffer.from(sliced, 'utf8').byteLength).toBeLessThanOrEqual(PR_CHECK_LOG_TAIL_BYTES)
})
it('keeps earlier error context when the recent tail is larger than the byte cap', () => {
const noisyPrefix = Array.from({ length: 120 }, (_, index) => `Installing package ${index}`)
const failure = 'AssertionError: expected visible failure'