fix(auto-review): scope logged calls by step

This commit is contained in:
pku-xht committed 2026-09-04 12:10:10 +08:00
1 parent ca8d65e5c4
commit dae5844f93
8 files changed
+266 -59

No files matched your search

@@ -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 .agents/notes/implemented/feature/2026-08-28-auto-review.md
2026-08-28-auto-review.md: 0550951c7b14faea3ad9944135d202d86e75e25b
2026-08-28-auto-review.zh.md: 78cf6469735aabf64fdf4bd7eaa04d451db31c6d
2026-08-28-auto-review.md: 47b478e196f7be255c6ce5bd33e79c73f8797d1e
2026-08-28-auto-review.zh.md: 107ba92fab32ef188b932f2e6cb361dee94bd3e8
@@ -36,7 +36,7 @@ An Auto denial gives the main agent a fixed message that names the rejected tool
Caller cancellation follows ordinary Tool settlement priority: a cancellation observed after a late allow becomes the canonical pre-dispatch cancellation, while a deny or technical failure that has already settled remains an Auto denial. A denied PTC inner call keeps the existing `ToolCallError` and program `catch` behavior, so a handled denial does not become an outer `run_code` failure. Allow produces no event, reason, or durable grant.
Publication and teardown are fail-closed. Before it publishes either registration, the integration requires the configured `read-only` preset to resolve exactly to sandbox `read-only` plus approval policy `ask`. A stored Auto session cannot publish unless the Auto registration is live and admits that Session; the service does not rewrite it to Full access. During disposal, the integration first closes new Auto selection and review admission and captures the exact Session object identities retiring from Auto before it changes any preset. The listener checks this retiring set before derived permission state, so a partial migration that already appended `permission/preset` or `sandbox/mode` cannot reopen execution. The integration switches those sessions to Read Only through the normal preset writer, aborts and awaits in-flight reviews, and only then removes the listener and Auto registration. If any Session cannot migrate, the integration still aborts and drains reviews but retains both closed registrations, so new Auto selections fail and calls from retiring sessions are denied instead of entering an unreviewed execution window.
Publication and teardown are fail-closed. Before it publishes either registration, the integration requires the configured `read-only` preset to resolve exactly to sandbox `read-only` plus approval policy `ask`. A stored Auto session cannot publish unless the Auto registration is live and admits that Session; the service does not rewrite it to Full access. During disposal, the integration first closes new Auto selection and review admission and captures the exact Session object identities retiring from Auto before it changes any preset. The listener checks this retiring set before derived permission state, so a partial migration that already appended `permission/preset` or `sandbox/mode` cannot reopen execution. The integration switches those sessions to Read Only through the normal preset writer, aborts the lifecycle, and waits for every active review or admitted call before it removes the listener and Auto registration. An allowed call remains active until `tools/execute` or `tools/result`; the execute wrapper combines the lifecycle signal with the caller signal before delegating, so disposal cancels any admitted body that has not started. If any Session cannot migrate, the integration still aborts and drains active calls but retains both closed registrations, so new Auto selections fail and calls from retiring sessions are denied instead of entering an unreviewed execution window.
## Verification
@@ -36,7 +36,7 @@ Auto 拒绝会向主 agent 提供固定消息,其中会指明被拒绝的工
调用方取消沿用普通 Tool 的结算优先级:late allow 后观察到的取消会转为规范的 dispatch 前取消,而已经结算的拒绝或技术失败仍保持 Auto 拒绝。被拒绝的 PTC inner call 保留既有 `ToolCallError` 与程序 `catch` 行为,因此被处理的拒绝不会转成外层 `run_code` 失败。允许决定不产生事件、原因或持久 grant。
发布与资源释放均以拒绝方式关闭。在发布任一注册前,integration 要求配置的 `read-only` 预设精确解析为沙箱 `read-only` 加审批策略 `ask`。存储的 Auto 会话只有在 Auto 注册为 live 状态并准入该 Session 时才能发布;服务不会把它改写为 Full access。资源释放期间,integration 会先关闭新的 Auto 选择与审查准入,并在改变任何预设前捕获正在退出 Auto 的精确 Session 对象身份。监听器会先检查该退役集合,再派生当前权限状态,因此即使部分迁移已经追加 `permission/preset` 或 `sandbox/mode`,也不能重新开放执行。integration 随后通过普通预设写入器把这些会话切换到 Read Only,中止并等待在途审查,最后才移除监听器与 Auto 注册。若有 Session 无法迁移,integration 仍会中止并排空审查,但会保留两项已关闭的注册,使新的 Auto 选择失败,并让退役会话的调用被拒绝,而不是留下未经审查的执行窗口。
发布与资源释放均以拒绝方式关闭。在发布任一注册前,integration 要求配置的 `read-only` 预设精确解析为沙箱 `read-only` 加审批策略 `ask`。存储的 Auto 会话只有在 Auto 注册为 live 状态并准入该 Session 时才能发布;服务不会把它改写为 Full access。资源释放期间,integration 会先关闭新的 Auto 选择与审查准入,并在改变任何预设前捕获正在退出 Auto 的精确 Session 对象身份。监听器会先检查该退役集合,再派生当前权限状态,因此即使部分迁移已经追加 `permission/preset` 或 `sandbox/mode`,也不能重新开放执行。integration 随后通过普通预设写入器把这些会话切换到 Read Only,中止生命周期,并等待每次在途审查或已准入调用完成,最后才移除监听器与 Auto 注册。允许的调用会保持 active 状态,直至进入 `tools/execute` 或 `tools/result`;execute 包装层会在继续分派前合并生命周期 signal 与调用方 signal,因此资源释放会取消任何尚未开始的已准入工具主体。若有 Session 无法迁移,integration 仍会中止并排空 active 调用,但会保留两项已关闭的注册,使新的 Auto 选择失败,并让退役会话的调用被拒绝,而不是留下未经审查的执行窗口。
## 验证
@@ -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/interaction/auto-review/README.md
README.md: 07554ba22338c251bc6426e169df8204361942c0
README.zh.md: 4b796fccea1ed665e14825f3e4b5703ad975a5dc
README.md: 97dc62d46c0cf9dc61f94dfe5c236d85a309e8c3
README.zh.md: c2c745401bc5de5297e36b580c8a00fb2f1bb64a
+1 -1
View File
@@ -70,7 +70,7 @@ The plugin prepends one `tools/pre-execute` listener. It rebuilds each native ac
An Auto denial uses a fixed model-facing message that names the rejected tool and states that its body was not executed. Its `AutoReviewDeniedError` / `AUTO_REVIEW_DENIED` identity and optional raw reason travel through the ordinary native or PTC structured-error fields. The Web tree recognizes that identity before keyed Tool-view dispatch and renders the generic denial card, so a specialized or external Tool view cannot hide the verdict. The presentation normalizes the reason only when it renders the card.
Publication and teardown are fail-closed. Before publishing, the integration requires the configured `read-only` preset to resolve exactly to sandbox `read-only` plus approval policy `ask`; a label mapped to any other bundle is rejected. A persisted Auto session cannot publish without the live Auto registration. Before changing any preset during disposal, the plugin captures the exact Session object identities that are retiring from Auto. The listener checks that set before derived permission state, so a partial migration that has already appended `permission/preset` or `sandbox/mode` still cannot reopen Tool execution. The plugin closes new admission, switches the captured sessions to Read Only through the normal preset writer, and then aborts and awaits in-flight reviews. If every migration succeeds, teardown removes the listener and Auto registration; if any migration fails, Cordis reports the cleanup error while retaining both in their closed state, so later calls from retiring sessions stay denied and new Auto selections fail.
Publication and teardown are fail-closed. Before publishing, the integration requires the configured `read-only` preset to resolve exactly to sandbox `read-only` plus approval policy `ask`; a label mapped to any other bundle is rejected. A persisted Auto session cannot publish without the live Auto registration. Before changing any preset during disposal, the plugin captures the exact Session object identities that are retiring from Auto. The listener checks that set before derived permission state, so a partial migration that has already appended `permission/preset` or `sandbox/mode` still cannot reopen Tool execution. The plugin closes new admission, switches the captured sessions to Read Only through the normal preset writer, then aborts the lifecycle and waits for every active review or admitted call. An allowed call remains active until `tools/execute` or `tools/result`; the execute wrapper combines the lifecycle signal with the caller signal before delegating, so disposal cancels any admitted body that has not started. If every migration succeeds, teardown removes the listener and Auto registration; if any migration fails, Cordis reports the cleanup error while retaining both in their closed state, so later calls from retiring sessions stay denied and new Auto selections fail.
### Source map
@@ -70,7 +70,7 @@ DSH_AUTO_REVIEW_CERTIFICATION=1 pnpm exec vitest run --config vitest.e2e.config.
Auto 拒绝使用固定模型可见消息,其中会指明被拒绝的工具并说明其主体未执行。其 `AutoReviewDeniedError`/`AUTO_REVIEW_DENIED` 身份与可选 raw reason 通过普通原生或 PTC 结构化错误字段传播。Web 树会在 keyed Tool 视图分派前识别该身份并渲染通用拒绝卡,因此专用或外部 Tool 视图都不能遮住拒绝结论。展示层只在渲染工具卡时归一化原因。
发布与资源释放都以拒绝方式关闭。发布前,integration 要求配置的 `read-only` 预设精确解析为沙箱 `read-only` 加审批策略 `ask`;同名但映射到其他组合的条目会被拒绝。持久 Auto 会话在 live Auto 注册缺失时不能发布。资源释放在修改任何预设前,会先捕获所有正在退出 Auto 的精确 Session 对象身份。监听器会先检查该集合,再派生当前权限状态,因此即使部分迁移已经追加 `permission/preset` 或 `sandbox/mode`,也不能重新开放 Tool 执行。插件随后关闭新准入,通过普通预设写入器把这些已捕获会话切换到 Read Only,再中止并等待在途审查。如果全部迁移成功,资源释放会移除监听器与 Auto 注册;如果任一迁移失败,Cordis 会报告清理错误并让两者保留在已关闭状态,使退役会话的后续调用继续被拒绝、新的 Auto 选择继续失败。
发布与资源释放都以拒绝方式关闭。发布前,integration 要求配置的 `read-only` 预设精确解析为沙箱 `read-only` 加审批策略 `ask`;同名但映射到其他组合的条目会被拒绝。持久 Auto 会话在 live Auto 注册缺失时不能发布。资源释放在修改任何预设前,会先捕获所有正在退出 Auto 的精确 Session 对象身份。监听器会先检查该集合,再派生当前权限状态,因此即使部分迁移已经追加 `permission/preset` 或 `sandbox/mode`,也不能重新开放 Tool 执行。插件随后关闭新准入,通过普通预设写入器把这些已捕获会话切换到 Read Only,再中止生命周期并等待每次在途审查或已准入调用。允许的调用会保持 active 状态,直至进入 `tools/execute` 或 `tools/result`;execute 包装层会在继续分派前合并生命周期 signal 与调用方 signal,因此资源释放会取消任何尚未开始的已准入工具主体。如果全部迁移成功,资源释放会移除监听器与 Auto 注册;如果任一迁移失败,Cordis 会报告清理错误并让两者保留在已关闭状态,使退役会话的后续调用继续被拒绝、新的 Auto 选择继续失败。
### 源码地图
+121 -51
View File
@@ -103,6 +103,19 @@ interface ReviewSnapshot {
readonly action: PendingAction
}
type NativeCallEvent = Extract<SessionEvent, { type: 'tool/call' }>
type PtcStartEvent = Extract<SessionEvent, { type: 'tool/code-dispatch-start' }>
interface StepIdentity {
readonly turn: number
readonly step: number
}
interface ScopedPtcStart {
readonly event: PtcStartEvent
readonly step: StepIdentity
}
/** Runtime facts owned until one admitted call cannot outlive lifecycle cancellation. */
interface ActiveCall {
readonly done: Promise<void>
@@ -244,12 +257,55 @@ function filteredUserEntries(
}))
}
/** Find every event matching one predicate, preserving log order. */
function matchingEvents<T extends SessionEvent>(
events: readonly SessionEvent[],
predicate: (event: SessionEvent) => event is T,
): T[] {
return events.filter(predicate)
/** Copy the turn and step identity carried by one core execution event. */
function stepIdentity(data: { readonly turn: number; readonly step: number }): StepIdentity {
return { turn: data.turn, step: data.step }
}
/** Compare two turn-and-step identities. */
function sameStep(left: StepIdentity, right: StepIdentity): boolean {
return left.turn === right.turn && left.step === right.step
}
/** Key one call id inside the step that owns its lifecycle. */
function scopedCallKey(step: StepIdentity, callId: ToolCallId): string {
return `${step.turn}\0${step.step}\0${callId}`
}
/** Assign each PTC start to its open step, retaining a narrow fixture fallback. */
function scopePtcStarts(events: readonly SessionEvent[]): {
readonly starts: readonly ScopedPtcStart[]
readonly openStep: StepIdentity | undefined
} {
const latestRoots = new Map<ToolCallId, NativeCallEvent>()
const starts: ScopedPtcStart[] = []
let openStep: StepIdentity | undefined
for (const event of events) {
if (event.type === 'turn/start' || event.type === 'turn/end') {
openStep = undefined
continue
}
if (event.type === 'step/start') {
openStep = stepIdentity(event.data)
continue
}
if (event.type === 'step/end') {
openStep = undefined
continue
}
if (event.type === 'tool/call') {
latestRoots.set(event.data.callId, event)
continue
}
if (event.type !== 'tool/code-dispatch-start') continue
const root = latestRoots.get(event.data.rootCallId)
const step = openStep ?? (root === undefined ? undefined : stepIdentity(root.data))
if (step === undefined) {
throw new Error('auto-review: a PTC call has no owning step in the session log')
}
starts.push({ event, step })
}
return { starts, openStep }
}
/** Resolve one native action from its visible call and latest request header. */
@@ -282,22 +338,17 @@ function nativeAction(
/** Resolve one PTC inner action from its start-event snapshot. */
function ptcAction(
exec: ToolExecution,
starts: readonly Extract<SessionEvent, { type: 'tool/code-dispatch-start' }>[],
visibleParentIds: ReadonlySet<ToolCallId>,
start: ScopedPtcStart,
visibleParentKeys: ReadonlySet<string>,
): PendingAction {
const matches = starts.filter(event => event.data.subCallId === exec.callId)
if (matches.length !== 1) {
throw new Error('auto-review: the pending PTC call is missing or ambiguous in the session log')
}
const start = matches[0]
if (start === undefined
|| !visibleParentIds.has(start.data.parentCallId)
|| start.data.rootCallId !== exec.rootCallId
|| start.data.name !== exec.name
|| !sameJson(start.data.arguments, exec.arguments)) {
const { event } = start
if (!visibleParentKeys.has(scopedCallKey(start.step, event.data.parentCallId))
|| event.data.rootCallId !== exec.rootCallId
|| event.data.name !== exec.name
|| !sameJson(event.data.arguments, exec.arguments)) {
throw new Error('auto-review: the pending PTC call disagrees with its logged action')
}
const schema = loggedSchema(start.data, exec.name, 'PTC')
const schema = loggedSchema(event.data, exec.name, 'PTC')
return {
mode: 'ptc-inner',
name: schema.name,
@@ -326,35 +377,52 @@ function snapshotAutoReview(agent: Agent, exec: ToolExecution): ReviewSnapshot {
throw new Error('auto-review: the session has no working directory')
}
const nativeCalls = matchingEvents(events, (event): event is Extract<SessionEvent, { type: 'tool/call' }> =>
event.type === 'tool/call')
const starts = matchingEvents(events, (event): event is Extract<SessionEvent, { type: 'tool/code-dispatch-start' }> =>
event.type === 'tool/code-dispatch-start')
const nativeCalls = events.filter((event): event is NativeCallEvent => event.type === 'tool/call')
const { starts, openStep } = scopePtcStarts(events)
const initialPromptSeq = directParentInitialPromptSeq(agent, events)
const nativeById = new Map<ToolCallId, Extract<SessionEvent, { type: 'tool/call' }>[]>()
const nativeByScopedId = new Map<string, NativeCallEvent[]>()
for (const event of nativeCalls) {
const bucket = nativeById.get(event.data.callId)
if (bucket === undefined) nativeById.set(event.data.callId, [event])
const key = scopedCallKey(stepIdentity(event.data), event.data.callId)
const bucket = nativeByScopedId.get(key)
if (bucket === undefined) nativeByScopedId.set(key, [event])
else bucket.push(event)
}
const startsByParent = new Map<ToolCallId, Extract<SessionEvent, { type: 'tool/code-dispatch-start' }>[]>()
const seenSubCalls = new Set<ToolCallId>()
for (const event of starts) {
if (seenSubCalls.has(event.data.subCallId)) {
const startsByParent = new Map<string, ScopedPtcStart[]>()
const startsBySubCall = new Map<string, ScopedPtcStart>()
for (const start of starts) {
const subCallKey = scopedCallKey(start.step, start.event.data.subCallId)
if (startsBySubCall.has(subCallKey)) {
throw new Error('auto-review: a PTC call identity is ambiguous in the session log')
}
seenSubCalls.add(event.data.subCallId)
const bucket = startsByParent.get(event.data.parentCallId)
if (bucket === undefined) startsByParent.set(event.data.parentCallId, [event])
else bucket.push(event)
startsBySubCall.set(subCallKey, start)
const parentKey = scopedCallKey(start.step, start.event.data.parentCallId)
const bucket = startsByParent.get(parentKey)
if (bucket === undefined) startsByParent.set(parentKey, [start])
else bucket.push(start)
}
const latestRootCall = nativeCalls.findLast(event => event.data.callId === exec.rootCallId)
const currentStep = openStep
?? (latestRootCall === undefined ? undefined : stepIdentity(latestRootCall.data))
if (currentStep === undefined) {
throw new Error('auto-review: the pending root call is missing from the session log')
}
const currentRootCalls = nativeByScopedId.get(scopedCallKey(currentStep, exec.rootCallId)) ?? []
const currentRootCall = currentRootCalls[0]
if (currentRootCall === undefined || currentRootCalls.length !== 1) {
throw new Error('auto-review: the pending root call is missing or ambiguous in the session log')
}
const currentPtcStart = exec.parent === undefined
? undefined
: startsBySubCall.get(scopedCallKey(currentStep, exec.callId))
if (exec.parent !== undefined && currentPtcStart === undefined) {
throw new Error('auto-review: the pending PTC call is missing or ambiguous in the session log')
}
const projectInstructions: HistoricalUserMessage[] = []
const history: HistoricalEntry[] = []
const visibleParentIds = new Set<ToolCallId>()
let currentNativeCall: Extract<SessionEvent, { type: 'tool/call' }> | undefined
const visibleParentKeys = new Set<string>()
let passedCurrentRoot = false
let sawUnstartedSibling = false
for (const seq of nodes) {
// Surface nodes are event indexes produced by this Session's validated fold.
// oxlint-disable-next-line typescript/no-non-null-assertion
@@ -383,20 +451,24 @@ function snapshotAutoReview(agent: Agent, exec: ToolExecution): ReviewSnapshot {
continue
}
if (event.type !== 'assistant/message') continue
const messageStep = stepIdentity(event.data)
const isCurrentMessage = sameStep(messageStep, currentStep)
let sawUnstartedSibling = false
for (const block of event.data.message.content) {
if (block.type !== 'tool-call') continue
const isCurrentRoot = block.id === exec.rootCallId
const key = scopedCallKey(messageStep, block.id)
const isCurrentRoot = isCurrentMessage && block.id === exec.rootCallId
if (isCurrentRoot && passedCurrentRoot) {
throw new Error('auto-review: the pending root call is ambiguous in the current surface')
}
const calls = nativeById.get(block.id) ?? []
const calls = nativeByScopedId.get(key) ?? []
if (calls.length > 1) {
throw new Error('auto-review: a native call identity is ambiguous in the session log')
}
const call = calls[0]
const startsForCall = startsByParent.get(block.id) ?? []
const startsForCall = startsByParent.get(key) ?? []
if (call === undefined) {
if (!passedCurrentRoot) {
if (isCurrentMessage && !passedCurrentRoot) {
throw new Error('auto-review: a visible call before the pending root is missing from the session log')
}
if (startsForCall.length > 0) {
@@ -411,9 +483,8 @@ function snapshotAutoReview(agent: Agent, exec: ToolExecution): ReviewSnapshot {
if (call.data.name !== block.name || call.data.arguments !== block.arguments) {
throw new Error('auto-review: a visible tool call disagrees with its logged action')
}
visibleParentIds.add(block.id)
if (block.id === exec.callId) currentNativeCall = call
else {
visibleParentKeys.add(key)
if (call !== currentRootCall || exec.parent !== undefined) {
history.push({
kind: 'tool-call',
role: 'fact',
@@ -423,13 +494,13 @@ function snapshotAutoReview(agent: Agent, exec: ToolExecution): ReviewSnapshot {
})
}
for (const start of startsForCall) {
if (start.data.subCallId === exec.callId) continue
if (start === currentPtcStart) continue
history.push({
kind: 'tool-call',
role: 'fact',
mode: 'ptc-inner',
name: start.data.name,
arguments: json(start.data.arguments),
name: start.event.data.name,
arguments: json(start.event.data.arguments),
})
}
if (isCurrentRoot) passedCurrentRoot = true
@@ -441,11 +512,10 @@ function snapshotAutoReview(agent: Agent, exec: ToolExecution): ReviewSnapshot {
}
const action = exec.parent === undefined
// A direct execution's root id is its call id. The validated root above
// therefore supplied exactly this logged event.
? nativeAction(exec, header.tools, currentRootCall)
// The branch above established that every nested execution has one scoped start.
// oxlint-disable-next-line typescript/no-non-null-assertion
? nativeAction(exec, header.tools, currentNativeCall!)
: ptcAction(exec, starts, visibleParentIds)
: ptcAction(exec, currentPtcStart!, visibleParentKeys)
return deepFreeze({
provider: header.config.provider,
model: header.config.model,
@@ -473,6 +473,52 @@ describe('native review request', () => {
expect(requestText).not.toContain('obsolete description')
})
it('scopes reused native call ids and started prefixes to one assistant step', async () => {
const { ctx, adapter } = await harness([
decisionChunks('{"risk":"low","decision":"allow"}'),
])
const probe = registerProbe(ctx)
const { session, agent } = autoSession(ctx, 'native-reused-call-id')
appendHeader(session, [{ name: 'probe', description: 'probe', parameters: { type: 'object' } }])
const callId = ToolCallId('reused-native-call')
appendAssistant(session, [
{ type: 'tool-call', id: callId, name: 'probe', arguments: '{"path":"old"}' },
{ type: 'tool-call', id: ToolCallId('old-unstarted'), name: 'probe', arguments: '{}' },
], 1, 1)
appendNativeCall(session, callId, 'probe', '{"path":"old"}', 1, 1)
appendAssistant(session, [
{ type: 'tool-call', id: callId, name: 'probe', arguments: '{"path":"current"}' },
], 1, 2)
appendNativeCall(session, callId, 'probe', '{"path":"current"}', 1, 2)
const result = await ctx.tools.execute({
signal: new AbortController().signal,
callId,
name: 'probe',
arguments: { path: 'current' },
agent,
})
expect(result.isError).toBe(false)
expect(probe.runs()).toBe(1)
expect(adapter.requests).toHaveLength(1)
const sections = requestSections(adapter.requests[0]!)
expect(sections.FILTERED_HISTORY).toEqual(expect.arrayContaining([{
kind: 'tool-call',
role: 'fact',
mode: 'native',
name: 'probe',
arguments: '{"path":"old"}',
}]))
expect(sections.PENDING_ACTION).toEqual({
mode: 'native',
name: 'probe',
description: 'probe',
parameters: { type: 'object' },
arguments: { path: 'current' },
})
})
it('assigns child creation, direct-parent, human, and forged-message roles without overriding human limits', async () => {
const { ctx, adapter } = await harness([
decisionChunks('{"risk":"medium","decision":"deny"}'),
@@ -946,6 +992,95 @@ describe('PTC and bypass semantics', () => {
}
})
it('scopes reused PTC root and sub-call ids to the open step', async () => {
const { ctx, adapter } = await harness([
decisionChunks('{"risk":"low","decision":"allow"}'),
])
const probe = registerProbe(ctx)
const { session, agent } = autoSession(ctx, 'ptc-reused-call-id')
const outerCallId = ToolCallId('reused-outer')
const subCallId = ToolCallId('reused-outer:code:0')
session.append('turn/start', { turn: 1 })
appendHeader(session)
session.append('step/start', { turn: 1, step: 1 })
appendAssistant(session, [{
type: 'tool-call', id: outerCallId, name: RUN_CODE_NAME, arguments: '{"code":"old"}',
}], 1, 1)
appendNativeCall(session, outerCallId, RUN_CODE_NAME, '{"code":"old"}', 1, 1)
session.append('tool/code-dispatch-start', {
rootCallId: outerCallId,
parentCallId: outerCallId,
subCallId,
name: 'probe',
description: 'old inner description',
parameters: { type: 'object' },
arguments: { path: 'old' },
})
session.append('tool/code-dispatch', {
rootCallId: outerCallId,
parentCallId: outerCallId,
subCallId,
name: 'probe',
arguments: { path: 'old' },
isError: false,
content: [{ type: 'text', text: 'old result' }],
})
session.append('tool/result', {
turn: 1,
step: 1,
message: createToolResultMessage({
callId: outerCallId,
content: [{ type: 'text', text: 'old outer result' }],
isError: false,
}),
}, { surfaceOp: 'append' })
session.append('step/end', { turn: 1, step: 1 })
session.append('step/start', { turn: 1, step: 2 })
appendAssistant(session, [{
type: 'tool-call', id: outerCallId, name: RUN_CODE_NAME, arguments: '{"code":"current"}',
}], 1, 2)
appendNativeCall(session, outerCallId, RUN_CODE_NAME, '{"code":"current"}', 1, 2)
session.append('tool/code-dispatch-start', {
rootCallId: outerCallId,
parentCallId: outerCallId,
subCallId,
name: 'probe',
description: 'current inner description',
parameters: { type: 'object' },
arguments: { path: 'current' },
})
const result = await ctx.tools.execute({
signal: new AbortController().signal,
rootCallId: outerCallId,
parent: Symbol('outer execution') as ToolExecutionToken,
callId: subCallId,
name: 'probe',
arguments: { path: 'current' },
agent,
})
expect(result.isError).toBe(false)
expect(probe.runs()).toBe(1)
expect(adapter.requests).toHaveLength(1)
const sections = requestSections(adapter.requests[0]!)
expect((sections.FILTERED_HISTORY as Array<Record<string, unknown>>)
.filter(entry => entry['mode'] === 'ptc-inner')).toEqual([{
kind: 'tool-call',
role: 'fact',
mode: 'ptc-inner',
name: 'probe',
arguments: '{\n "path": "old"\n}',
}])
expect(sections.PENDING_ACTION).toEqual({
mode: 'ptc-inner',
name: 'probe',
description: 'current inner description',
parameters: { type: 'object' },
arguments: { path: 'current' },
})
})
it('does not review unscoped, non-Auto, or outer run_code executions', async () => {
const { ctx, adapter } = await harness([])
const probe = registerProbe(ctx)
@@ -1438,6 +1573,7 @@ describe('logged-fact failures', () => {
} },
{ id: 'missing-current-log', prepare: (session, callId) => {
appendHeader(session, [{ name: 'probe', description: 'probe', parameters: { type: 'object' } }])
session.append('step/start', { turn: 1, step: 1 })
appendAssistant(session, [{ type: 'tool-call', id: callId, name: 'probe', arguments: '{}' }])
} },
{ id: 'duplicate-current-log', prepare: (session, callId) => {
@@ -1515,6 +1651,7 @@ describe('logged-fact failures', () => {
} },
{ id: 'unstarted-call-with-ptc-log', prepare: (session, callId) => {
appendHeader(session, [{ name: 'probe', description: 'probe', parameters: { type: 'object' } }])
session.append('step/start', { turn: 1, step: 1 })
const later = ToolCallId('unstarted-with-ptc')
appendAssistant(session, [
{ type: 'tool-call', id: callId, name: 'probe', arguments: '{}' },