Files
deepseek-harness/packages/api/session-controller/tests/session-skills.host.spec.ts
T
sjw1231 e2f1208bcf Merge origin/master into feat/apply-patch
Regenerate config/tool/module/event catalogs, Cordis API and client slot catalogs; re-record reviewed bilingual hashes instead of merging generated bytes.

Accept deleted filesystem invariant companions. Master has no replacement event-invariant registration; keep delete-intent in typed events, policy guards, and behavior tests.

Adopt master workspace-changes intent waterfalls and tool-execution recorder association, add a prepended delete-intent listener that delegates before capture, remove argument parsing and the fs-patch dependency, and retain the real-tool Review matrix.

Keep master filesystem mutation-result metadata and tool switches alongside opt-in apply_patch. Await current-directory resolution in plan and no-follow preflight; store patch diffs as processPath. Adapt native/PTC fixtures to the supported modes.

Preserve client patch diffs and stopped states with master partial arguments and absolute navigation. Use master's rewritten ProviderEditor, including its remaining repeated model validation.

Regenerate the lockfile with pnpm install and align the new fs-patch package version. Clean retired package build outputs. Update exact rescope exceptions for verified preset and event identifiers from master; old package names remain rejected.
2026-10-16 11:51:43 +08:00

287 lines
12 KiB
TypeScript

