import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MemoryCompositionRunner } from 'dsh-brain-mnemon/testing' import * as skillsPlugin from 'dsh-brain-mnemon-source-skills' import * as generalStrategy from 'dsh-brain-mnemon-strategy-general' import type { BacktestRun, DraftView, EvalCase, EvidencePack, SkillCatalog, SkillDraft, SkillSuggestion, Trajectory } from 'dsh-brain-mnemon-source-skills/contracts' import type { HostAgent, HostAgentContext, HostSessionEvent } from '../src/host/dsh.ts' import { DEFAULT_SKILLS_CONFIG, type ResolvedSkillsConfig } from '../src/host/protocol.ts' import { SkillEvolution, type SkillEvolutionHost, type SkillsSourcePort } from '../src/host/skill-evolution.ts' import { SubagentStoppedError } from '../src/host/subagent-errors.ts' import { gradeCase, parseSkillDraft, parseSkillReview, renderSteps, skillDraftPrompt, skillExecutorPrompt, skillReviewPrompt, SKILL_REVIEW_PERSONA } from '../src/host/skill-review.ts' import { captureTurn, redact, sessionTitle, TrajectoryWindow, turnSkillUses } from '../src/host/skill-trajectory.ts' import { sessionLog } from './fixtures/session-log.ts' type Listener = (...args: never[]) => unknown function turn(events: HostSessionEvent[], number: number, user: string, tools: Array<{ name: string; args: unknown; error?: string; output?: string }> = [], answer = 'Done.'): void { const push = (type: string, data: Record) => events.push({ type, seq: events.length, time: Date.UTC(2026, 9, 21, 8, number), data }) push('turn/start', { turn: number }) push('user/message', { id: `u${number}`, role: 'user', content: [{ type: 'text', text: user }], source: { kind: 'user' } }) push('user/message', { id: `m${number}`, role: 'user', content: [{ type: 'text', text: '[MNEMON] reminder' }], source: { kind: 'plugin:dsh-brain-mnemon' } }) tools.forEach((tool, index) => { const callId = `c${number}-${index}` push('tool/call', { turn: number, step: 1, callId, name: tool.name, arguments: JSON.stringify(tool.args) }) push('tool/result', { turn: number, step: 1, message: { role: 'tool', toolCallId: callId, source: { kind: 'tool', callId }, content: [{ type: 'text', text: tool.output ?? tool.error ?? 'ok' }], ...(tool.error === undefined ? {} : { isError: true }) }, ...(tool.error === undefined ? {} : { error: { name: 'Error', code: 'failed', reason: tool.error } }), }) }) push('assistant/message', { turn: number, step: 2, message: { id: `a${number}`, content: [{ type: 'text', text: answer }] } }) push('turn/end', { turn: number, reason: { kind: 'completed' } }) } describe('trajectory capture', () => { it('numbers user turns, skill loads, tool results and failures, and drops plugin messages', () => { const events: HostSessionEvent[] = [] turn(events, 1, 'Write the release notes', [ { name: 'skill', args: { name: 'release-notes' }, output: '…' }, { name: 'bash', args: { command: 'git log --oneline', token: 'secret' }, error: 'fatal: not a git repository' }, { name: 'bash', args: { command: 'cat CHANGELOG.md' }, output: '## 2.0' }, ]) events.push({ type: 'session/title', seq: events.length, data: { title: 'Release v2 notes' } }) turn(events, 2, 'No — group them by component from now on. api_key=sk-abcdefghijklmnop') const first = captureTurn(events, 1)! expect(first).toMatchObject({ turn: 1, userCharacters: 23, toolCalls: 3, toolFailures: 1, toolNames: ['skill', 'bash'], skills: ['release-notes'], reason: 'completed' }) expect(first.steps.map(step => step.kind)).toEqual(['user', 'skill', 'tool', 'tool', 'assistant']) expect(first.steps[2]).toMatchObject({ tool: { name: 'bash', ok: false, input: 'command=git log --oneline token=***', error: 'fatal: not a git repository' } }) expect(sessionTitle(events)).toBe('Release v2 notes') const window = new TrajectoryWindow() window.add(first, new Date()) window.add(captureTurn(events, 2)!, new Date()) window.add(captureTurn(events, 2)!, new Date()) expect(window.size).toBe(2) expect(window.score()).toMatchObject({ turnScore: 2, eligible: false }) const steps = window.steps() expect(steps.map(step => step.index)).toEqual([1, 2, 3, 4, 5, 6, 7]) expect(steps[5]!.text).toBe('No — group them by component from now on. api_key=***') expect(renderSteps(steps.slice(1, 3))).toBe('[2] turn 1 · skill loaded: release-notes (by the model)\n[3] turn 1 · tool bash (command=git log --oneline token=***) FAILED: fatal: not a git repository') expect(redact('Bearer abc.def and sk-1234567890abcdef')).toBe('Bearer *** and sk-1234***') }) it('lists the skills each turn used: a / command, and the skill loads that succeeded, each once', () => { const events: HostSessionEvent[] = [] turn(events, 1, 'Write the release notes', [ { name: 'skill', args: { name: 'release-notes' } }, { name: 'skill', args: { name: 'release-notes' } }, { name: 'skill', args: { name: 'pdf' }, error: 'unknown skill' }, ]) const push = (type: string, data: Record) => events.push({ type, seq: events.length, data }) push('turn/start', { turn: 2 }) push('user/message', { id: 'u2', role: 'user', content: [{ type: 'text', text: 'weekly' }], source: { kind: 'skill-invocation', name: 'weekly-report' } }) push('turn/end', { turn: 2, reason: { kind: 'completed' } }) turn(events, 3, 'Thanks') expect(turnSkillUses(events)).toEqual([ { turn: 1, skills: [{ name: 'release-notes', by: 'model' }] }, { turn: 2, skills: [{ name: 'weekly-report', by: 'user' }] }, ]) }) }) describe('skill model answers', () => { it('parses a review leniently and drops what cannot be used', () => { expect(parseSkillReview({ outcome: 'suggest', summary: ' Grouping was corrected. ', annotations: [{ step: 4, signal: 'correction', note: 'x' }, { step: 'x', signal: 'correction', note: 'bad' }, { step: 2, signal: 'nope', note: 'bad' }], suggestions: [{ skillName: 'release-notes', action: 'update', summary: 'Group', confidence: '0.8', signals: ['correction', 'bogus'], steps: [4, 'x'] }, { skillName: '', summary: 'x' }], cases: [{ skillName: 'release-notes', title: 'T', prompt: 'P', checks: [{ text: 'grouped', must: true }, { text: '' }], steps: [4] }, { title: 'no checks', prompt: 'p', checks: [] }], })).toEqual({ outcome: 'suggest', summary: 'Grouping was corrected.', annotations: [{ step: 4, signal: 'correction', note: 'x' }], suggestions: [{ skillName: 'release-notes', action: 'update', summary: 'Group', confidence: 0.8, signals: ['correction'], steps: [4] }], cases: [{ skillName: 'release-notes', title: 'T', prompt: 'P', checks: [{ text: 'grouped', must: true }], steps: [4] }], }) expect(parseSkillDraft({ content: '```markdown\n---\nname: a\n---\nbody\n```', notes: 'n', changes: ['c'] })).toEqual({ content: '---\nname: a\n---\nbody\n', notes: 'n', changes: ['c'] }) expect(() => parseSkillDraft({ content: ' ' })).toThrow('no SKILL.md') }) it('passes a case only when every must check passes, weighing must checks twice', () => { const entry = { id: 'c', skillName: 's', title: 't', prompt: 'p', checks: [{ id: 'a', text: 'A', must: true }, { id: 'b', text: 'B', must: false }], origin: { kind: 'manual' as const }, enabled: true, createdAt: '', updatedAt: '' } expect(gradeCase(entry, { checks: [{ index: 1, pass: true, note: 'ok' }, { index: 2, pass: false, note: 'no' }], summary: 's' })).toMatchObject({ verdict: 'pass', score: 2 / 3 }) expect(gradeCase(entry, { checks: [{ index: 2, pass: true, note: 'ok' }] })).toMatchObject({ verdict: 'fail', score: 1 / 3, checks: [{ checkId: 'a', pass: false, note: 'not graded' }, { checkId: 'b', pass: true }] }) }) }) describe('skill evolution in the Host', () => { let directory: string let runner: MemoryCompositionRunner let source: SkillsSourcePort let events: HostSessionEvent[] let agent: HostAgent let listeners: Map let config: ResolvedSkillsConfig beforeEach(async () => { vi.useFakeTimers() config = { ...DEFAULT_SKILLS_CONFIG } directory = mkdtempSync(join(tmpdir(), 'mnemon-skill-evolution-')) mkdirSync(join(directory, 'dsh', 'skills', 'release-notes'), { recursive: true }) mkdirSync(join(directory, 'workspace')) writeFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), '---\nname: release-notes\ndescription: Write release notes from a changelog.\n---\n\n1. Read CHANGELOG.md\n') runner = new MemoryCompositionRunner() await runner.mount(generalStrategy, { instanceId: 'general' }) await runner.mount(skillsPlugin, { instanceId: 'skills', config: { dataDir: join(directory, 'data'), dshHome: join(directory, 'dsh'), agentsHome: join(directory, 'agents') } }) const scope = { storage: 'custom' as const, workspaceId: join(directory, 'workspace') } const base = { sourceInstanceKey: 'source:skills', scope } source = { scope, read: async (operation, input = null) => (await runner.executeManagement({ ...base, mode: 'read', operation, input: input as never, confirmed: false })).value as never, mutate: async (operation, input) => { const { revision } = await runner.executeManagement({ ...base, mode: 'read', operation: 'revision', input: null, confirmed: false }) return (await runner.executeManagement({ ...base, mode: 'mutate', operation, input: JSON.parse(JSON.stringify(input)), confirmed: true, expectedRevision: revision })).value as never }, } events = [] listeners = new Map() const ctx = { on: (name: string, listener: Listener) => { listeners.set(name, listener); return () => listeners.delete(name) }, effect: () => () => undefined, } as unknown as HostAgentContext agent = { id: 'session-1', status: 'idle', session: { header: { cwd: join(directory, 'workspace') }, ...sessionLog(events) }, ctx, followup: vi.fn(), steer: vi.fn(), inject: vi.fn(), cancel: vi.fn() } }) afterEach(async () => { vi.useRealTimers() await runner.dispose() rmSync(directory, { recursive: true, force: true }) }) function evolution(answers: Array<(label: string, prompt: string) => unknown>) { const skillTask = vi.fn(async (_parent, label, prompt) => { const next = answers.shift() if (next === undefined) throw new Error('unexpected model call: ' + label) const value = next(label, prompt) if (value instanceof Error) throw value return { structured: value } }) const runTask = vi.fn(async (_root: string | undefined, _signal: AbortSignal, operation: (task: HostAgent) => Promise) => operation(agent)) const host = { settings: () => config, source: () => source, taskRoute: (): { provider: string; model: string; reasoningEffort?: string } | undefined => ({ provider: 'test-provider', model: 'test-model', reasoningEffort: 'high' }), runTask: runTask as never, skillTask, warn: vi.fn() } return { skills: new SkillEvolution(host), skillTask, runTask, host } } async function endTurn(number: number, text: string, tools: Parameters[3] = []): Promise { turn(events, number, text, tools) listeners.get('session/event')!(agent.session as never, events.at(-1) as never) await vi.advanceTimersByTimeAsync(0) } function mixedReview() { return { outcome: 'suggest', summary: 'Two reusable workflows.', suggestions: [ { skillName: 'incident-triage', action: 'create', summary: 'Capture incident logs.', confidence: 0.9, steps: [1] }, { skillName: 'release-notes', action: 'update', summary: 'Group by component.', confidence: 0.9, steps: [1] }, ], cases: ['incident-triage', 'release-notes'].map(skillName => ({ skillName, title: 'Workflow', prompt: 'Follow the workflow', checks: [{ text: 'Follows the workflow', must: true }], steps: [1] })), } } it.each([true, false])('uses Source creation preferences for evolution with workspace=%s (#658)', async inWorkspace => { config = { ...config, targetScope: 'user', autoBacktest: false } await runner.mount(skillsPlugin, { instanceId: 'configured', config: { dataDir: join(directory, 'data'), dshHome: join(directory, 'dsh'), agentsHome: join(directory, 'agents'), skillRoots: { create: ['project-agents', 'user-agents'], default: 'project-agents' }, } }) const scope = { storage: 'custom' as const, ...(inWorkspace ? { workspaceId: join(directory, 'workspace') } : {}) } const client = await runner.managementClient('source:configured', scope) const configuredSource: SkillsSourcePort = { scope, read: async (operation, input = null) => (await client.read(operation, input as never)).value as never, mutate: async (operation, input) => { const { revision } = await client.read('revision', null) return (await client.mutate(operation, input as never, { confirmed: true, expectedRevision: revision })).value as never }, } const expectedRoot = inWorkspace ? 'project-agents' : 'user-agents' const content = '---\nname: incident-triage\ndescription: Capture incident logs.\n---\n\n1. Read the logs.\n' const { skills } = evolution([(_label, prompt) => { expect(prompt).toContain(`It will be written to ${expectedRoot}.`) return { content, notes: '', changes: [] } }]) await skills.draft(configuredSource, join(directory, 'unrelated-task-cwd'), { skill: 'incident-triage' }) await vi.waitFor(async () => expect(await configuredSource.read('drafts')).toHaveLength(1)) const [draft] = await configuredSource.read('drafts') expect(draft?.targetRoot).toBe(expectedRoot) await configuredSource.mutate('draft-adopt', { id: draft!.id }) const path = inWorkspace ? join(directory, 'workspace', '.agents', 'skills') : join(directory, 'agents', 'skills') expect(readFileSync(join(path, 'incident-triage', 'SKILL.md'), 'utf8')).toBe(content) }) it.each([ [undefined, 'workspaces', 'user-dsh'], ['user', 'workspaces', 'user-dsh'], ['project', 'global', 'project-dsh'], ['storage', 'global', 'user-dsh'], ['storage', 'custom', 'user-dsh'], ['storage', 'workspace', 'project-dsh'], ['storage', 'workspaces', 'project-dsh'], ] as const)('records and drafts a new skill in %s scope with %s storage', async (targetScope, storage, expectedRoot) => { config = { ...config, ...(targetScope === undefined ? {} : { targetScope }), evolution: true, autoBacktest: false, idleSeconds: 3600 } source = { ...source, scope: { storage } } // The Source catalog, not the model task's cwd, owns the project root. mkdirSync(join(directory, '.git')) const content = '---\nname: incident-triage\ndescription: Capture incident logs.\n---\n\n1. Read the logs.\n' const { skills } = evolution([mixedReview, (_label, prompt) => { expect(prompt).toContain(`It will be written to ${expectedRoot}.`) return { content, notes: '', changes: [] } }]) const stop = skills.watch(agent) await endTurn(1, 'Capture incident logs and group release notes.') await skills.reviewNow(agent) const suggestion = (await source.read('suggestions')).find(entry => entry.action === 'create')! expect(suggestion.targetRoot).toBe(expectedRoot) // A stored proposal keeps its destination when the preference later changes. config = { ...config, targetScope: expectedRoot === 'user-dsh' ? 'project' : 'user' } await skills.draft(source, join(directory, 'unrelated-task-cwd'), { suggestionId: suggestion.id }) await vi.waitFor(async () => expect(await source.read('drafts')).toHaveLength(1)) const [draft] = await source.read('drafts') expect(draft).toMatchObject({ action: 'create', targetRoot: expectedRoot }) expect(existsSync(join(directory, '.dsh', 'skills', 'incident-triage'))).toBe(false) await source.mutate('draft-adopt', { id: draft!.id }) const path = expectedRoot === 'user-dsh' ? join(directory, 'dsh', 'skills') : join(directory, '.dsh', 'skills') expect(readFileSync(join(path, 'incident-triage', 'SKILL.md'), 'utf8')).toBe(content) stop() }) it('uses the explicit draft root and lets adoption override it for a new skill', async () => { config = { ...config, targetScope: 'project', autoBacktest: false } const content = '---\nname: incident-triage\ndescription: Capture incident logs.\n---\n\n1. Read the logs.\n' const { skills } = evolution([(_label, prompt) => { expect(prompt).toContain('It will be written to user-agents.') return { content, notes: '', changes: [] } }]) await skills.draft(source, undefined, { skill: 'incident-triage', targetRoot: 'user-agents' }) await vi.waitFor(async () => expect(await source.read('drafts')).toHaveLength(1)) const [draft] = await source.read('drafts') expect(draft!.targetRoot).toBe('user-agents') await source.mutate('draft-adopt', { id: draft!.id, root: 'project-agents' }) expect(readFileSync(join(directory, 'workspace', '.agents', 'skills', 'incident-triage', 'SKILL.md'), 'utf8')).toBe(content) expect(existsSync(join(directory, 'agents', 'skills', 'incident-triage'))).toBe(false) }) it.each(['suggestion', 'direct'] as const)('keeps the %s draft destination when newer drafts fill its evidence window', async origin => { config = { ...config, targetScope: 'project', evolution: true, autoBacktest: false, idleSeconds: 3600 } const content = '---\nname: incident-triage\ndescription: Capture incident logs.\n---\n\n1. Read the logs.\n' const prompts: string[] = [] const answer = (_label: string, prompt: string) => { prompts.push(prompt); return { content, notes: '', changes: [] } } const { skills } = evolution([mixedReview, answer, answer]) const stop = skills.watch(agent) await endTurn(1, 'Capture incident logs and group release notes.') await skills.reviewNow(agent) const suggestion = (await source.read('suggestions')).find(entry => entry.action === 'create')! expect(suggestion.targetRoot).toBe('project-dsh') const input = origin === 'suggestion' ? { suggestionId: suggestion.id } : { skill: 'incident-triage' } await skills.draft(source, undefined, { ...input, targetRoot: 'user-agents', guidance: 'Preserve the log order.' }) await vi.waitFor(async () => expect(await source.read('drafts')).toHaveLength(1)) const [first] = await source.read('drafts') for (let index = 0; index < 3; index++) await source.mutate('draft-record', { ...(origin === 'direct' ? { suggestionId: suggestion.id } : {}), skillName: 'incident-triage', content, notes: `Another draft ${index}`, changes: [], guidance: [], targetRoot: 'project-dsh', }) const pack = await source.read('evidence-pack', input) expect(pack.drafts.some(draft => draft.id === first!.id)).toBe(false) await skills.draft(source, undefined, { ...input, guidance: 'Explain the checks.' }) await vi.waitFor(async () => expect(await source.read('drafts')).toHaveLength(5)) const [redraft] = await source.read('drafts') expect(prompts[1]).toContain('It will be written to user-agents.') expect(redraft).toMatchObject({ targetRoot: 'user-agents', guidance: ['Preserve the log order.', 'Explain the checks.'] }) stop() }) it('rejects an unavailable project before model work instead of falling back to user skills', async () => { config = { ...config, targetScope: 'project', autoBacktest: false } const read = source.read const scoped: SkillsSourcePort = { ...source, read: async (operation: string, input?: unknown): Promise => { const value = await read(operation, input) if (operation !== 'catalog') return value const catalog = value as SkillCatalog return { roots: catalog.roots.filter(root => root.kind.startsWith('user-')), skills: catalog.skills, problems: [] } as T } } const { skills, skillTask } = evolution([]) await expect(skills.draft(scoped, directory, { skill: 'incident-triage' })).rejects.toThrow(/project.*selected workspace/i) expect(skillTask).not.toHaveBeenCalled() expect(await source.read('drafts')).toEqual([]) }) it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('rejects an unwritable destination before model work without changing scope', async () => { config = { ...config, autoBacktest: false } chmodSync(join(directory, 'dsh', 'skills'), 0o555) try { const { skills, skillTask } = evolution([]) await expect(skills.draft(source, directory, { skill: 'incident-triage' })).rejects.toThrow(/user-dsh.*not writable/i) expect(skillTask).not.toHaveBeenCalled() expect(await source.read('drafts')).toEqual([]) } finally { chmodSync(join(directory, 'dsh', 'skills'), 0o755) } }) it('rejects a removed project rather than recreating it from an unrelated task cwd', async () => { config = { ...config, targetScope: 'project', autoBacktest: false } rmSync(join(directory, 'workspace'), { recursive: true }) const { skills, skillTask } = evolution([]) await expect(skills.draft(source, directory, { skill: 'incident-triage' })).rejects.toThrow(/selected workspace.*unavailable/i) expect(skillTask).not.toHaveBeenCalled() expect(existsSync(join(directory, 'workspace'))).toBe(false) }) it('keeps improvements in their original root despite settings and explicit destination overrides', async () => { config = { ...config, targetScope: 'project', autoBacktest: false } const content = '---\nname: release-notes\ndescription: Group release notes.\n---\n\n1. Group by component.\n' const { skills } = evolution([() => ({ content, notes: '', changes: [] })]) await skills.draft(source, undefined, { skill: 'release-notes', targetRoot: 'project-agents' }) await vi.waitFor(async () => expect(await source.read('drafts')).toHaveLength(1)) const [draft] = await source.read('drafts') expect(draft).toMatchObject({ action: 'update', baseKey: 'user-dsh:release-notes' }) expect(draft!.targetRoot).toBeUndefined() await source.mutate('draft-adopt', { id: draft!.id, root: 'project-agents' }) expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).toBe(content) expect(existsSync(join(directory, 'workspace', '.agents', 'skills', 'release-notes'))).toBe(false) }) it('stays out of the way until evolution is turned on', async () => { const { skills, skillTask } = evolution([]) const stop = skills.watch(agent) await endTurn(1, 'x'.repeat(400), [{ name: 'bash', args: {} }]) await vi.advanceTimersByTimeAsync(60_000) expect(skillTask).not.toHaveBeenCalled() expect(skills.pending('session-1')).toBeUndefined() stop() }) it.each([ { allowCreate: true, allowUpdate: true }, { allowCreate: true, allowUpdate: false }, { allowCreate: false, allowUpdate: true }, { allowCreate: false, allowUpdate: false }, ])('applies independent suggestion switches end to end: %j', async switches => { config = { ...config, evolution: true, idleSeconds: 3600, ...switches } const { skills, skillTask, runTask } = evolution([mixedReview]) const stop = skills.watch(agent) await endTurn(1, 'Capture incident logs and group release notes by component.') const count = Number(switches.allowCreate) + Number(switches.allowUpdate) if (count === 0) { await expect(skills.reviewNow(agent)).rejects.toThrow('Enable new-skill or skill-improvement suggestions') expect(skills.pending(agent.id)).toBeUndefined() expect(runTask).not.toHaveBeenCalled() } else { expect(await skills.reviewNow(agent)).toMatchObject({ inserted: count, casesAdded: count }) expect(skillTask.mock.calls[0]![2]).toContain(`Allowed suggestion types: create=${switches.allowCreate}, update=${switches.allowUpdate}`) } const suggestions = await source.read('suggestions') expect(suggestions.map(entry => entry.action).sort()).toEqual([ ...(switches.allowCreate ? ['create'] : []), ...(switches.allowUpdate ? ['update'] : []), ]) expect(await source.read('cases', { skill: 'incident-triage' })).toHaveLength(Number(switches.allowCreate)) expect(await source.read('cases', { skill: 'release-notes' })).toHaveLength(Number(switches.allowUpdate)) stop() }) it('skips a scheduled review when both types are disabled and resumes on a later turn', async () => { config = { ...config, evolution: true, reviewThreshold: 1, idleSeconds: 20 } const { skills, skillTask } = evolution([mixedReview]) const stop = skills.watch(agent) await endTurn(1, 'Capture incident logs before changing the system.') config = { ...config, allowCreate: false, allowUpdate: false } await vi.advanceTimersByTimeAsync(20_000) expect(skillTask).not.toHaveBeenCalled() config = { ...config, allowUpdate: true } await endTurn(2, 'Group release notes by component.') await vi.advanceTimersByTimeAsync(20_000) await vi.waitFor(async () => expect(await source.read('suggestions')).toMatchObject([{ action: 'update' }])) expect(skillTask).toHaveBeenCalledTimes(1) stop() }) it.each(['allowCreate', 'allowUpdate'] as const)('honors %s being disabled while a review is running', async key => { config = { ...config, evolution: true, idleSeconds: 3600 } const { skills, host } = evolution([]) let markStarted!: () => void const started = new Promise(resolve => { markStarted = resolve }) let complete!: (value: { structured: unknown }) => void host.skillTask.mockImplementation(() => { markStarted(); return new Promise(resolve => { complete = resolve }) }) const stop = skills.watch(agent) await endTurn(1, 'Keep incident and release workflows consistent.') const pending = skills.reviewNow(agent) await started config = { ...config, [key]: false } complete({ structured: mixedReview() }) expect(await pending).toMatchObject({ inserted: 1, casesAdded: 1 }) expect(await source.read('suggestions')).toMatchObject([{ action: key === 'allowCreate' ? 'update' : 'create' }]) stop() }) it('does not start the model if both types are disabled while its task is being prepared', async () => { const { skills, runTask, skillTask } = evolution([]) runTask.mockImplementation(async (_root, _signal, operation) => { config = { ...config, allowCreate: false, allowUpdate: false } return operation(agent) }) const stop = skills.watch(agent) await endTurn(1, 'Capture incident logs before changing the system.') expect(await skills.reviewNow(agent)).toMatchObject({ inserted: 0, updated: 0, casesAdded: 0 }) expect(skillTask).not.toHaveBeenCalled() stop() }) it('reviews an idle window that reached the score, records evidence and starts a new window', async () => { config = { ...config, evolution: true, idleSeconds: 20 } let prompt = '' const { skills, skillTask } = evolution([(_label, text) => { prompt = text return { outcome: 'suggest', summary: 'The user corrected the grouping.', annotations: [{ step: 6, signal: 'correction', note: 'Wanted grouping by component' }], suggestions: [{ skillName: 'release-notes', action: 'update', summary: 'Group entries by component', rationale: 'Corrected twice', confidence: 0.85, signals: ['correction'], steps: [3, 6] }], cases: [{ skillName: 'release-notes', title: 'Grouped notes', prompt: 'Write v2 release notes', checks: [{ text: 'Grouped by component', must: true }], steps: [1, 6] }], } }]) skills.watch(agent) await endTurn(1, 'Write the release notes for v2 from the changelog in this repository, please.', [ { name: 'skill', args: { name: 'release-notes' } }, { name: 'bash', args: { command: 'git log' }, error: 'not a git repository' }, { name: 'read', args: { path: 'CHANGELOG.md' } }, ]) expect(skills.pending('session-1')).toEqual({ turns: 1, score: 3 }) await endTurn(2, 'No, group them by component from now on, and put breaking changes first in every section.') expect(skills.pending('session-1')!.score).toBeGreaterThanOrEqual(5) // A new turn before the pause postpones the review. await listeners.get('agent/pre-step')!({ step: 1, signal: new AbortController().signal } as never, (async () => ({ kind: 'enter', messages: [] })) as never) await vi.advanceTimersByTimeAsync(30_000) expect(skillTask).not.toHaveBeenCalled() await endTurn(3, 'Thanks, that is right.') await vi.advanceTimersByTimeAsync(20_000) expect(skillTask).toHaveBeenCalledTimes(1) expect(prompt).toContain('[2] turn 1 · skill loaded: release-notes (by the model)') expect(prompt).toContain('=== release-notes (user-dsh:') const bytes = Buffer.byteLength(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')) expect(prompt).toContain(`- release-notes: Write release notes from a changelog. (SKILL.md=${bytes} UTF-8 bytes; layout=bundle)`) const [suggestion] = await source.read('suggestions') expect(suggestion).toMatchObject({ skillName: 'release-notes', action: 'update', status: 'pending', sourceSessionId: 'session-1', signals: ['correction'] }) const trajectory = await source.read('trajectory', { id: suggestion!.evidence[0]!.trajectoryId }) expect(trajectory).toMatchObject({ outcome: 'suggested', stats: { turns: 3, toolFailures: 1, skills: ['release-notes'] }, reviewSummary: 'The user corrected the grouping.' }) expect(trajectory.annotations).toEqual([{ step: 6, signal: 'correction', note: 'Wanted grouping by component', suggestionIds: [suggestion!.id] }]) expect(await source.read('cases', { skill: 'release-notes' })).toMatchObject([{ title: 'Grouped notes', origin: { kind: 'review' } }]) expect(skills.pending('session-1')).toEqual({ turns: 0, score: 0 }) }) it('tells the conversation which skills each turn used and how its review went', async () => { config = { ...config, evolution: true, idleSeconds: 20 } const { skills } = evolution([() => ({ outcome: 'suggest', summary: 'The user corrected the grouping.', suggestions: [{ skillName: 'release-notes', action: 'update', summary: 'Group entries by component', confidence: 0.85, signals: ['correction'], steps: [3, 6] }], })]) skills.watch(agent) await endTurn(1, 'Write the release notes for v2 from the changelog in this repository, please.', [ { name: 'skill', args: { name: 'release-notes' } }, { name: 'bash', args: { command: 'git log' }, error: 'not a git repository' }, { name: 'read', args: { path: 'CHANGELOG.md' } }, ]) await endTurn(2, 'No, group them by component from now on, and put breaking changes first in every section.') expect(await skills.activity(agent)).toEqual({ available: true, turns: [{ turn: 1, skills: [{ name: 'release-notes', by: 'model' }] }], reviews: [{ turn: 2, state: 'scheduled', suggestions: [] }], }) await vi.advanceTimersByTimeAsync(20_000) const [suggestion] = await source.read('suggestions') expect((await skills.activity(agent)).reviews).toEqual([{ turn: 2, state: 'suggested', suggestions: [{ id: suggestion!.id, skillName: 'release-notes', action: 'update', status: 'pending' }] }]) // A handled suggestion leaves the line; the review stays. await source.mutate('suggestion-dismiss', { id: suggestion!.id }) expect((await skills.activity(agent)).reviews).toEqual([{ turn: 2, state: 'suggested', suggestions: [] }]) // Turning self-evolution off stops what is scheduled next. config = { ...config, evolution: false } await endTurn(3, 'Now do the same for the v3 changelog, grouped by component with breaking changes first.', [{ name: 'skill', args: { name: 'release-notes' } }]) expect((await skills.activity(agent)).reviews.map(review => review.state)).toEqual(['suggested']) }) it('logs a failed review, keeps its window and pauses the session after three failures', async () => { config = { ...config, evolution: true, idleSeconds: 1, cooldownSeconds: 0, reviewThreshold: 1 } const { skills, skillTask, host } = evolution([() => new Error('model unavailable'), () => new Error('model unavailable'), () => new Error('model unavailable')]) skills.watch(agent) for (let index = 1; index <= 4; index++) { await endTurn(index, `Turn ${index}`) await vi.advanceTimersByTimeAsync(2_000) } expect(skillTask).toHaveBeenCalledTimes(3) expect(host.warn).toHaveBeenCalledWith('skill review failed', expect.any(Error)) const reviews = await source.read>('reviews') expect(reviews.map(review => review.outcome)).toEqual(['error', 'error', 'error']) expect(reviews[0]!.error).toBe('model unavailable') expect(skills.pending('session-1')!.turns).toBe(3) }) function automaticHarness(options: { regression?: boolean; incomplete?: boolean; noCases?: boolean; create?: boolean; onDraft?: () => void } = {}) { config = { ...config, evolution: true, autoAdopt: true, autoBacktest: true, idleSeconds: 1, cooldownSeconds: 0, reviewThreshold: 1 } const harness = evolution([]) const skillName = options.create ? 'incident-triage' : 'release-notes' let drafts = 0 const prompts: string[] = [] harness.host.skillTask.mockImplementation(async (_parent, label, prompt) => { if (label.includes('draft')) { options.onDraft?.() drafts++ prompts.push(prompt) return { structured: { content: `---\nname: ${skillName}\ndescription: Group release notes.\n---\n\n1. Group by component. Candidate ${drafts}.\n`, notes: '', changes: ['Group by component'] } } } if (label.startsWith('Mnemon skill eval:')) return { structured: { steps: ['Read changelog'], answer: prompt.includes('Candidate') ? 'candidate' : 'baseline' } } if (label.startsWith('Mnemon skill judge:')) return { structured: { checks: options.incomplete ? [] : [{ index: 1, pass: !options.regression || !prompt.includes('candidate'), note: 'measured' }], summary: 'Scored the simulated answer' } } return { structured: { outcome: 'suggest', summary: 'Group notes by component.', suggestions: [{ skillName, action: options.create ? 'create' : 'update', summary: 'Group release notes by component.', confidence: 0.95, steps: [1] }], cases: options.noCases ? [] : [{ skillName, title: 'Grouped notes', prompt: 'Write v2 notes', checks: [{ text: 'Grouped by component', must: true }], steps: [1] }], } } }) harness.skills.watch(agent) return { ...harness, prompts, drafts: () => drafts, start: async () => { await endTurn(1, 'Write release notes and group entries by component.'); await vi.advanceTimersByTimeAsync(1500) }, outcome: async () => { const [suggestion] = await source.read('suggestions'); return suggestion }, } } it('leaves a fresh suggestion actionable without drafting when its daily quota is exhausted', async () => { const run = automaticHarness() config = { ...config, autoAdoptDailyLimit: 0 } await run.start() await vi.waitFor(async () => expect((await run.outcome())?.autoAdoption?.at(-1)).toMatchObject({ stage: 'review', reason: 'daily-limit', attempt: 0, detail: expect.stringContaining('0/0') })) expect((await run.outcome())?.status).toBe('pending') expect(run.drafts()).toBe(0) config = { ...config, autoAdopt: false } await run.skills.draft(source, undefined, { suggestionId: (await run.outcome())!.id }) await vi.waitFor(async () => expect((await run.outcome())?.status).toBe('review')) await source.mutate('draft-adopt', { id: (await run.outcome())!.draftId! }) expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).toContain('Candidate 1') run.skills.dispose() }) it('never generates or adopts update drafts for a linked skill, manually or automatically', async () => { const location = join(directory, 'dsh', 'skills', 'release-notes') const upstream = join(directory, 'upstream') const original = readFileSync(join(location, 'SKILL.md'), 'utf8') renameSync(location, upstream) symlinkSync(upstream, location, process.platform === 'win32' ? 'junction' : 'dir') const run = automaticHarness() await expect(run.skills.draft(source, undefined, { skill: 'release-notes' })).rejects.toThrow('Linked skills are read-only') expect(run.skillTask).not.toHaveBeenCalled() await run.start() expect(run.drafts()).toBe(0) expect(await source.read('suggestions')).toEqual([]) expect(await source.read('drafts')).toEqual([]) expect(readFileSync(join(upstream, 'SKILL.md'), 'utf8')).toBe(original) run.skills.dispose() }) it('automatically adopts a fresh idle suggestion with full paired results and one frozen model', async () => { const run = automaticHarness() await run.start() await vi.waitFor(async () => expect((await run.outcome())?.status).toBe('adopted'), { timeout: 5000 }) const suggestion = (await run.outcome())! expect(suggestion.autoAdoption?.at(-1)).toMatchObject({ stage: 'adopted', attempt: 1, baselineScore: 1, draftScore: 1 }) expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).toContain('Candidate 1') const runs = await source.read('runs') expect(runs).toHaveLength(2) expect(new Set(runs.map(entry => entry.casesHash)).size).toBe(1) expect(runs.every(entry => entry.model?.provider === 'test-provider' && entry.model?.reasoningEffort === 'high')).toBe(true) expect((await source.read>('reviews'))[0]?.autoAdoptions?.at(-1)).toMatchObject({ suggestionId: suggestion.id, stage: 'adopted' }) run.skills.dispose() }) it('uses a no-skill baseline for creation and retains the configured user root', async () => { const run = automaticHarness({ create: true }) await run.start() await vi.waitFor(async () => expect((await run.outcome())?.status).toBe('adopted'), { timeout: 5000 }) expect(existsSync(join(directory, 'dsh', 'skills', 'incident-triage', 'SKILL.md'))).toBe(true) expect((await source.read('runs')).map(entry => entry.target.kind).sort()).toEqual(['draft', 'none']) run.skills.dispose() }) it('does not turn a new-skill suggestion into an update when a user creates that skill while it is queued', async () => { const run = automaticHarness({ create: true }) config = { ...config, allowUpdate: false } const original = source const path = join(directory, 'dsh', 'skills', 'incident-triage', 'SKILL.md') const content = '---\nname: incident-triage\ndescription: Human workflow.\n---\n\nKeep this human instruction.\n' source = { ...original, mutate: async (operation, input, signal) => { const result = await original.mutate(operation, input, signal) if (operation === 'review-record') { mkdirSync(join(path, '..'), { recursive: true }); writeFileSync(path, content) } return result as never } } await run.start() await vi.waitFor(async () => expect((await run.outcome())?.autoAdoption?.at(-1)).toMatchObject({ stage: 'review', reason: 'changed' }), { timeout: 5000 }) expect(run.drafts()).toBe(0) expect(readFileSync(path, 'utf8')).toBe(content) run.skills.dispose() }) it('respects the separate create permission', async () => { const run = automaticHarness({ create: true }) config = { ...config, allowCreate: false } await run.start() await vi.advanceTimersByTimeAsync(1000) expect(run.drafts()).toBe(0) expect(existsSync(join(directory, 'dsh', 'skills', 'incident-triage'))).toBe(false) run.skills.dispose() }) it.each(['vision', 'case-limit'] as const)('does not silently omit enabled cases: %s', async kind => { const run = automaticHarness() await source.mutate('case-save', { skillName: 'release-notes', title: kind === 'vision' ? 'Grouped notes' : 'Another case', prompt: kind === 'vision' ? 'Write v2 notes' : 'Check a different release', requiresVision: kind === 'vision', checks: [{ text: 'Grouped by component', must: true }] }) if (kind === 'case-limit') config = { ...config, casesPerRun: 1 } await run.start() await vi.waitFor(async () => expect((await run.outcome())?.autoAdoption?.at(-1)).toMatchObject({ stage: 'review', reason: kind === 'vision' ? 'unmeasured' : 'case-limit' }), { timeout: 5000 }) expect(run.drafts()).toBe(0) run.skills.dispose() }) it('respects the backtest model override independently of the draft model', async () => { const run = automaticHarness() await source.mutate('draft-preference', { slot: 'draft', model: { provider: 'draft-provider', model: 'draft-model' } }) await source.mutate('draft-preference', { slot: 'run', skillName: 'release-notes', model: { provider: 'eval-provider', model: 'eval-model' } }) await run.start() await vi.waitFor(async () => expect((await run.outcome())?.status).toBe('adopted'), { timeout: 5000 }) expect(run.runTask.mock.calls.map(call => (call as unknown[])[3])).toEqual(expect.arrayContaining([{ provider: 'draft-provider', model: 'draft-model' }, { provider: 'eval-provider', model: 'eval-model' }])) expect((await source.read('runs')).every(entry => entry.model?.model === 'eval-model')).toBe(true) run.skills.dispose() }) it('rewrites at most twice with the scores and retains a regressed draft for manual review', async () => { const run = automaticHarness({ regression: true }) await run.start() await vi.waitFor(async () => expect((await run.outcome())?.autoAdoption?.at(-1)).toMatchObject({ stage: 'review', attempt: 3, reason: 'regressed', baselineScore: 1, draftScore: 0 }), { timeout: 8000 }) expect(run.drafts()).toBe(3) expect(run.prompts[1]).toContain('Baseline score: 1; previous draft score: 0') expect((await run.outcome())?.status).toBe('review') expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).not.toContain('Candidate') expect(await source.read('runs')).toHaveLength(6) run.skills.dispose() }) it.each(['off', 'manual', 'disabled-backtest', 'disabled-update'] as const)('does not automatically draft when %s', async mode => { const run = automaticHarness() if (mode === 'off') config = { ...config, autoAdopt: false } if (mode === 'disabled-backtest') config = { ...config, autoBacktest: false } if (mode === 'disabled-update') config = { ...config, allowUpdate: false } if (mode === 'manual') { await endTurn(1, 'Write release notes.'); await run.skills.reviewNow(agent) } else await run.start() await vi.advanceTimersByTimeAsync(1000) expect(run.drafts()).toBe(0) expect(await source.read('drafts')).toHaveLength(0) run.skills.dispose() }) it.each(['no-cases', 'unmeasured'] as const)('keeps a reason visible instead of adopting %s', async reason => { const run = automaticHarness({ noCases: reason === 'no-cases', incomplete: reason === 'unmeasured' }) await run.start() await vi.waitFor(async () => expect((await run.outcome())?.autoAdoption?.at(-1)).toMatchObject({ stage: 'review', reason }), { timeout: 5000 }) expect((await run.outcome())?.status).toBe(reason === 'no-cases' ? 'pending' : 'review') expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).not.toContain('Candidate') run.skills.dispose() }) it('stops before recording a draft when automatic adoption is disabled during generation', async () => { let skills: SkillEvolution const run = automaticHarness({ onDraft: () => { config = { ...config, autoAdopt: false }; skills.settingsChanged() } }) skills = run.skills await run.start() await vi.waitFor(async () => expect((await run.outcome())?.autoAdoption?.at(-1)).toMatchObject({ stage: 'paused', reason: 'disabled' }), { timeout: 5000 }) expect(await source.read('drafts')).toHaveLength(0) expect(await source.read('runs')).toHaveLength(0) expect((await run.outcome())?.status).toBe('pending') run.skills.dispose() }) it('cancels non-cooperative backtests when the switch is disabled and keeps the draft reviewable', async () => { const run = automaticHarness() const model = run.host.skillTask.getMockImplementation()! run.host.skillTask.mockImplementation(async (...args) => args[1].startsWith('Mnemon skill eval:') ? new Promise(() => {}) : model(...args)) await run.start() await vi.waitFor(async () => expect(await source.read('runs')).toHaveLength(2), { timeout: 5000 }) config = { ...config, autoAdopt: false } run.skills.settingsChanged() await vi.waitFor(async () => expect((await run.outcome())?.autoAdoption?.at(-1)).toMatchObject({ stage: 'paused', reason: 'disabled' }), { timeout: 5000 }) await vi.waitFor(async () => expect((await source.read('runs')).every(entry => entry.status === 'interrupted')).toBe(true)) expect((await run.outcome())?.status).toBe('review') expect((await source.read('drafts'))[0]?.status).toBe('ready') expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).not.toContain('Candidate') run.skills.dispose() }) it('does not sweep old suggestions or automatically process a reinforced suggestion', async () => { const run = automaticHarness() config = { ...config, autoAdopt: false } await run.start() const original = (await run.outcome())! config = { ...config, autoAdopt: true } run.skills.settingsChanged() await endTurn(2, 'Again, group release notes by component.') await vi.advanceTimersByTimeAsync(2000) expect(run.drafts()).toBe(0) expect((await run.outcome())?.id).toBe(original.id) expect((await run.outcome())?.status).toBe('pending') run.skills.dispose() }) it('drafts in the background, backtests draft and baseline, and adopts through the Source', async () => { config = { ...config, allowCreate: false, allowUpdate: false } config = { ...config, evolution: true } await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Grouped notes', prompt: 'Write v2 notes', checks: [{ text: 'Grouped by component', must: true }] } }) const next = '---\nname: release-notes\ndescription: Write release notes grouped by component.\n---\n\n1. Read CHANGELOG.md\n2. Group by component\n' // Two runs share the model at once, so answer by what each call asks rather than by order. const drafts = [ () => ({ content: '# missing frontmatter', notes: 'x', changes: [] }), (prompt: string) => { expect(prompt).toContain('Your previous SKILL.md was rejected'); return { content: next, notes: '按组件分组。', changes: ['Group by component'] } }, ] const { skills, host } = evolution([]) host.skillTask.mockImplementation(async (_parent: HostAgent, label: string, prompt: string) => { if (label === 'Mnemon skill draft') return { structured: drafts.shift()!(prompt) } if (label.startsWith('Mnemon skill eval')) return { structured: prompt.includes('Group by component') ? { steps: ['read changelog', 'group'], answer: '## API\n- x' } : { steps: ['read changelog'], answer: '- x' } } const pass = prompt.includes('## API') return { structured: { checks: [{ index: 1, pass, note: pass ? 'grouped' : 'flat list' }], summary: pass ? 'good' : 'flat' } } }) const started = await skills.draft(source, join(directory, 'workspace'), { skill: 'release-notes', guidance: 'Group by component' }) expect(started).toEqual({ started: true }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => { const runs = await source.read('runs', { skill: 'release-notes' }) expect(runs.map(run => run.status)).toEqual(["completed", "completed"]) }) const [draft] = await source.read('drafts', { skill: 'release-notes' }) expect(draft).toMatchObject({ status: 'ready', action: 'update', notes: '按组件分组。', guidance: ['Group by component'] }) const view = await source.read<{ runs: BacktestRun[] }>('draft', { id: draft!.id }) expect(view.runs.map(run => [run.target.kind, run.passRate])).toEqual([['draft', 1], ['current', 0]]) await source.mutate('draft-adopt', { id: draft!.id }) expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).toBe(next) }) it('redrafts and backtests the recorded project file from global management', async () => { const path = join(directory, 'workspace', '.dsh', 'skills', 'release-notes', 'SKILL.md') mkdirSync(join(path, '..'), { recursive: true }) const original = '---\nname: release-notes\ndescription: Original project workflow.\n---\n\n1. Follow original project checks.\n' writeFileSync(path, original) const first = await source.mutate('draft-record', { skillName: 'release-notes', content: original, notes: '', changes: [], guidance: ['Keep project checks.'] }) await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Project checks', prompt: 'Write notes', checks: [{ text: 'Keeps project checks', must: true }] } }) const management = await runner.managementClient('source:skills', { storage: 'global' }) const global: SkillsSourcePort = { scope: { storage: 'global' }, read: async (operation, input = null) => (await management.read(operation, input as never)).value as never, mutate: async (operation, input) => { const { revision } = await management.read('revision', null) return (await management.mutate(operation, input as never, { confirmed: true, expectedRevision: revision })).value as never }, } const { skills, host } = evolution([]) const execution: string[] = [] host.skillTask.mockImplementation(async (_parent: HostAgent, label: string, prompt: string) => { if (label === 'Mnemon skill draft') { expect(prompt).toContain('Follow original project checks') expect(prompt).toContain('Keep project checks.') return { structured: { content: original + '\n2. Include the release date.\n', notes: '', changes: [] } } } if (label.startsWith('Mnemon skill eval')) { execution.push(prompt); return { structured: { steps: ['Checked project'], answer: 'Ready' } } } return { structured: { checks: [{ index: 1, pass: true, note: 'checked' }], summary: 'good' } } }) await skills.draft(global, undefined, { draftId: first.id }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => expect((await global.read('runs')).map(run => run.status)).toEqual(['completed', 'completed'])) expect(execution).toHaveLength(2) expect(execution.every(prompt => prompt.includes('Follow original project checks'))).toBe(true) const [next] = await global.read('drafts') expect(next!.origin?.path).toBe(path) await global.mutate('draft-adopt', { id: next!.id }) expect(readFileSync(path, 'utf8')).toContain('Include the release date') expect(readFileSync(join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md'), 'utf8')).not.toContain('Include the release date') }) it('repairs an oversized bundle draft through references without writing until adoption', async () => { config = { ...config, autoBacktest: false } const file = join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md') const header = readFileSync(file, 'utf8') const details = '保留所有参数与异常处理示例。\n'.repeat(2_000) const original = header + details writeFileSync(file, original) expect(Buffer.byteLength(original)).toBeGreaterThan(65_536) expect(original.length).toBeLessThan(65_536) const next = header + '2. Follow references/details.md for parameters and error handling.\n' const { skills, skillTask, host } = evolution([ (_label, prompt) => { expect(prompt).toContain(`${Buffer.byteLength(original)} UTF-8 bytes`) expect(prompt).toContain('65536') return { content: original, notes: '', changes: [] } }, (_label, prompt) => { const repair = prompt.split('Your previous SKILL.md was rejected:')[1]! expect(repair).toContain('references/') expect(repair).toContain('files') expect(repair).toContain('Preserve') return { content: next, notes: 'Move details into a reference.', changes: ['Extract details'], files: [{ path: 'references/details.md', action: 'upsert', content: details }] } }, ]) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(async () => expect(await source.read('drafts', { skill: 'release-notes' })).toHaveLength(1)) expect(skillTask).toHaveBeenCalledTimes(2) expect(host.warn).not.toHaveBeenCalled() expect(readFileSync(file, 'utf8')).toBe(original) const reference = join(directory, 'dsh', 'skills', 'release-notes', 'references', 'details.md') expect(existsSync(reference)).toBe(false) const [draft] = await source.read('drafts', { skill: 'release-notes' }) await source.mutate('draft-adopt', { id: draft!.id }) expect(readFileSync(file, 'utf8')).toBe(next) expect(readFileSync(reference, 'utf8')).toBe(details) skills.dispose() }) it('repairs an oversized flat draft in place without creating a bundle', async () => { config = { ...config, autoBacktest: false } const bundle = join(directory, 'dsh', 'skills', 'release-notes') const file = bundle + '.md' renameSync(join(bundle, 'SKILL.md'), file) rmSync(bundle, { recursive: true }) const original = readFileSync(file, 'utf8') const next = original + '2. Group by component.\n' const { skills, skillTask, host } = evolution([ () => ({ content: original + '字'.repeat(22_000), notes: '', changes: [] }), (_label, prompt) => { const repair = prompt.split('Your previous SKILL.md was rejected:')[1]! expect(repair).toContain('omit files') expect(repair).toContain('Do not convert') return { content: next, notes: '', changes: ['Group by component'] } }, ]) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(async () => expect(await source.read('drafts', { skill: 'release-notes' })).toHaveLength(1)) const [draft] = await source.read('drafts', { skill: 'release-notes' }) expect(draft!.files ?? []).toEqual([]) expect(skillTask).toHaveBeenCalledTimes(2) expect(host.warn).not.toHaveBeenCalled() await source.mutate('draft-adopt', { id: draft!.id }) expect(readFileSync(file, 'utf8')).toBe(next) expect(existsSync(bundle)).toBe(false) skills.dispose() }) it('stops after one oversized retry without replacing a saved draft or writing references', async () => { config = { ...config, autoBacktest: false } const file = join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md') const original = readFileSync(file, 'utf8') await source.mutate('draft-record', { skillName: 'release-notes', content: original, notes: 'Saved draft', changes: [], guidance: [] }) const ledgerPath = join(directory, 'data', 'skills', 'ledger.json') const ledger = readFileSync(ledgerPath, 'utf8') const oversized = () => ({ content: original + '字'.repeat(22_000), notes: '', changes: [], files: [{ path: 'references/details.md', action: 'upsert', content: 'Never written.' }] }) const { skills, skillTask, host } = evolution([oversized, oversized]) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(() => expect(host.warn).toHaveBeenCalledOnce()) expect(skillTask).toHaveBeenCalledTimes(2) expect(readFileSync(file, 'utf8')).toBe(original) expect(readFileSync(ledgerPath, 'utf8')).toBe(ledger) expect(existsSync(join(directory, 'dsh', 'skills', 'release-notes', 'references'))).toBe(false) skills.dispose() }) it('regenerates a truncated draft under a fresh task with the configured larger budget', async () => { config = { ...config, autoBacktest: false, draftMaxTokens: 32_768, draftRetryMaxTokens: 65_536 } const file = join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md') const original = readFileSync(file, 'utf8') + '发布说明:保留完整工作流。\n'.repeat(1_000) writeFileSync(file, original) const { skills, host, runTask } = evolution([]) const tasks: string[] = [] runTask.mockImplementation(async (_root, _signal, operation) => operation({ ...agent, id: `task-${runTask.mock.calls.length}` })) const route = { provider: 'chosen-provider', model: 'chosen-model' } host.skillTask.mockImplementation(async (task, _label, prompt, _schema, _persona, _signal, selected, maxTokens) => { tasks.push(task.id) expect(selected).toEqual(route) expect(prompt.match(/发布说明:保留完整工作流。/gu)).toHaveLength(1_000) expect(await source.read('drafts', { skill: 'release-notes' })).toEqual([]) if (maxTokens === 32_768) throw new SubagentStoppedError('max-tokens', maxTokens) expect(maxTokens).toBe(65_536) return { structured: { content: original + '2. Group by component\n', notes: '', changes: ['Group by component'] } } }) await skills.draft(source, undefined, { skill: 'release-notes', route }) await vi.waitFor(async () => expect(await source.read('drafts', { skill: 'release-notes' })).toHaveLength(1)) expect(tasks).toEqual(['task-1', 'task-2']) expect(readFileSync(file, 'utf8')).toBe(original) expect(host.warn).not.toHaveBeenCalled() }) it.each(['truncation', 'invalid-file'] as const)('preserves the saved draft and ledger when the final attempt ends in %s', async final => { config = { ...config, autoBacktest: false, draftMaxTokens: 24_576, draftRetryMaxTokens: 49_152 } const file = join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md') const original = readFileSync(file, 'utf8') + '\n按组件分组。\n' writeFileSync(file, original) await source.mutate('draft-record', { skillName: 'release-notes', content: original, notes: 'Saved draft', changes: [], guidance: [] }) const ledgerPath = join(directory, 'data', 'skills', 'ledger.json') const ledger = readFileSync(ledgerPath, 'utf8') const { skills, host, runTask } = evolution([]) host.skillTask.mockImplementation(async (_task, _label, _prompt, _schema, _persona, _signal, _route, maxTokens) => { if (maxTokens === 24_576 || final === 'truncation') throw new SubagentStoppedError('max-tokens', maxTokens) return { structured: { content: '# incomplete skill file', notes: '', changes: [] } } }) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(() => expect(host.warn).toHaveBeenCalledOnce()) expect(runTask).toHaveBeenCalledTimes(2) expect(host.skillTask.mock.calls.map(call => call[7])).toEqual([24_576, 49_152]) expect(readFileSync(ledgerPath, 'utf8')).toBe(ledger) expect(readFileSync(file, 'utf8')).toBe(original) if (final === 'truncation') { const error = host.warn.mock.calls[0]![1] as Error expect(error.message).toContain('24576, 49152') expect(error.message).toContain(`${Buffer.byteLength(original, 'utf8')} bytes`) expect(error.message).toContain('skills.draftMaxTokens') expect(error.message).toContain('skills.draftRetryMaxTokens') expect(error.message).toContain('provider') } }) it.each([16_384, 32_768])('leaves a suggestion pending without retry when the retry budget is %s', async retryBudget => { config = { ...config, autoBacktest: false, draftRetryMaxTokens: retryBudget } const { skills, host, runTask } = evolution([mixedReview]) turn(events, 1, 'Group release notes by component.') await skills.reviewNow(agent) const suggestion = (await source.read('suggestions')).find(entry => entry.action === 'update')! runTask.mockClear() host.skillTask.mockImplementation(async () => { throw new SubagentStoppedError('max-tokens', 32_768, 'upstream detail '.repeat(40)) }) await skills.draft(source, undefined, { suggestionId: suggestion.id }) await vi.waitFor(() => expect(host.warn).toHaveBeenCalledOnce()) expect(runTask).toHaveBeenCalledOnce() const saved = (await source.read('suggestions')).find(entry => entry.id === suggestion.id)! expect(saved).toMatchObject({ status: 'pending', lastError: expect.stringContaining('32768') }) expect(saved.lastError).toContain('skills.draftRetryMaxTokens') expect(saved.lastError).toContain('lower') expect(saved.lastError).toContain('shorten the skill') expect(saved.lastError).toMatch(/model with a (?:larger|higher)/u) expect(saved.draftId).toBeUndefined() expect(await source.read('drafts', { skill: 'release-notes' })).toEqual([]) }) it('does not retry a truncated draft after user cancellation', async () => { const { skills, host, runTask } = evolution([]) host.skillTask.mockImplementation(async () => { skills.dispose() throw new SubagentStoppedError('max-tokens', 32_768) }) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(() => expect(host.warn).toHaveBeenCalledOnce()) expect(runTask).toHaveBeenCalledOnce() expect(await source.read('drafts', { skill: 'release-notes' })).toEqual([]) }) it('does not start a third attempt when file-validation repair then hits max-tokens', async () => { const { skills, host, runTask } = evolution([ () => ({ content: '# missing frontmatter', notes: '', changes: [] }), () => new SubagentStoppedError('max-tokens', 32_768), ]) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(() => expect(host.warn).toHaveBeenCalledOnce()) expect(runTask).toHaveBeenCalledTimes(2) expect(host.skillTask.mock.calls.map(call => call[7])).toEqual([32_768, 32_768]) expect(await source.read('drafts', { skill: 'release-notes' })).toEqual([]) }) it('does not save a completed model result after user cancellation', async () => { const { skills, host, runTask } = evolution([]) const file = join(directory, 'dsh', 'skills', 'release-notes', 'SKILL.md') const original = readFileSync(file, 'utf8') host.skillTask.mockImplementation(async () => { skills.dispose() return { structured: { content: original + '2. Group by component\n', notes: '', changes: [] } } }) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(() => expect(host.warn).toHaveBeenCalledOnce()) expect(runTask).toHaveBeenCalledOnce() expect(await source.read('drafts', { skill: 'release-notes' })).toEqual([]) expect(readFileSync(file, 'utf8')).toBe(original) }) it.each([ new SubagentStoppedError('cancelled', 32_768), new Error('provider rejected max_tokens'), new Error('memory subagent stopped with max-tokens'), ])('does not retry a draft error without a real max-tokens stop: %s', async error => { const { skills, host, runTask } = evolution([() => error]) await skills.draft(source, undefined, { skill: 'release-notes' }) await vi.waitFor(() => expect(host.warn).toHaveBeenCalledOnce()) expect(runTask).toHaveBeenCalledOnce() expect(await source.read('drafts', { skill: 'release-notes' })).toEqual([]) }) it.each([false, true])('uses a fresh comparison baseline when a draft picks a model (picked=%s)', async picked => { await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Grouped notes', prompt: 'Write v2 notes', checks: [{ text: 'Grouped by component', must: true }] } }) const { skills, host } = evolution([]) host.skillTask.mockImplementation(async (_parent: HostAgent, label: string) => { if (label === 'Mnemon skill draft') return { structured: { content: '---\nname: release-notes\ndescription: Group release notes.\n---\n\n1. Group by component\n', notes: '', changes: [], } } if (label.startsWith('Mnemon skill eval')) return { structured: { steps: ['read'], answer: 'notes' } } return { structured: { checks: [{ index: 1, pass: true, note: 'ok' }], summary: 'ok' } } }) const baseline = await skills.backtest(source, undefined, { skillName: 'release-notes', target: { kind: 'current' } }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => expect((await source.read('run', { id: baseline.runId })).status).toBe('completed')) host.skillTask.mockClear() await skills.draft(source, undefined, { skill: 'release-notes', ...(picked ? { route: { provider: 'other-provider', model: 'other-model' } } : {}) }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => { const runs = await source.read('runs', { skill: 'release-notes' }) expect(runs).toHaveLength(picked ? 3 : 2) expect(runs.every(run => run.status === 'completed')).toBe(true) }) const [draft] = await source.read('drafts', { skill: 'release-notes' }) expect(draft!.runIds.includes(baseline.runId)).toBe(!picked) expect(host.skillTask.mock.calls.filter(([, label]) => label.startsWith('Mnemon skill eval'))).toHaveLength(picked ? 2 : 1) skills.dispose() }) it('retries a case whose run fails and leaves a case that never runs out of the score', async () => { await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Flaky', prompt: 'Write notes A', checks: [{ text: 'Has notes', must: true }] } }) await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Broken', prompt: 'Write notes B', checks: [{ text: 'Has notes', must: true }] } }) const { skills, host } = evolution([]) const failures = new Map([['Write notes A', 1], ['Write notes B', 2]]) host.skillTask.mockImplementation(async (_parent: HostAgent, label: string, prompt: string) => { if (label.startsWith('Mnemon skill eval')) { const key = prompt.includes('Write notes A') ? 'Write notes A' : 'Write notes B' const left = failures.get(key)! if (left > 0) { failures.set(key, left - 1); throw new Error('memory subagent stopped with max-tokens') } return { structured: { steps: ['read'], answer: 'notes' } } } return { structured: { checks: [{ index: 1, pass: true, note: 'ok' }], summary: 'ok' } } }) const { runId } = await skills.backtest(source, join(directory, 'workspace'), { skillName: 'release-notes', target: { kind: 'current' } }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => expect((await source.read('run', { id: runId })).status).toBe('completed')) const run = await source.read('run', { id: runId }) expect(Object.fromEntries(run.results.map(result => [result.title, result.verdict]))).toEqual({ Flaky: 'pass', Broken: 'error' }) expect(run.results.find(result => result.title === 'Broken')?.error).toContain('max-tokens') expect(run).toMatchObject({ passRate: 1, score: 1, errors: 1 }) }) it('records image-only cases as unmeasured without creating a task Agent or calling a model', async () => { const entry = await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Read a screenshot', prompt: 'Read the attached screenshot', requiresVision: true, checks: [{ text: 'The number is 7', must: true }] } }) const { skills, skillTask, runTask } = evolution([]) for (const kind of ['current', 'none'] as const) { const { runId } = await skills.backtest(source, undefined, { skillName: 'release-notes', target: { kind } }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => expect((await source.read('run', { id: runId })).status).toBe('completed')) const run = await source.read('run', { id: runId }) expect(run.results).toMatchObject([{ caseId: entry.id, verdict: 'error', unmeasuredReason: 'requires-vision', checks: [], steps: [], answer: '' }]) expect(run.progress).toEqual({ done: 1, total: 1 }) expect(run.score).toBeUndefined() expect(run.passRate).toBeUndefined() } expect(runTask).not.toHaveBeenCalled() expect(skillTask).not.toHaveBeenCalled() expect((await source.read('cases'))[0]?.requiresVision).toBe(true) skills.dispose() }) it('grades only text cases in a mixed run and allows a vision flag to be cleared', async () => { const vision = await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Image', prompt: 'Read an image', requiresVision: true, checks: [{ text: 'Has number', must: true }] } }) await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Text', prompt: 'Write notes', checks: [{ text: 'Has notes', must: true }] } }) const { skills, host } = evolution([]) host.skillTask.mockImplementation(async (_parent, label, prompt) => { expect(prompt).not.toContain('Read an image') return { structured: label.startsWith('Mnemon skill eval') ? { steps: ['read'], answer: 'notes' } : { checks: [{ index: 1, pass: true, note: 'ok' }], summary: 'ok' } } }) const { runId } = await skills.backtest(source, undefined, { skillName: 'release-notes', target: { kind: 'current' } }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => expect((await source.read('run', { id: runId })).status).toBe('completed')) expect(await source.read('run', { id: runId })).toMatchObject({ score: 1, passRate: 1, progress: { done: 2, total: 2 } }) expect(host.skillTask).toHaveBeenCalledTimes(2) // Edits from an older client preserve the marker when the field is omitted. const { requiresVision: _flag, ...legacyEdit } = vision expect(await source.mutate('case-save', { case: legacyEdit })).toMatchObject({ requiresVision: true }) await expect(source.mutate('case-save', { case: { ...vision, requiresVision: 'false' } })).rejects.toThrow('requiresVision must be a boolean') const cleared = await source.mutate('case-save', { case: { ...vision, requiresVision: false, prompt: 'The image has been transcribed: 7' } }) expect(cleared.requiresVision ?? false).toBe(false) skills.dispose() }) it('does not use a historical image failure as evidence of a skill failure when drafting', async () => { const entry = await source.mutate('case-save', { case: { skillName: 'release-notes', title: 'Image', prompt: 'Read an image', requiresVision: true, checks: [{ text: 'The number is 7', must: true }] } }) const run = await source.mutate('run-start', { skillName: 'release-notes', target: { kind: 'current' }, caseIds: [entry.id] }) const result = { caseId: entry.id, title: entry.title, verdict: 'fail', score: 0, checks: [{ checkId: entry.checks[0]!.id, pass: false, note: 'Fabricated wrong number' }], steps: [], answer: '' } await source.mutate('run-progress', { id: run.id, result }) await source.mutate('run-finish', { id: run.id, status: 'completed' }) const pack = await source.read('evidence-pack', { skill: 'release-notes' }) const prompt = skillDraftPrompt(pack, [], 'user-dsh') expect(prompt).toContain('Not measured: requires image input') expect(prompt).not.toContain('Fabricated wrong number') expect(prompt).not.toContain('last result: fail') await expect(source.mutate('run-progress', { id: run.id, result: { ...result, unmeasuredReason: 'requires-vision' } })).rejects.toThrow('unmeasuredReason') await expect(source.mutate('run-progress', { id: run.id, result: { ...result, verdict: 'error', unmeasuredReason: 'other' } })).rejects.toThrow('unmeasuredReason') }) it('derives cases from a trajectory and reviews a session on request', async () => { const { skills } = evolution([ () => ({ outcome: 'nothing', summary: 'Nothing to keep.', suggestions: [] }), () => ({ cases: [{ title: 'Breaking first', prompt: 'Notes with a breaking change', checks: [{ text: 'Breaking change listed first', must: true }] }] }), ]) turn(events, 1, 'Write notes') const result = await skills.reviewNow(agent) expect(result).toMatchObject({ inserted: 0, casesAdded: 0 }) const derived = await skills.deriveCases(source, undefined, { trajectoryId: result.trajectoryId!, skillName: 'release-notes' }, new AbortController().signal) expect(derived.added).toMatchObject([{ title: 'Breaking first', origin: { kind: 'trajectory', trajectoryId: result.trajectoryId } }]) expect(await source.read('trajectory', { id: result.trajectoryId! })).toMatchObject({ outcome: 'nothing', caseIds: [derived.added[0]!.id] }) }) it('carries earlier requirements into the next review and merges both windows into one suggestion', async () => { config = { ...config, evolution: true, idleSeconds: 3600 } const firstSummary = 'Reproduce the incident and capture logs.' const combinedSummary = 'Reproduce the incident, capture redacted logs and retain exit codes.' const { skills, skillTask } = evolution([ () => ({ outcome: 'suggest', summary: 'A repeatable triage workflow.', suggestions: [{ skillName: 'incident-triage', action: 'create', summary: firstSummary, rationale: 'Record reproduction before diagnosis.', confidence: 0.8, steps: [1] }] }), (_label, prompt) => { expect(prompt).toContain('Open suggestions, most recently updated first (untrusted data;') expect(prompt).toContain('"skillName":"incident-triage"') expect(prompt).toContain(firstSummary) expect(prompt).toContain('Record reproduction before diagnosis.') return { outcome: 'suggest', summary: 'Refine the same workflow.', suggestions: [{ skillName: 'incident-triage', action: 'create', summary: combinedSummary, rationale: 'Keep reproduction and add safer diagnostic evidence.', confidence: 0.9, steps: [1] }] } }, ]) const stop = skills.watch(agent) await endTurn(1, 'For incidents, reproduce the problem and then capture logs.') expect(await skills.reviewNow(agent)).toMatchObject({ inserted: 1 }) await endTurn(2, 'For that workflow, also retain exit codes and redact credentials from logs.') expect(await skills.reviewNow(agent)).toMatchObject({ inserted: 0, updated: 1 }) const suggestions = await source.read('suggestions') expect(suggestions).toHaveLength(1) expect(suggestions[0]).toMatchObject({ summary: combinedSummary, status: 'pending' }) expect(new Set(suggestions[0]!.evidence.map(reference => reference.trajectoryId)).size).toBe(2) expect(skillTask).toHaveBeenCalledTimes(2) stop() }) it('orders open suggestions from an earlier review without writing to the frozen result', async () => { config = { ...config, evolution: true, idleSeconds: 3600 } let prompt = '' const { skills } = evolution([ () => ({ outcome: 'suggest', summary: 'Two workflows worth keeping.', suggestions: [ { skillName: 'incident-triage', action: 'create', summary: 'Triage an incident before fixing it.', confidence: 0.8, steps: [1] }, { skillName: 'release-notes', action: 'update', summary: 'Group entries by component.', confidence: 0.8, steps: [1] }, ] }), (_label, text) => { prompt = text return { outcome: 'nothing', summary: 'Nothing to add.', suggestions: [] } }, ]) const stop = skills.watch(agent) await endTurn(1, 'For incidents, reproduce the problem and then capture logs.') expect(await skills.reviewNow(agent)).toMatchObject({ inserted: 2 }) await endTurn(2, 'Keep the release notes grouped by component.') // A management read hands back a deeply frozen result, so ordering two open // suggestions must not write to it. expect(await skills.reviewNow(agent)).toMatchObject({ inserted: 0, updated: 0 }) expect(prompt).toContain('"skillName":"incident-triage"') expect(prompt).toContain('"skillName":"release-notes"') stop() }) it('offers an existing unloaded skill for update and omits dismissed suggestions', async () => { const { skills } = evolution([ () => ({ outcome: 'suggest', summary: 'Triage.', suggestions: [{ skillName: 'incident-triage', action: 'create', summary: 'Dismissed workflow', confidence: 0.8, steps: [1] }] }), (_label, prompt) => { expect(prompt).toContain('skills loaded: none') expect(prompt).toContain('- release-notes: Write release notes from a changelog.') expect(prompt).not.toContain('Dismissed workflow') expect(SKILL_REVIEW_PERSONA).toContain('even if it was not loaded in this window') expect(SKILL_REVIEW_PERSONA).not.toContain('If any answer is yes, suggest action="create"') return { outcome: 'suggest', summary: 'Improve notes.', suggestions: [{ skillName: 'release-notes', action: 'update', summary: 'Group notes by component.', confidence: 0.9, steps: [1] }] } }, ]) turn(events, 1, 'Capture an incident workflow.') await skills.reviewNow(agent) const [first] = await source.read('suggestions') await source.mutate('suggestion-dismiss', { id: first!.id }) turn(events, 2, 'Write release notes, grouped by component.') await skills.reviewNow(agent) expect(await source.read('suggestions', { status: ['pending'] })).toMatchObject([{ skillName: 'release-notes', action: 'update' }]) }) it('settles a hung draft even if its task ignores cancellation, and rejects its late result', async () => { config = { ...config, evolution: true, autoBacktest: false, idleSeconds: 3600 } const { skills, runTask } = evolution([mixedReview]) const stop = skills.watch(agent) await endTurn(1, 'Capture incident logs and group release notes.') await skills.reviewNow(agent) const suggestion = (await source.read('suggestions'))[0]! let finish!: (value: unknown) => void runTask.mockImplementation(() => new Promise(resolve => { finish = resolve })) await skills.draft(source, undefined, { suggestionId: suggestion.id }) await vi.advanceTimersByTimeAsync(16 * 60_000) expect((await source.read('suggestions')).find(item => item.id === suggestion.id)).toMatchObject({ status: 'pending', lastError: 'skill draft did not finish within 15 minutes' }) finish({ structured: { content: `---\nname: ${suggestion.skillName}\ndescription: New skill.\n---\nBody`, notes: '', changes: [] } }) await vi.advanceTimersByTimeAsync(0) expect(await source.read('drafts')).toEqual([]) skills.dispose() stop() }) it.each(['cancel', 'deadline'] as const)('settles a hung backtest on %s and frees its slot', async mode => { const { skills, runTask } = evolution([]) const entry = await source.mutate('case-save', { skillName: 'release-notes', title: 'Case', prompt: 'Check', checks: [{ text: 'Pass', must: true }], enabled: true }) const signals: AbortSignal[] = [] runTask.mockImplementation((_root, signal) => { signals.push(signal); return new Promise(() => undefined) }) const input = { skillName: 'release-notes', target: { kind: 'none' as const }, caseIds: [entry.id] } const first = await skills.backtest(source, undefined, input) await skills.backtest(source, undefined, input) const queued = await skills.backtest(source, undefined, input) expect(signals).toHaveLength(2) if (mode === 'cancel') await source.mutate('run-cancel', { id: first.runId }) await vi.advanceTimersByTimeAsync(mode === 'cancel' ? 1_100 : 46 * 60_000) expect((await source.read('run', { id: first.runId })).status).toBe('interrupted') expect(signals[0]!.aborted).toBe(true) if (mode === 'cancel') { await vi.waitFor(() => expect(signals).toHaveLength(3)) expect((await source.read('run', { id: queued.runId })).status).toBe('running') } await expect(skills.backtest(source, undefined, input)).resolves.toHaveProperty('runId') skills.dispose() await vi.advanceTimersByTimeAsync(0) }, 20_000) it('returns a suggestion to pending when its draft task outlives the deadline', async () => { config = { ...config, evolution: true, autoBacktest: false, idleSeconds: 3600 } const { skills, runTask } = evolution([mixedReview]) const stop = skills.watch(agent) await endTurn(1, 'Capture incident logs and group release notes.') await skills.reviewNow(agent) const suggestion = (await source.read('suggestions'))[0]! // A task that stops reporting settles only when the draft deadline aborts it. runTask.mockImplementation((_root, signal: AbortSignal) => new Promise((_resolve, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true }) })) await skills.draft(source, join(directory, 'workspace'), { suggestionId: suggestion.id }) await vi.advanceTimersByTimeAsync(16 * 60 * 1000) await vi.waitFor(async () => { const after = (await source.read('suggestions')).find(entry => entry.id === suggestion.id)! expect(after.status).toBe('pending') expect(after.lastError).toBe('skill draft did not finish within 15 minutes') }) stop() }) it('drafts supporting reference files and passes them through backtesting (#654)', async () => { // An oversized model response must not silently drop file changes. expect(() => parseSkillDraft({ content: 'Skill', files: Array.from({ length: 21 }, (_, i) => ({ path: `references/${i}.md`, action: 'upsert', content: 'Reference', })) })).toThrow('at most 20') expect(parseSkillDraft({ content: '---\nname: a\ndescription: A.\n---\nBody\n', notes: 'n', changes: ['c'], files: [], })).toEqual({ content: '---\nname: a\ndescription: A.\n---\nBody\n', notes: 'n', changes: ['c'] }) expect(parseSkillDraft({ content: '---\nname: a\ndescription: A.\n---\nSee [ref](references/guide.md).\n', notes: 'n', changes: ['c'], files: [{ path: 'references/guide.md', action: 'upsert', content: '# Guide\n' }], }).files).toEqual([{ path: 'references/guide.md', action: 'upsert', content: '# Guide\n' }]) const refsDir = join(directory, 'dsh', 'skills', 'release-notes', 'references') mkdirSync(refsDir, { recursive: true }) writeFileSync(join(refsDir, 'format.md'), '# Legacy format\n') writeFileSync(join(refsDir, 'old.md'), 'Obsolete template\n') const evalCase = await source.mutate('case-save', { skillName: 'release-notes', title: 'Checklist flow', prompt: 'Prepare release notes', checks: [{ text: 'Uses checklist reference', must: true }], enabled: true, }) const prompts: Array<{ label: string; prompt: string }> = [] config = { ...config, autoBacktest: true } const { skills, host } = evolution([]) host.skillTask.mockImplementation(async (_parent: HostAgent, label: string, prompt: string) => { prompts.push({ label, prompt }) if (label === 'Mnemon skill draft') { return { structured: { content: '---\nname: release-notes\ndescription: Write release notes cleanly.\n---\n\n# release-notes\n\n1. Follow [checklist](references/checklist.md) and [format](references/format.md).\n', notes: 'Moved checklist out of SKILL.md and dropped obsolete file.', changes: ['Trimmed SKILL.md', 'Added references/checklist.md', 'Removed references/old.md'], files: [ { path: 'references/checklist.md', action: 'upsert', content: '# Checklist\n\n1. Verify tags.\n' }, { path: 'references/format.md', action: 'upsert', content: '# New format\n' }, { path: 'references/old.md', action: 'delete' }, ], } } } if (label.startsWith('Mnemon skill eval:')) { return { structured: { steps: ['Read references/checklist.md'], answer: prompt.includes('## references/checklist.md') ? 'Draft notes' : 'Baseline notes' } } } return { structured: { checks: [{ index: 1, pass: true, note: 'Checked' }], summary: 'Pass' } } }) await skills.draft(source, join(directory, 'workspace'), { skill: 'release-notes' }) await vi.advanceTimersByTimeAsync(0) await vi.waitFor(async () => { const [draft] = await source.read('drafts', { skill: 'release-notes' }) expect(draft).toBeDefined() const view = await source.read('draft', { id: draft!.id }) expect(view.runs).toHaveLength(2) expect(view.runs.every(run => run.status === 'completed')).toBe(true) }) const [draft] = await source.read('drafts', { skill: 'release-notes' }) expect(draft!.files).toHaveLength(3) const draftPrompt = prompts.find(entry => entry.label.includes('draft'))!.prompt expect(draftPrompt).toContain(' entry.label.includes('eval') && entry.prompt.includes(' entry.label.includes('eval') && entry.prompt.includes('Obsolete template'))!.prompt expect(baseEvalPrompt).toContain('# Legacy format') expect(skillExecutorPrompt(evalCase, { name: 'release-notes', content: 'Body only' })).not.toContain('('draft-adopt', { id: draft!.id }) expect(adopted.skill.layout).toBe('bundle') expect(readFileSync(join(refsDir, 'checklist.md'), 'utf8')).toContain('Verify tags') expect(readFileSync(join(refsDir, 'format.md'), 'utf8')).toBe('# New format\n') expect(() => readFileSync(join(refsDir, 'old.md'), 'utf8')).toThrow() skills.dispose() }) }) describe('bounded skill review context', () => { it('shows full UTF-8 sizes and layouts even when loaded content is truncated or metadata is absent', () => { const content = '字'.repeat(23_000) const prompt = skillReviewPrompt({ steps: [], stats: { turns: 1, toolCalls: 0, toolFailures: 0, skills: ['large'] }, score: 1, threshold: 1, loaded: [{ name: 'large', root: 'user-dsh', path: '/skills/large/SKILL.md', content, layout: 'bundle' }], catalog: [ { name: 'large', description: 'Large workflow.', layout: 'bundle', bytes: 69_000 }, { name: 'near', description: 'Single file.', layout: 'flat', bytes: 64_000 }, { name: 'legacy', description: 'No optional metadata.' }, ], caseTitles: {}, openSuggestions: [], }) expect(prompt).toContain('69000 UTF-8 bytes') expect(prompt).toContain('64000 UTF-8 bytes') expect(prompt).toContain('layout=bundle') expect(prompt).toContain('layout=flat') expect(prompt).toContain('65536') expect(prompt).toContain('- legacy: No optional metadata.') expect(prompt).not.toContain('undefined') expect(prompt).toContain('[truncated]') expect(prompt).not.toContain(content) }) it('limits open suggestions and their wording without exposing evidence or draft payloads', () => { const prompt = skillReviewPrompt({ steps: [], stats: { turns: 0, toolCalls: 0, toolFailures: 0, skills: [] }, score: 0, threshold: 1, loaded: [], catalog: [], caseTitles: {}, openSuggestions: Array.from({ length: 30 }, (_, index) => ({ skillName: `workflow-${index}`, action: 'create', status: 'pending', confidence: 0.8, summary: 's'.repeat(2000), rationale: 'r'.repeat(2000), updatedAt: '2026-10-26T00:00:00.000Z', evidence: 'private trajectory payload', draft: 'private draft payload', })), }) const rows = prompt.split('\n').filter(line => line.startsWith('{')).map(line => JSON.parse(line)) expect(rows).toHaveLength(20) expect(rows[0].summary).toHaveLength(600) expect(rows[0].rationale).toHaveLength(400) expect(prompt).not.toContain('private trajectory payload') expect(prompt).not.toContain('private draft payload') expect(prompt.length).toBeLessThan(26_000) }) })