Files
deepseek-harness/scripts/persistence-developer.spec.ts
Yixiang TuandTianyi Cui e0bd7e1960 feat(session): add developer changes using historical tool schemas
Session V4 reserves developer-role messages for incremental model-visible
session changes. The role, tool addition/removal blocks, and deferred-loading
marker need a durable representation before independent provider and UI
integrations can emit or consume them. Known developer events must match an
open turn and step; unsupported providers and UI consumers fail explicitly.

Request headers already capture full tool definitions. Persisting another
ToolSchema in each addition would duplicate Session information and create
two definitions that could drift. Additions therefore store toolName, and
the containing developer event uses headerSeq to select one earlier known
request/header for all its additions. A same-name replacement keeps its
historical definition identity through restart, fork and surface changes.
Removals require no definition copy, and ordinary developer messages omit
headerSeq. Generic sourceEventSeqs remains independent derivation metadata.

The rejected inline tool field is optional never with @persistenceReserved.
The schema extractor retains that uninhabited slot, so permitting a future
value requires a format bump instead of being mistaken for compatible
optional metadata. Unrelated optional fields remain additive and readable.

Native and Session admission reject missing, forward, non-header, unknown,
ambiguous and incomplete referenced definitions, and reject the retired
inline tool field. Validate complete schema fields only for referenced
definitions, preserving unrelated header behavior and extra JSON metadata.
Unknown ignorable records remain opaque. Empty developer nodes retain their
surface position without producing a message or shadowing the system head.
No automatic emitter, provider activation, UI implementation, or speculative
public resolver is added.

Keep the core-owned developer source binding beside the introduced role,
including the request-only type rejection and attribution round trips. Update
consumer guards, SDK/snapshot handling, bilingual owner documentation, and
the same unreleased V4 acknowledgement. Keep earlier tool/source migration
work and its documentation in the parent. Preserve the existing recorded
Cordis inspection generation from the original developer change.

Integration keeps the final source layer as the sole parent and preserves
master's Messages input filtering, empty-user omission, empty tool results,
and system-update placement. Developer/deferred guards still run before
conversion. Native V4 admission, header references, reservation declarations,
and generic tooling match the validated marker candidate. Parent-owned
fixture and generator fixes remain in the parent.

Earlier feature validation passed full build, full lint, 41 doc-sync gates,
and 16 hygiene gates. The unchanged native implementation retains that evidence.
The focused Session/V4/request-input run passes 884 tests across 38 files with
100% statement, branch, function and line coverage for the V3-to-V4 package
and Session surface. Consumer tests pass 482 with one existing skip; tool,
message and optional-field tests pass 146. Cordis inspection and compaction
replays pass in both source and built modes (two cases per mode). Ten invalid
referenced-definition/unknown-header controls failed before their scoped
guards and pass after them.

Reservation validation: the actual generated developer root records tool as
optional primitive never. Widening it requires a bump, while traceId remains
additive and preserved; all 85 focused reader/classifier tests pass.

Final-parent validation: 205 tests across eight provider, type, catalog,
Session and native-format files pass. The preserved parent fixture verifies
Messages input-history replay; runtime/declaration and parent-owned-file
comparisons show no loss during the final rebase.

Co-authored-by: Tianyi Cui <53024+tianyicui@users.noreply.github.com>
2026-09-18 19:08:11 +08:00

69 lines
4.7 KiB
TypeScript

/** Developer field classification matches native admission and metadata preservation. */
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { Session, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format'
import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
import { canonicalizeSchema, schemaDigest } from './persistence-schema-model.ts'
import { classifyPersistenceChange, parsePersistenceSnapshot } from './persistence-changes.ts'
function toolAdditionSchema() {
const inventory = parsePersistenceSnapshot(JSON.parse(readFileSync(new URL('../docs/persistence-schema.json', import.meta.url), 'utf8')) as unknown)
const before = inventory.roots.find(root => root.key === 'event:developer/message')!
const nodes = [...structuredClone(before.schema.nodes)]
const blockIndex = nodes.findIndex(node => node.kind === 'object' && node.properties.some((property) => {
const type = nodes[property.type]
return property.name === 'type' && type?.kind === 'literal' && type.value === 'tool-addition'
}))
const block = nodes[blockIndex]!
if (block.kind !== 'object') throw new Error('missing tool-addition schema')
const stringIndex = nodes.findIndex(node => node.kind === 'primitive' && node.type === 'string')
return { before, nodes, blockIndex, block, stringIndex }
}
describe('developer field compatibility', () => {
it('requires a version bump before a future declaration can use the rejected inline tool field', () => {
const { before, nodes, blockIndex, block, stringIndex } = toolAdditionSchema()
nodes[blockIndex] = { ...block, properties: [
...block.properties.filter(property => property.name !== 'tool'),
{ name: 'tool', type: stringIndex, optional: true },
] }
const schema = canonicalizeSchema(nodes, 0)
expect(classifyPersistenceChange(before, { ...before, schema, digest: schemaDigest(schema) }))
.toContainEqual(expect.objectContaining({ requiresVersionBump: true }))
const reserved = block.properties.find(property => property.name === 'tool')
expect(reserved).toMatchObject({ optional: true })
expect(before.schema.nodes[reserved!.type]).toEqual({ kind: 'primitive', type: 'never' })
const event: SessionFormatEvent = { type: 'developer/message', seq: 3, time: 4, surfaceOp: 'append', data: {
turn: 1, step: 1, headerSeq: 2, message: { id: 'legacy-inline', role: 'developer', source: { kind: 'tool-registry' },
content: [{ type: 'tool-addition', toolName: 'search', tool: 'optional metadata' }],
},
} }
expect(() => sessionFormatCatalog.encodeCurrentEvent(event)).toThrow('omit inline tool definitions')
})
it('accepts and preserves a tool-addition field classified as optional', () => {
const { before, nodes, blockIndex, block, stringIndex } = toolAdditionSchema()
nodes[blockIndex] = { ...block, properties: [...block.properties, { name: 'traceId', type: stringIndex, optional: true }] }
const schema = canonicalizeSchema(nodes, 0)
expect(classifyPersistenceChange(before, { ...before, schema, digest: schemaDigest(schema) })).toMatchObject([{ kind: 'optional-property-added', requiresVersionBump: false }])
const header = { version: 4, id: 'optional-developer-field', createdAt: 1, isSeeded: false, delegationDepth: 0 }
const message = { id: 'developer', role: 'developer', source: { kind: 'tool-registry', extra: true },
content: [{ type: 'tool-addition', toolName: 'search', traceId: 'retained' }], extra: true }
const events: SessionFormatEvent[] = [
{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
{ type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } },
{ type: 'request/header', seq: 2, time: 3, data: { reason: 'initial', header: { config: { provider: 'test', model: 'test' }, tools: [{ name: 'search', description: 'Search', parameters: {} }] } } },
{ type: 'developer/message', seq: 3, time: 4, surfaceOp: 'append', data: { turn: 1, step: 1, headerSeq: 2, message, extra: true } },
]
const reader = sessionFormatCatalog.createRestore(sessionFormatCatalog.encodeCurrentHeader(header, 0), { recovery: 'strict', validation: 'current' })
for (const event of events) reader.decodeRow(sessionFormatCatalog.encodeCurrentEvent(event))
const artifact = reader.finish()
expect(artifact.events).toEqual(events)
const restored = Session.fromRestore(SessionId(header.id), artifact.events as SessionEvent[],
artifact.header as unknown as SessionHeader, SessionLogOffset(0), 'detached')
expect(restored.deriveMessages()).toEqual([message])
})
})