import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import { Context } from '@deepseek-ai/cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit'
import type { Agent } from '@deepseek-ai/dsh-agent'
import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query'
import type {} from '@deepseek-ai/dsh-skill'
import { describe, expect, it, vi } from 'vitest'
import { SessionSkillCatalog } from '../src/skill-catalog.ts'
function observation(
sessionId: SessionId,
options: { readonly cwd?: string; readonly workingDirectory?: string | null; readonly agentPreset?: string } = {},
): SessionObservation {
const events = Object.freeze([])
const lease = (): SessionObservation => ({
source: 'live',
header: {
version: SESSION_FORMAT_VERSION,
id: sessionId,
createdAt: 1,
isSeeded: false,
...options.cwd === undefined ? {} : { cwd: options.cwd },
},
events,
inheritedEventCount: SessionLogOffset(0),
cursor: -1,
projections: {
asOfSeq: -1,
values: {
...options.agentPreset === undefined ? {} : { agentPreset: options.agentPreset },
...options.workingDirectory === undefined ? {} : { workingDirectory: options.workingDirectory },
},
},
retain: lease,
[Symbol.dispose]: () => {},
})
return lease()
}
async function context(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(AgentRegistry)
provideWorkingDirectoryFixture(ctx, '/catalog/default')
return ctx
}
describe('SessionSkillCatalog', () => {
it('reads a moved cold Session catalog from its recorded current directory without resuming an Agent', async () => {
const ctx = await context()
const sessionId = SessionId('cold-skills')
const observed = observation(sessionId, { cwd: '/cold/original', workingDirectory: '/cold/project' })
const dispose = vi.spyOn(observed, Symbol.dispose)
const observeSession = vi.fn(() => Promise.resolve(observed))
ctx.provide('sessionQuery', { observeSession } as never)
const resume = vi.spyOn(ctx.agents, 'resume')
const ensureDirectory = vi.spyOn(ctx.workingDirectory, 'ensure')
const list = vi.fn(() => Promise.resolve([
{
name: 'review',
description: 'Review the current change.',
whenToUse: 'Before publishing.',
path: '/cold/project/.agents/skills/review/SKILL.md',
invocation: { modelInvocable: true, userInvocable: true },
},
{
name: 'model-only',
description: 'Not shown to the user.',
invocation: { modelInvocable: true, userInvocable: false },
},
]))
ctx.provide('skills', { list } as never)
const catalog = new SessionSkillCatalog(ctx)
await expect(catalog.list({ sessionId }, new AbortController().signal)).resolves.toEqual({
skills: [{
name: 'review',
description: 'Review the current change.',
whenToUse: 'Before publishing.',
path: '/cold/project/.agents/skills/review/SKILL.md',
modelInvocable: true,
}],
})
expect(observeSession).toHaveBeenCalledWith(sessionId)
expect(dispose).toHaveBeenCalledOnce()
expect(resume).not.toHaveBeenCalled()
expect(ensureDirectory).not.toHaveBeenCalled()
expect(ctx.agents.list()).toEqual([])
expect(list).toHaveBeenCalledWith({ cwd: '/cold/project', scope: undefined })
})
it.each([
{ cwd: undefined, workingDirectory: '/cold/current', expected: '/cold/current' },
{ cwd: '/cold/original', workingDirectory: null, expected: '/cold/original' },
{ cwd: undefined, workingDirectory: null, expected: '/catalog/default' },
{ cwd: undefined, workingDirectory: undefined, expected: '/catalog/default' },
])('resolves cold directory metadata $cwd / $workingDirectory to $expected without filesystem checks', async ({ cwd, workingDirectory, expected }) => {
const ctx = await context()
try {
const sessionId = SessionId('cold-directory-fallback')
ctx.provide('sessionQuery', {
observeSession: () => Promise.resolve(observation(sessionId, {
...cwd === undefined ? {} : { cwd },
...workingDirectory === undefined ? {} : { workingDirectory },
})),
} as never)
const list = vi.fn(() => Promise.resolve([]))
ctx.provide('skills', { list } as never)
const ensure = vi.spyOn(ctx.workingDirectory, 'ensure')
const resume = vi.spyOn(ctx.agents, 'resume')
await expect(new SessionSkillCatalog(ctx).list({ sessionId }, new AbortController().signal))
.resolves.toEqual({ skills: [] })
expect(list).toHaveBeenCalledWith({ cwd: expected, scope: undefined })
expect(ensure).not.toHaveBeenCalled()
expect(resume).not.toHaveBeenCalled()
} finally {
await ctx.fiber.dispose()
}
})
it('uses a live Agent to address a preset-owned registry', async () => {
const ctx = await context()
const sessionId = SessionId('live-skills')
const session = ctx.sessions.create(sessionId, { meta: { cwd: '/live/project' } })
const agent = { id: sessionId, session, status: 'idle', ctx } as Agent
await ctx.agents.register(agent)
const ensureDirectory = vi.spyOn(ctx.workingDirectory, 'ensure').mockResolvedValue('/live/current')
ctx.provide('sessionQuery', {
observeSession: () => Promise.resolve(observation(sessionId, { cwd: '/live/project' })),
} as never)
const scopedList = vi.fn(() => Promise.resolve([{
name: 'preset-owned',
description: 'Composed for this Agent.',
invocation: { modelInvocable: false, userInvocable: true },
}]))
const acquireScope = vi.fn()
ctx.provide('agentPresets', {
serviceFor: () => ({ list: scopedList }),
acquireScope,
} as never)
const catalog = new SessionSkillCatalog(ctx)
await expect(catalog.list({ sessionId }, new AbortController().signal)).resolves.toEqual({
skills: [{
name: 'preset-owned',
description: 'Composed for this Agent.',
modelInvocable: false,
}],
})
expect(scopedList).toHaveBeenCalledWith({ cwd: '/live/current', scope: agent })
expect(ensureDirectory).toHaveBeenCalledWith(agent, expect.any(AbortSignal))
expect(session.header.cwd).toBe('/live/project')
expect(acquireScope).not.toHaveBeenCalled()
})
it('uses the recorded preset standing scope for a cold Session', async () => {
const ctx = await context()
const sessionId = SessionId('standing-skills')
const scope = { agentPreset: 'minimal' }
ctx.provide('sessionQuery', {
observeSession: () => Promise.resolve(observation(sessionId, {
cwd: '/cold/project',
agentPreset: 'minimal',
})),
} as never)
const acquireScope = vi.fn(() => Promise.resolve({ key: scope, [Symbol.asyncDispose]: async () => {} }))
ctx.provide('agentPresets', { acquireScope } as never)
const list = vi.fn(() => Promise.resolve([]))
ctx.provide('skills', { list } as never)
const catalog = new SessionSkillCatalog(ctx)
await expect(catalog.list({ sessionId }, new AbortController().signal)).resolves.toEqual({ skills: [] })
expect(acquireScope).toHaveBeenCalledWith('minimal')
expect(list).toHaveBeenCalledWith({ cwd: '/cold/project', scope })
expect(ctx.agents.list()).toEqual([])
})
it.each(['agent-preset/not-found', 'agent-preset/invalid'] as const)('falls back to the global registry for %s', async (code) => {
const ctx = await context()
const sessionId = SessionId('gone-preset')
ctx.provide('sessionQuery', {
observeSession: () => Promise.resolve(observation(sessionId, {
cwd: '/cold/project',
agentPreset: 'gone',
})),
} as never)
ctx.provide('agentPresets', {
acquireScope: () => Promise.reject(new RemoteError(code, 'unavailable preset', { agentPreset: 'gone', available: [], reason: 'unavailable' })),
} as never)
const list = vi.fn(() => Promise.resolve([]))
ctx.provide('skills', { list } as never)
const catalog = new SessionSkillCatalog(ctx)
await expect(catalog.list({ sessionId }, new AbortController().signal)).resolves.toEqual({ skills: [] })
expect(list).toHaveBeenCalledWith({ cwd: '/cold/project', scope: undefined })
})
it.each([new Error('preset defect'), new RemoteError('gateway/internal', 'preset defect', {})])('warns and falls back to global skills for unexpected preset failures: %s', async (failure) => {
const ctx = await context()
const sessionId = SessionId('gone-preset')
ctx.provide('sessionQuery', {
observeSession: () => Promise.resolve(observation(sessionId, {
cwd: '/cold/project',
agentPreset: 'gone',
})),
} as never)
ctx.provide('agentPresets', {
acquireScope: () => Promise.reject(failure),
} as never)
const list = vi.fn(() => Promise.resolve([]))
ctx.provide('skills', { list } as never)
const catalog = new SessionSkillCatalog(ctx)
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
await expect(catalog.list({ sessionId }, new AbortController().signal)).resolves.toEqual({ skills: [] })
expect(list).toHaveBeenCalledWith({ cwd: '/cold/project', scope: undefined })
expect(warn).toHaveBeenCalledWith(expect.stringContaining('preset gone'))
expect(warn).toHaveBeenCalledWith(expect.stringContaining('preset defect'))
})
it.each([
{
error: new SessionQueryError(
'session "missing-skills" not found',
'SESSION_QUERY_SESSION_NOT_FOUND',
),
code: 'session/not-found',
},
{ error: new Error('storage offline'), code: 'gateway/internal' },
] as const)('classifies failed Session inspection as $code', async ({ error, code }) => {
const ctx = await context()
ctx.provide('sessionQuery', { observeSession: () => Promise.reject(error) } as never)
const catalog = new SessionSkillCatalog(ctx)
await expect(catalog.list(
{ sessionId: SessionId('missing-skills') },
new AbortController().signal,
)).rejects.toMatchObject({ code })
})
it('reports an absent skill registry instead of an empty catalog', async () => {
const ctx = await context()
const sessionId = SessionId('no-skills')
ctx.provide('sessionQuery', {
observeSession: () => Promise.resolve(observation(sessionId, { cwd: '/project' })),
} as never)
const catalog = new SessionSkillCatalog(ctx)
const failed = catalog.list({ sessionId }, new AbortController().signal)
await expect(failed).rejects.toMatchObject({ code: 'gateway/internal' })
await expect(failed).rejects.toThrow('skill registry is absent')
})
it('rejects observations without projections', async () => {
const ctx = await context()
const sessionId = SessionId('incomplete-skills')
const withoutProjections = { ...observation(sessionId, { cwd: '/project' }), projections: undefined }
const observeSession = vi.fn()
.mockResolvedValueOnce(withoutProjections)
ctx.provide('sessionQuery', { observeSession } as never)
const catalog = new SessionSkillCatalog(ctx)
const unprojected = catalog.list({ sessionId }, new AbortController().signal)
await expect(unprojected).rejects.toMatchObject({ code: 'gateway/internal' })
await expect(unprojected).rejects.toThrow('projected Session observation')
})
it('classifies a provider listing failure', async () => {
const ctx = await context()
const sessionId = SessionId('failed-skills')
ctx.provide('sessionQuery', {
observeSession: () => Promise.resolve(observation(sessionId, { cwd: '/project' })),
} as never)
ctx.provide('skills', {
list: () => Promise.reject(new Error('catalog offline')),
} as never)
const catalog = new SessionSkillCatalog(ctx)
await expect(catalog.list({ sessionId }, new AbortController().signal))
.rejects.toMatchObject({
code: 'gateway/internal', message: 'skill listing failed: Error: catalog offline',
})
})
})