Files
deepseek-harness/packages/context/harness-dev-context/tests/harness-dev-context.spec.ts
T
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00

287 lines
16 KiB
TypeScript

/** Prompt stability of the harness checkout and Web GUI URL across processes, checkouts, and ports. */
import { describe, expect, it, onTestFinished } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit'
import {
createUserMessage, createMessage, LlmAdapter,
type GenerateOptions, type LlmResolvedModelInfo, type StreamChunk, type SystemPromptUpdate, type SystemMessage,
} from '@deepseek-ai/dsh-llm'
import type { SessionId, Session } from '@deepseek-ai/dsh-session'
import { renderContextSnapshot, renderPrompt } from '@deepseek-ai/dsh-system-prompt'
import * as HarnessDevContext from '../src/index.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
const SOURCE_PROMPT = 'The runtime context names the DeepSeek Harness implementation checkout. The checkout location and current working directory are separate values and may differ; never infer the working directory from the checkout path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself.'
const WEB_GUIDANCE = 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. '
+ 'The browser provides no implicit DOM, route, or screenshot context. '
+ 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while '
+ '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. '
+ 'Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. '
+ 'Starting another server does not update this GUI. '
+ 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. '
+ 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.'
const WEB_PROMPT = `You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. ${WEB_GUIDANCE}`
/** The value-bearing paragraphs earlier releases rendered. */
const LEGACY_SOURCE = 'The DeepSeek Harness implementation checkout is at /old/checkout/. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself.'
// Frozen as earlier releases rendered it, independent of the current guidance.
const LEGACY_WEB = 'You are interacting with the user through the DeepSeek Harness Web GUI at http://127.0.0.1:3100. '
+ 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. '
+ 'The browser provides no implicit DOM, route, or screenshot context. '
+ 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while '
+ '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. '
+ 'Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. '
+ 'Starting another server does not update this GUI. '
+ 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. '
+ 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.'
/** Records every request and answers each with one short text reply. */
class RecordingAdapter extends LlmAdapter {
readonly requests: GenerateOptions[] = []
constructor(private readonly systemPromptUpdate: SystemPromptUpdate | undefined) {
super()
}
override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
return Promise.resolve({
provider, id: model, name: model,
...this.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: this.systemPromptUpdate },
})
}
async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
this.requests.push(options)
yield { type: 'block-start', index: 0, blockType: 'text' }
yield { type: 'text-delta', index: 0, text: 'ok' }
yield { type: 'block-end', index: 0, block: { type: 'text', text: 'ok' } }
yield { type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } }
yield { type: 'finish', reason: { kind: 'stop' } }
}
}
const ROUTE = { provider: 'route', model: 'model' }
/** The Web GUI service with a port the test can move, as restarted processes see it. */
function provideWebServices(ctx: Context): { port: number } {
const listener = { port: 4567 }
ctx.provide('webApp', {
getAdvertisedUrl: () => `http://127.0.0.1:${String(listener.port)}`,
} satisfies Context['webApp'])
return listener
}
/** A production AgentLoop with this plugin mounted. */
async function promptLoop(systemPromptUpdate: SystemPromptUpdate | undefined) {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
const listener = provideWebServices(ctx)
await mountAgentLoopTestDependencies(ctx)
const adapter = new RecordingAdapter(systemPromptUpdate)
ctx.llm.registerAdapter([ROUTE.provider], adapter)
await ctx.plugin(HarnessDevContext)
const harness = await mountAgentLoopTestHarness(ctx)
/** Resume the Session's complete log under a new Agent, as a restarted process does. */
const resume = async (session: Session, id: string): Promise<Agent> => (await ctx.agents.create({
sessionId: brandString<SessionId>(id), agentOptions: ROUTE, seed: [...session.snapshotEvents()],
})).agent
/** One turn under an earlier release: the given paragraphs and no value contexts. */
const earlierSession = async (source = LEGACY_SOURCE, web = LEGACY_WEB): Promise<Agent> => {
const earlierRelease = ctx.on('system-prompt/assemble', async (_assembly, _context, next) => {
const assembly = await next()
return {
...assembly,
sections: assembly.sections.map(section => section.name === 'harness:source' ? { ...section, text: source }
: section.name === 'app:web-surface' ? { ...section, text: web } : section),
contexts: assembly.contexts.filter(entry => entry.name !== 'harness:source' && entry.name !== 'app:web-surface'),
}
})
const agent = await harness.create(brandString<SessionId>('earlier'), ROUTE)
await send(agent, 'before the upgrade')
earlierRelease()
return agent
}
return { ctx, listener, adapter, harness, resume, earlierSession }
}
async function send(agent: Agent, text: string): Promise<void> {
agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
await agent.whenIdle()
}
/** Every committed system prompt version in event order; a cleared version is `''`. */
function systemPrompts(session: Session): string[] {
return session.snapshotEvents().flatMap(event => event.type === 'system/message'
? [event.data.message.content.map(block => block.type === 'text' ? block.text : '').join('')]
: [])
}
function latestRuntimeContext(session: Session): string | undefined {
const event = session.snapshotEvents().findLast(entry => entry.type === 'user/message'
&& entry.data.source.kind === 'runtime-context')
const block = event?.type === 'user/message' ? event.data.content[0] : undefined
return block?.type === 'text' ? block.text : undefined
}
function requestSystemPrompts(request: GenerateOptions | undefined): string[] {
return (request?.messages ?? []).filter(message => message.role === 'system')
.map(message => message.content.map(block => block.type === 'text' ? block.text : '').join(''))
}
describe('harness-dev-context', () => {
it('registers value-free sections and reports the checkout and Web GUI URL as runtime context', async () => {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
provideWebServices(ctx)
await mountAgentLoopTestDependencies(ctx)
const fiber = ctx.plugin(HarnessDevContext)
await fiber
const assembly = await ctx.systemPrompt.assemble()
expect(assembly.sections.filter(entry => entry.name === 'harness:source' || entry.name === 'app:web-surface')
.map(entry => entry.text)).toEqual([SOURCE_PROMPT, WEB_PROMPT])
expect(renderPrompt(assembly)).not.toContain('127.0.0.1')
expect(renderContextSnapshot(assembly).split('\n\n').slice(1)).toEqual([
expect.stringMatching(/^Current DeepSeek Harness implementation checkout: ".+"\.$/u),
'Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:4567".',
])
await fiber.dispose()
const disposed = await ctx.systemPrompt.assemble()
expect(disposed.sections.filter(entry => entry.name === 'harness:source' || entry.name === 'app:web-surface')).toEqual([])
expect(admittedMessages(disposed)).toEqual([])
expect(disposed.contexts).toEqual([])
})
it.each([
{ route: 'replace-only', systemPromptUpdate: undefined },
{ route: 'in-history', systemPromptUpdate: 'in-history' as const },
])('resumes an earlier-format Session on other ports without rewriting its system prompt ($route)', async ({ systemPromptUpdate }) => {
const h = await promptLoop(systemPromptUpdate)
const original = await h.earlierSession()
const logged = systemPrompts(original.session)
expect(logged).toHaveLength(1)
expect(logged[0]).toContain(LEGACY_SOURCE)
expect(logged[0]).toContain(LEGACY_WEB)
let session = original.session
for (const port of [4568, 4569]) {
h.listener.port = port
const resumed = await h.resume(session, `earlier-on-${String(port)}`)
await send(resumed, `after the upgrade on ${String(port)}`)
expect(systemPrompts(resumed.session)).toEqual(logged)
expect(requestSystemPrompts(h.adapter.requests.at(-1))).toEqual(logged)
expect(latestRuntimeContext(resumed.session))
.toContain(`Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:${String(port)}".`)
expect(latestRuntimeContext(resumed.session)).toContain('Current DeepSeek Harness implementation checkout: "')
session = resumed.session
}
})
it('retains legacy paragraphs through repeated and empty history and retires only the named section', async () => {
const h = await promptLoop(undefined)
const agent = await h.harness.create(brandString<SessionId>('legacy-metadata'), ROUTE)
agent.session.append('turn/start', { turn: 1 })
agent.session.append('step/start', { turn: 1, step: 1 })
const append = (message: SystemMessage) => agent.session.append('system/message', {
turn: 1, step: 1, message,
}, { surfaceOp: 'append' })
const current = async () => renderPrompt(await h.ctx.systemPrompt.assemble({ agent }))
append(createMessage({ role: 'system', content: [
{ type: 'text', text: LEGACY_SOURCE },
{ type: 'reasoning', text: 'unrelated legacy content' },
{ type: 'text', text: `\n\n${LEGACY_WEB}` },
], source: { kind: 'system-prompt' } }))
expect(await current()).toContain(LEGACY_SOURCE)
expect(await current()).toContain(LEGACY_WEB)
// An upgraded Session can hold several whole-prompt messages with the same paragraphs.
append(createMessage({ role: 'system', content: [
{ type: 'text', text: `${LEGACY_SOURCE}\n\n${LEGACY_WEB}\n\nA later whole-prompt addition.` },
], source: { kind: 'system-prompt' } }))
expect(await current()).toContain(LEGACY_SOURCE)
expect(await current()).toContain(LEGACY_WEB)
append(createMessage({ role: 'system', content: [], source: { kind: 'system-prompt' } }))
expect(await current()).toContain(LEGACY_SOURCE)
expect(await current()).toContain(LEGACY_WEB)
append(createMessage({ role: 'system', content: [{ type: 'text', text: 'The checkout instructions no longer apply.' }],
source: { kind: 'system-prompt', sections: [{ name: 'harness:source', state: 'retired', noticeIndex: [0] }] },
}))
expect(await current()).toContain(SOURCE_PROMPT)
expect(await current()).not.toContain(LEGACY_SOURCE)
expect(await current()).toContain(LEGACY_WEB)
append(createMessage({ role: 'system', content: [{ type: 'text', text: 'The Web instructions no longer apply.' }],
source: { kind: 'system-prompt', sections: [{ name: 'app:web-surface', state: 'retired', noticeIndex: [0] }] },
}))
expect(await current()).toContain(WEB_PROMPT)
expect(await current()).not.toContain(LEGACY_WEB)
append(createMessage({ role: 'system', content: [
{ type: 'text', text: 'Replacement notice.\n\n' }, { type: 'text', text: LEGACY_WEB },
], source: { kind: 'system-prompt', sections: [
{ name: 'app:web-surface', order: 1, state: 'active', contentIndex: 1, noticeIndex: [0] },
] } }))
expect(await current()).toContain(LEGACY_WEB)
append(createMessage({ role: 'system', content: [{ type: 'text', text: 'No earlier sections apply.' }],
source: { kind: 'system-prompt', reset: true, sections: [] },
}))
expect(await current()).not.toContain(LEGACY_WEB)
agent.session.append('step/end', { turn: 1, step: 1 })
agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
})
it('keeps earlier paragraphs and additions across an explicit series start', async () => {
const h = await promptLoop('in-history')
const resumed = await h.resume((await h.earlierSession()).session, 'earlier-consolidated')
const [earlier] = systemPrompts(resumed.session)
const update = h.ctx.systemPrompt.section({ name: 'test:update', order: 0, text: 'Updated instruction.' })
await send(resumed, 'append the update')
expect(systemPrompts(resumed.session)).toHaveLength(2)
update()
h.ctx.on('agent/pre-step', async (_payload, next) => {
const decision = await next()
return decision.kind === 'enter' ? { ...decision, startsRequestSeries: true } : decision
})
await send(resumed, 'start a new series')
const expected = [earlier, 'Updated instruction.', 'The earlier instructions from test:update no longer apply.']
expect(systemPrompts(resumed.session)).toEqual(expected)
await send(resumed, 'continue the series')
expect(systemPrompts(resumed.session)).toHaveLength(3)
expect(requestSystemPrompts(h.adapter.requests.at(-1))).toEqual(expected)
})
it.each([
{ variant: 'a paragraph without the fixed ending', source: 'The DeepSeek Harness implementation checkout is at /old/checkout/.' },
{ variant: 'a paragraph broken across lines', source: LEGACY_SOURCE.replace('/old/checkout/', '/old/\ncheckout/') },
])('replaces text that only resembles an earlier paragraph: $variant', async ({ source }) => {
const h = await promptLoop(undefined)
const original = await h.earlierSession(source, WEB_PROMPT)
const resumed = await h.resume(original.session, 'resembling')
await send(resumed, 'after the upgrade')
const current = systemPrompts(resumed.session).at(-1)
expect(current).toContain(SOURCE_PROMPT)
expect(current).not.toContain('/old/')
})
it('keeps a new Session system prompt free of process values across ports', async () => {
const h = await promptLoop(undefined)
const agent = await h.harness.create(brandString<SessionId>('fresh'), ROUTE)
await send(agent, 'first')
const logged = systemPrompts(agent.session)
expect(logged).toHaveLength(1)
expect(logged[0]).toContain(SOURCE_PROMPT)
expect(logged[0]).toContain(WEB_PROMPT)
expect(logged[0]).not.toContain('127.0.0.1')
expect(latestRuntimeContext(agent.session)).toContain('Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:4567".')
h.listener.port = 4568
const resumed = await h.resume(agent.session, 'fresh-on-4568')
await send(resumed, 'second')
expect(systemPrompts(resumed.session)).toEqual(logged)
expect(latestRuntimeContext(resumed.session)).toContain('Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:4568".')
})
})
function admittedMessages(assembly: import('@deepseek-ai/dsh-system-prompt').PromptAssembly) {
return assembly.systemUpdates(false).map(update => update.message)
}