fix(workspace-context): guard baseline restoration
This commit is contained in:
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/context/workspace-context/README.md
|
||||
README.md: 8201a9bb347c27da432748576151a0f6db9f3d9f
|
||||
README.zh.md: adcf50d70fe685a0cf8604405be5568fbcb409c1
|
||||
README.md: c79f208705c827c609a4b482f0057a18ac0d8fc0
|
||||
README.zh.md: aacdcc9b2b12aca8394fb87099af0c382677bef1
|
||||
|
||||
@@ -6,7 +6,7 @@ Per-session workspace instruction loading for `AGENTS.md`-compatible files. The
|
||||
|
||||
## Lifecycle
|
||||
|
||||
The baseline is injected at the first `agent/step` of each live session. It reads `$DSH_HOME/AGENTS.md` followed by, in each directory from the project root to `agent.session.header.cwd`, every existing base candidate and then every existing local-overlay candidate. Within one directory, candidates whose content is byte-identical after trimming leading and trailing whitespace collapse to the earliest candidate in configured order, so a `CLAUDE.md` that merely duplicates its sibling `AGENTS.md` is rendered once. The durable sourced `user/message` enters the same request as the claimed prompt. If a later surface replacement such as compaction shadows that baseline, `system-prompt/assemble` recomposes and injects the current chain before the loop snapshots its next request.
|
||||
The baseline is injected at the first `agent/step` of each live session. It reads `$DSH_HOME/AGENTS.md` followed by, in each directory from the project root to `agent.session.header.cwd`, every existing base candidate and then every existing local-overlay candidate. Within one directory, candidates whose content is byte-identical after trimming leading and trailing whitespace collapse to the earliest candidate in configured order, so a `CLAUDE.md` that merely duplicates its sibling `AGENTS.md` is rendered once. The durable sourced `user/message` enters the same request as the claimed prompt. If a later surface replacement such as compaction shadows that baseline, a model-request `system-prompt/assemble` recomposes and injects the current chain before the loop snapshots that request; inspection-only assemblies such as TUI `/status` do not mutate the session.
|
||||
|
||||
The plugin also listens on `tools/post-execute` for successful first-party `read`, `write`, and `edit` calls. Each touch checks newly reached descendant scopes and every previously loaded scope. Each configured candidate name is an independent scope in its directory: a newly present file is attached through the result's `additionalContexts`; a changed file appends a replacement; a file that disappears or becomes a per-directory duplicate of an earlier candidate appends a removal notice. Native calls and Code Mode sub-dispatches share this path: `run_code` defers each nested context until its outer result, so the loop still appends updates after tool-call/result adjacency is complete. This follows structured filesystem activity rather than shell `cd`, because each local bash call starts a fresh shell and parsing arbitrary shell syntax would be unreliable.
|
||||
|
||||
@@ -52,7 +52,7 @@ Model-visible text contains no hidden state markers. Each baseline or dynamic co
|
||||
|
||||
An unchanged path and SHA-1 content digest is not injected again. A per-session, per-scope provider cache stores only `{ path, version, digest, trimmedDigest }`: when the provider's opaque `FsVersion` and the effective visible state both match, reconciliation skips the content read; a changed version triggers a bounded read and SHA-1 confirmation before any model-visible update. The `trimmedDigest` — SHA-1 over the whitespace-trimmed content — is the per-directory duplicate key, so an unchanged file can still be removed when an earlier candidate converges on its content. Resume works because SHA-1 state is persisted in the typed source, while an empty in-memory version cache merely causes one confirming read. Compaction re-arms a scope after its context event leaves the visible surface even when the cached version is unchanged. A removal is a tombstone, so a later candidate reappearance is loaded again. Only model-visible changes actually rendered within the byte budget enter the source, pending state, and version cache; an omitted change remains eligible for a later touch, while a same-digest version refresh updates only the provider cache.
|
||||
|
||||
The initial baseline event itself is not rewritten. Its typed changes remain authoritative only while that event is in the visible session surface. After a surface replacement removes it, prompt assembly recomposes the current baseline for that replacement generation and injects it before the first post-replacement request; a queued baseline that is discarded with its step remains eligible for the next request. A successful filesystem touch can still append later replacements or removals. The in-memory scope marker and provider-version cache only select and accelerate probes. A hot plugin remount retains a baseline only when its typed event remains visible, while rebuilding current scope and version tracking; otherwise it injects a current baseline. A resumed loop always recomposes the current baseline and also reconciles still-visible dynamic scopes before its first request. There is no file watcher, so an on-disk change becomes visible at the next successful `read`, `write`, or `edit` touch, when prompt assembly restores a shadowed baseline, or when a resumed loop prepares its baseline.
|
||||
The initial baseline event itself is not rewritten. Its typed changes remain authoritative only while that event is in the visible session surface. After a surface replacement removes it, model-request prompt assembly recomposes the current baseline and rechecks cancellation, visibility, and the current replacement generation immediately before injecting it. Concurrent preparations can read in parallel, but only the first commit queues a baseline; inspection-only assemblies never restore one. A successful filesystem touch can still append later replacements or removals. The in-memory scope marker and provider-version cache only select and accelerate probes. A hot plugin remount retains a baseline only when its typed event remains visible, while rebuilding current scope and version tracking; otherwise it injects a current baseline. A resumed loop always recomposes the current baseline and also reconciles still-visible dynamic scopes before its first request. There is no file watcher, so an on-disk change becomes visible at the next successful `read`, `write`, or `edit` touch, when a model request restores a shadowed baseline, or when a resumed loop prepares its baseline.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -162,7 +162,7 @@ Append-only; newly visible content follows the reusable request prefix and does
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Discovery follows structured fs tools, not shell navigation** — a `bash` command that changes directories does not trigger nested instruction discovery because shell syntax and per-call shell state are not a reliable filesystem seam.
|
||||
- **Refresh is event-driven** — there is no watcher; external edits become visible on the next successful first-party `read`, `write`, or `edit`, when prompt assembly restores a shadowed baseline, or when a resumed loop prepares its baseline.
|
||||
- **Refresh is event-driven** — there is no watcher; external edits become visible on the next successful first-party `read`, `write`, or `edit`, when model-request prompt assembly restores a shadowed baseline, or when a resumed loop prepares its baseline.
|
||||
- **Candidate semantics stay intentionally small** — lowercase names, `.claude/rules/`, and `@path` imports are not interpreted; project scopes load `AGENTS.local.md`/`CLAUDE.local.md` overlays by default, but the user-global `$DSH_HOME` scope has no local overlay and other custom names require explicit candidate configuration.
|
||||
- **Per-directory dedup is content-based** — sibling candidates collapse only when byte-identical after trimming leading and trailing whitespace; a `CLAUDE.md` that symlinks its sibling `AGENTS.md` resolves to the same content and collapses like any duplicate, while a distinct real copy that has drifted from `AGENTS.md` loads in full alongside it.
|
||||
- **Symlinked instruction files are followed across the trust boundary** — a candidate whose final component is a symlink is resolved and its target loaded, so a cloned repository can surface off-tree file content as lower-authority workspace guidance (it never overrides system, developer, or direct user instructions). Confine `ctx.fs` with the filesystem policy gate or an OS sandbox when loading untrusted repositories.
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
## 生命周期
|
||||
|
||||
基线会在每个实时会话的第一个 `agent/step` 注入。它先读取 `$DSH_HOME/AGENTS.md`,随后针对项目根目录到 `agent.session.header.cwd` 的每个目录,先读取每个现有基础候选文件,再读取每个现有本地 overlay 候选文件。同一目录中,如果候选文件在去除首尾空白后字节完全一致,就会按已配置顺序折叠到最早候选文件,因此 `CLAUDE.md` 若只是复制同级 `AGENTS.md`,只会渲染一次。这条持久的带来源 `user/message` 与被认领的提示词进入同一个请求。如果后续表层替换(例如压缩(compaction))遮蔽了该基线,`system-prompt/assemble` 会在 loop 对下一个请求创建快照之前,重新组合并注入当前指令链。
|
||||
基线会在每个实时会话的第一个 `agent/step` 注入。它先读取 `$DSH_HOME/AGENTS.md`,随后针对项目根目录到 `agent.session.header.cwd` 的每个目录,先读取每个现有基础候选文件,再读取每个现有本地 overlay 候选文件。同一目录中,如果候选文件在去除首尾空白后字节完全一致,就会按已配置顺序折叠到最早候选文件,因此 `CLAUDE.md` 若只是复制同级 `AGENTS.md`,只会渲染一次。这条持久的带来源 `user/message` 与被认领的提示词进入同一个请求。如果后续表层替换(例如压缩(compaction))遮蔽了该基线,面向模型请求的 `system-prompt/assemble` 会在 loop 对该请求创建快照之前,重新组合并注入当前指令链;TUI `/status` 等仅检查组装不会改变会话。
|
||||
|
||||
该插件还会监听 `tools/post-execute` 中成功的第一方 `read`、`write` 和 `edit` 调用。每次 touch 都会检查新达到的后代 scope 以及之前加载的每个 scope。每个已配置候选名称都是所在目录中的独立 scope:新出现的文件通过结果的 `additionalContexts` 附加;已改变文件追加替换;文件消失或成为同一目录中较早候选文件的重复项时,追加移除通知。原生调用与 Code Mode 子分派共享该路径:`run_code` 将每个嵌套上下文延迟到外层结果,因此 loop 仍会在工具调用/结果相邻关系完成后追加更新。这种发现跟随结构化文件系统活动,而不是 shell `cd`,因为每次本地 bash 调用都启动新 shell,解析任意 shell 语法也不可靠。
|
||||
|
||||
@@ -52,7 +52,7 @@ These instructions apply to work under `packages/app`. Use them as guidance when
|
||||
|
||||
路径与 SHA-1 内容 digest 都未变时,不会重复注入。每会话、每 scope 提供方 cache 只存储 `{ path, version, digest, trimmedDigest }`:当提供方的不透明 `FsVersion` 与有效可见状态都匹配时,对账会跳过内容读取;版本改变会在任何模型可见更新之前触发有界读取与 SHA-1 确认。`trimmedDigest` 是针对去除空白后内容的 SHA-1,也是每目录重复 key,因此较早候选文件与某个未更改文件的内容收敛后,后者仍可被移除。恢复可行,因为 SHA-1 状态持久化在带类型的来源中,而空的内存版本 cache 只会导致一次确认读取。压缩会在 scope 的上下文事件离开可见表层后重新启用它,即使缓存版本未变。移除是 tombstone,因此候选文件之后重新出现时会重新加载。只有在字节预算内实际渲染的模型可见变更才会进入来源、pending 状态和版本 cache;已省略变更仍可在后续 touch 处理,而相同 digest 的版本刷新只更新提供方 cache。
|
||||
|
||||
初始基线事件自身不会被改写。其带类型的变更仅在该事件仍位于可见会话表层时才是权威状态。表层替换将其移除后,提示词组装会为该替换代次重新组合当前基线,并在替换后的第一个请求前注入;随其步骤一起被丢弃的已排队基线仍可在下一个请求中重新准备。成功的文件系统 touch 仍可在之后追加替换或移除。内存中的 scope 标记和提供方版本 cache 只负责选择探测对象并加速探测。插件热重挂只有在其带类型的事件仍然可见时才保留基线,同时会重建当前 scope 与版本跟踪状态;否则会注入当前基线。恢复的 loop 始终重新组合当前基线,并在第一个请求前对账仍可见的动态 scope。没有文件 watcher,因此磁盘变更会在下一次成功 `read`、`write` 或 `edit` touch 时可见,也会在提示词组装恢复被遮蔽的基线时或恢复 loop 准备基线时可见。
|
||||
初始基线事件自身不会被改写。其带类型的变更仅在该事件仍位于可见会话表层时才是权威状态。表层替换将其移除后,面向模型请求的提示词组装会重新组合当前基线,并在注入前立即重新检查取消状态、可见性和当前替换代次。并发准备可以并行读取,但只有第一次提交会将一条基线排入队列;仅检查组装绝不会恢复基线。成功的文件系统 touch 仍可在之后追加替换或移除。内存中的 scope 标记和提供方版本 cache 只负责选择探测对象并加速探测。插件热重挂只有在其带类型的事件仍然可见时才保留基线,同时会重建当前 scope 与版本跟踪状态;否则会注入当前基线。恢复的 loop 始终重新组合当前基线,并在第一个请求前对账仍可见的动态 scope。没有文件 watcher,因此磁盘变更会在下一次成功 `read`、`write` 或 `edit` touch 时可见,也会在模型请求恢复被遮蔽的基线时或恢复 loop 准备基线时可见。
|
||||
|
||||
## 配置
|
||||
|
||||
@@ -162,7 +162,7 @@ The previously loaded instructions from this file no longer apply.
|
||||
## 已知限制与暂缓事项
|
||||
|
||||
- **发现跟随结构化 fs 工具,而非 shell 导航**:更改目录的 `bash` 命令不会触发嵌套指令发现,因为 shell 语法与每次调用 shell 状态不是可靠的文件系统 seam。
|
||||
- **刷新由事件驱动**:没有 watcher;外部编辑会在下一次成功的第一方 `read`、`write` 或 `edit` 时可见,也会在提示词组装恢复被遮蔽的基线时或恢复 loop 准备基线时可见。
|
||||
- **刷新由事件驱动**:没有 watcher;外部编辑会在下一次成功的第一方 `read`、`write` 或 `edit` 时可见,也会在面向模型请求的提示词组装恢复被遮蔽的基线时或恢复 loop 准备基线时可见。
|
||||
- **候选语义有意保持简单**:不解释小写名称、`.claude/rules/` 与 `@path` import;项目 scope 默认加载 `AGENTS.local.md`/`CLAUDE.local.md` overlay,但用户全局 `$DSH_HOME` scope 没有本地 overlay,其他自定义名称需要显式候选配置。
|
||||
- **每目录去重基于内容**:只有在去除首尾空白后字节完全一致时,才折叠同级候选文件。`CLAUDE.md` 若 symlink 到同级 `AGENTS.md`,会解析为相同内容,并像任何重复项一样折叠;从 `AGENTS.md` 漂移的独立实体副本则会与它一起完整加载。
|
||||
- **Symlink 指令文件会跨越信任边界跟随**:最终组件是 symlink 的候选文件会被解析并加载其目标,因此克隆仓库可以将树外文件内容呈现为较低优先级的工作区指引(它绝不会覆盖 system、developer 或用户直接下达的指令)。加载不受信任仓库时,请用文件系统策略门禁或 OS 沙箱限制 `ctx.fs`。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Workspace instruction loader for AGENTS.md-compatible files.
|
||||
*
|
||||
* Baseline instructions enter durable context before the first request and are
|
||||
* restored during prompt assembly when compaction removes them. Successful fs
|
||||
* restored during model-request prompt assembly when compaction removes them. Successful fs
|
||||
* tool touches reconcile nested, changed, and removed instructions through
|
||||
* `tools/post-execute` for the next model request. Plugin lifecycle reads use
|
||||
* the optional `ctx.fs` provider, so providerless products mount it as a no-op.
|
||||
@@ -55,8 +55,8 @@ function hasVisibleBaseline(session: Agent['session']): boolean {
|
||||
})
|
||||
}
|
||||
|
||||
function hasBaselineHistory(agent: Agent): boolean {
|
||||
return agent.session.events.some(event => event.type === 'user/message'
|
||||
function hasBaselineHistory(session: Agent['session']): boolean {
|
||||
return session.events.some(event => event.type === 'user/message'
|
||||
&& event.data.source.kind === 'workspace-instructions'
|
||||
&& event.data.source.baseline === true)
|
||||
}
|
||||
@@ -93,14 +93,13 @@ export function apply(ctx: Context, config: Config): void {
|
||||
if (event.type === 'user/message'
|
||||
&& event.data.source.kind === 'workspace-instructions'
|
||||
&& event.data.source.baseline === true) baselineQueuedGeneration.delete(session)
|
||||
if ((event.type === 'step/end' || event.type === 'turn/end')
|
||||
&& !hasVisibleBaseline(session)) baselineQueuedGeneration.delete(session)
|
||||
})
|
||||
|
||||
const prepareBaseline = async (
|
||||
agent: Agent,
|
||||
signal: AbortSignal | undefined,
|
||||
keepVisibleBaseline: boolean,
|
||||
deduplicateRestore = false,
|
||||
): Promise<void> => {
|
||||
if (resolved.maxBytes <= 0 || !Number.isFinite(resolved.maxBytes)) {
|
||||
baselineLoaded.add(agent.session)
|
||||
@@ -139,6 +138,13 @@ export function apply(ctx: Context, config: Config): void {
|
||||
fileSystem,
|
||||
{ includeBaselineScopes: false, ...signal === undefined ? {} : { signal } },
|
||||
)
|
||||
signal?.throwIfAborted()
|
||||
const generation = agent.session.surface.replaceGeneration
|
||||
if (deduplicateRestore && (
|
||||
hasVisibleBaseline(agent.session)
|
||||
|| baselineSettledGeneration.get(agent.session) === generation
|
||||
|| baselineQueuedGeneration.get(agent.session) === generation
|
||||
)) return
|
||||
if (update !== undefined) {
|
||||
agent.inject(update.context)
|
||||
applyInstructionVersionUpdates(agent.session, update.versionUpdates, instructionVersions)
|
||||
@@ -146,15 +152,20 @@ export function apply(ctx: Context, config: Config): void {
|
||||
if (!keepVisibleBaseline && instructions !== undefined && instructions.rendered.text.length > 0) {
|
||||
const baselineMessage = workspaceContextMessage(instructions.rendered.text)
|
||||
baselineSettledGeneration.delete(agent.session)
|
||||
baselineQueuedGeneration.set(agent.session, agent.session.surface.replaceGeneration)
|
||||
agent.inject(createUserMessage({
|
||||
content: baselineMessage.content,
|
||||
source: {
|
||||
kind: 'workspace-instructions',
|
||||
baseline: true,
|
||||
changes: [...baseline.changes.values()],
|
||||
},
|
||||
}))
|
||||
baselineQueuedGeneration.set(agent.session, generation)
|
||||
try {
|
||||
agent.inject(createUserMessage({
|
||||
content: baselineMessage.content,
|
||||
source: {
|
||||
kind: 'workspace-instructions',
|
||||
baseline: true,
|
||||
changes: [...baseline.changes.values()],
|
||||
},
|
||||
}))
|
||||
} catch (error: unknown) {
|
||||
baselineQueuedGeneration.delete(agent.session)
|
||||
throw error
|
||||
}
|
||||
} else {
|
||||
baselineSettledGeneration.set(agent.session, agent.session.surface.replaceGeneration)
|
||||
baselineQueuedGeneration.delete(agent.session)
|
||||
@@ -171,13 +182,14 @@ export function apply(ctx: Context, config: Config): void {
|
||||
ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
|
||||
const assembled = await next()
|
||||
const agent = context.agent
|
||||
if (agent === undefined
|
||||
if (context.modelRequest !== true
|
||||
|| agent === undefined
|
||||
|| !baselineLoaded.has(agent.session)
|
||||
|| hasVisibleBaseline(agent.session)
|
||||
|| baselineSettledGeneration.get(agent.session) === agent.session.surface.replaceGeneration
|
||||
|| baselineQueuedGeneration.get(agent.session) === agent.session.surface.replaceGeneration
|
||||
|| !hasBaselineHistory(agent)) return assembled
|
||||
await prepareBaseline(agent, context.signal, false)
|
||||
|| !hasBaselineHistory(agent.session)) return assembled
|
||||
await prepareBaseline(agent, context.signal, false, true)
|
||||
return assembled
|
||||
})
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import Loader from '@cordisjs/plugin-loader'
|
||||
import * as workspaceContext from '@deepseek-ai/dsh-workspace-context'
|
||||
import LlmService, { createUserMessage, CallId, type Message, type StreamChunk } from '@deepseek-ai/dsh-llm'
|
||||
import SessionStore, { Session, SessionId, SESSION_FORMAT_VERSION, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import AgentRegistry, { agentEvents, assembleContextFor, type Agent } from '@deepseek-ai/dsh-agent'
|
||||
import AgentRegistry, { agentEvents, assembleContextFor, assembleRequestContextFor, type Agent } from '@deepseek-ai/dsh-agent'
|
||||
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
|
||||
import { FileSystem, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs'
|
||||
import type {
|
||||
@@ -155,6 +155,26 @@ class BlockingReadFileSystem extends RecordingFileSystem {
|
||||
}
|
||||
}
|
||||
|
||||
class OverlappingReadFileSystem extends RecordingFileSystem {
|
||||
readonly paired = Promise.withResolvers<undefined>()
|
||||
readonly release = Promise.withResolvers<undefined>()
|
||||
private armed = false
|
||||
private started = 0
|
||||
|
||||
arm(): void {
|
||||
this.armed = true
|
||||
}
|
||||
|
||||
override async streamText(target: FsTarget, signal?: AbortSignal): Promise<AsyncIterable<string>> {
|
||||
if (this.armed) {
|
||||
this.started += 1
|
||||
if (this.started === 2) this.paired.resolve(undefined)
|
||||
await this.release.promise
|
||||
}
|
||||
return super.streamText(target, signal)
|
||||
}
|
||||
}
|
||||
|
||||
async function mountWorkspaceContext(ctx: Context, config: workspaceContext.Config): Promise<Awaited<ReturnType<Context['plugin']>>> {
|
||||
await ctx.plugin(LocalFileSystem, { cwd: '/' })
|
||||
return ctx.plugin(workspaceContext, config)
|
||||
@@ -1108,7 +1128,7 @@ describe('workspace context request injection', () => {
|
||||
sourceEventSeqs: [baseline!.seq],
|
||||
})
|
||||
|
||||
await ctx.systemPrompt.assemble(assembleContextFor(agent))
|
||||
await ctx.systemPrompt.assemble(assembleRequestContextFor(agent))
|
||||
|
||||
expect(baselineEvents(agent)).toHaveLength(2)
|
||||
expect(blocksText(agent.session.deriveMessages().at(-1)?.content)).toContain('repo rule')
|
||||
@@ -1118,7 +1138,7 @@ describe('workspace context request injection', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('retries a re-injected baseline when its queued step closes before the message becomes durable', async () => {
|
||||
it('does not restore a compacted baseline for an inspection-only assembly', async () => {
|
||||
const root = await tempRepo()
|
||||
const home = await tempRepo()
|
||||
try {
|
||||
@@ -1138,28 +1158,104 @@ describe('workspace context request injection', () => {
|
||||
surfaceOp: { op: 'replace', start: baseline!.seq, end: baseline!.seq },
|
||||
sourceEventSeqs: [baseline!.seq],
|
||||
})
|
||||
const queued: UserMessage[] = []
|
||||
const queuedAgent: Agent = {
|
||||
...agent,
|
||||
inject(input) { queued.push(input) },
|
||||
}
|
||||
await ctx.systemPrompt.assemble(assembleContextFor(agent, testToolSignal))
|
||||
|
||||
await ctx.systemPrompt.assemble(assembleContextFor(queuedAgent, testToolSignal))
|
||||
await ctx.systemPrompt.assemble(assembleContextFor(queuedAgent, testToolSignal))
|
||||
expect(queued).toHaveLength(1)
|
||||
|
||||
ctx.emit('session/event', agent.session, {
|
||||
type: 'step/end', seq: 999, time: 0, data: { turn: 1, step: 1 },
|
||||
})
|
||||
await ctx.systemPrompt.assemble(assembleContextFor(queuedAgent, testToolSignal))
|
||||
|
||||
expect(queued).toHaveLength(2)
|
||||
expect(baselineEvents(agent)).toHaveLength(1)
|
||||
expect(blocksText(agent.session.deriveMessages().at(-1)?.content)).toContain('compacted summary')
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
await rm(home, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('queues one baseline when two request assemblies finish preparation concurrently', async () => {
|
||||
const root = resolve('/virtual/concurrent-assembly-repo')
|
||||
const home = resolve('/virtual/concurrent-assembly-home')
|
||||
const ctx = new Context()
|
||||
try {
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(OverlappingReadFileSystem)
|
||||
const fs = ctx.fs as OverlappingReadFileSystem
|
||||
fs.entries.set(join(root, '.git'), { type: 'directory' })
|
||||
fs.entries.set(join(root, 'AGENTS.md'), { type: 'file', content: 'repo rule' })
|
||||
await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 })
|
||||
const agent = stubAgent(root)
|
||||
await composeBaselinePrefix(ctx, agent)
|
||||
const baseline = baselineEvents(agent)[0]
|
||||
expect(baseline).toBeDefined()
|
||||
agent.session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text: 'compacted summary' }],
|
||||
source: { kind: 'plugin', plugin: 'compact' },
|
||||
}), {
|
||||
surfaceOp: { op: 'replace', start: baseline!.seq, end: baseline!.seq },
|
||||
sourceEventSeqs: [baseline!.seq],
|
||||
})
|
||||
const queued: UserMessage[] = []
|
||||
const queuedAgent: Agent = {
|
||||
...agent,
|
||||
acceptsNextStep: true,
|
||||
inject(input) { queued.push(input) },
|
||||
}
|
||||
fs.arm()
|
||||
|
||||
const first = ctx.systemPrompt.assemble(assembleRequestContextFor(queuedAgent, testToolSignal))
|
||||
const second = ctx.systemPrompt.assemble(assembleRequestContextFor(queuedAgent, testToolSignal))
|
||||
await fs.paired.promise
|
||||
fs.release.resolve(undefined)
|
||||
await Promise.all([first, second])
|
||||
|
||||
expect(queued).toHaveLength(1)
|
||||
expect(blocksText(queued[0]?.content)).toContain('repo rule')
|
||||
} finally {
|
||||
await ctx.fiber.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('retries restoration after synchronous baseline injection failure', async () => {
|
||||
const root = resolve('/virtual/injection-failure-repo')
|
||||
const home = resolve('/virtual/injection-failure-home')
|
||||
const ctx = new Context()
|
||||
try {
|
||||
await ctx.plugin(SystemPrompt)
|
||||
await ctx.plugin(RecordingFileSystem)
|
||||
const fs = ctx.fs as RecordingFileSystem
|
||||
fs.entries.set(join(root, '.git'), { type: 'directory' })
|
||||
fs.entries.set(join(root, 'AGENTS.md'), { type: 'file', content: 'repo rule' })
|
||||
await ctx.plugin(workspaceContext, { dshHome: home, maxBytes: 65536 })
|
||||
const agent = stubAgent(root)
|
||||
await composeBaselinePrefix(ctx, agent)
|
||||
const baseline = baselineEvents(agent)[0]
|
||||
expect(baseline).toBeDefined()
|
||||
agent.session.append('user/message', createUserMessage({
|
||||
content: [{ type: 'text', text: 'compacted summary' }],
|
||||
source: { kind: 'plugin', plugin: 'compact' },
|
||||
}), {
|
||||
surfaceOp: { op: 'replace', start: baseline!.seq, end: baseline!.seq },
|
||||
sourceEventSeqs: [baseline!.seq],
|
||||
})
|
||||
const throwingAgent: Agent = {
|
||||
...agent,
|
||||
inject() { throw new Error('injection failed') },
|
||||
}
|
||||
|
||||
await expect(ctx.systemPrompt.assemble(
|
||||
assembleRequestContextFor(throwingAgent, testToolSignal),
|
||||
)).rejects.toThrow('injection failed')
|
||||
|
||||
const queued: UserMessage[] = []
|
||||
const retryingAgent: Agent = {
|
||||
...agent,
|
||||
inject(input) { queued.push(input) },
|
||||
}
|
||||
await ctx.systemPrompt.assemble(assembleRequestContextFor(retryingAgent, testToolSignal))
|
||||
|
||||
expect(queued).toHaveLength(1)
|
||||
expect(blocksText(queued[0]?.content)).toContain('repo rule')
|
||||
} finally {
|
||||
await ctx.fiber.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('includes a re-injected baseline in the first real request after a between-step replacement', async () => {
|
||||
const root = await tempRepo()
|
||||
const home = await tempRepo()
|
||||
|
||||
Reference in New Issue
Block a user