Skip to content

Commit 9e4269b

Browse files
committed
fix(agents): preserve split-owner completion policy
1 parent 16e72d2 commit 9e4269b

14 files changed

Lines changed: 259 additions & 2 deletions

File tree

‎packages/gateway-protocol/src/schema/sessions.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,7 @@ export const SessionsPatchParamsSchema = closedObject({
396396
execNode: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
397397
model: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
398398
spawnedBy: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
399+
completionOwnerSessionKey: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
399400
spawnedWorkspaceDir: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
400401
spawnedCwd: Type.Optional(Type.Union([NonEmptyString, Type.Null()])),
401402
spawnDepth: Type.Optional(Type.Union([Type.Integer({ minimum: 0 }), Type.Null()])),
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
title: Issue 109025 completion handoff sender-policy live probe
2+
3+
scenario:
4+
id: issue-109025-completion-policy-live
5+
surface: subagents
6+
runtimeParityTier: live-only
7+
coverage:
8+
secondary:
9+
- agents.subagents
10+
- runtime.delivery
11+
- channels.qa-channel
12+
gatewayConfigPatch:
13+
tools:
14+
toolsBySender:
15+
"*":
16+
deny:
17+
- exec
18+
- process
19+
- nodes
20+
- gateway
21+
- write
22+
"id:alice":
23+
deny:
24+
- write
25+
objective: Prove a dormant requester-agent completion handoff retains the original requester's exact sender tool policy instead of reapplying the wildcard deny.
26+
successCriteria:
27+
- An exact-sender parent spawns a child and yields before the child completes.
28+
- The child follows a serial filesystem-read chain that remains allowed by the wildcard policy.
29+
- The child completion wakes the requester agent without a new external sender turn.
30+
- The requester-agent continuation uses exec, which the wildcard policy denies, to generate a fresh marker while write remains denied.
31+
- The QA runner reads the exec-created proof file and finds the exact same unpredictable marker in Gateway output.
32+
docsRefs:
33+
- docs/gateway/config-tools.md
34+
- docs/tools/subagents.md
35+
- docs/help/testing.md
36+
codeRefs:
37+
- src/agents/requester-tool-policy.ts
38+
- src/agents/subagent-announce-delivery.ts
39+
- src/agents/subagent-capabilities.ts
40+
- src/agents/tools/sessions-yield-tool.ts
41+
execution:
42+
kind: flow
43+
suiteIsolation: isolated
44+
isolationReason: Mutates sender tool policy and exercises a yielded parent with a live child completion.
45+
channel: qa-channel
46+
retryCount: 0
47+
summary: Exercise exact sender policy through a real inbound turn, dormant requester-agent completion, and restricted exec call.
48+
config:
49+
childLabelPrefix: issue-109025-completion-child
50+
chainFilePrefix: issue-109025-completion-chain
51+
completionPrefix: ISSUE109025_COMPLETION_EXEC_OK
52+
53+
flow:
54+
steps:
55+
- name: dormant requester completion retains exact-sender exec authority
56+
actions:
57+
- call: waitForGatewayHealthy
58+
args:
59+
- ref: env
60+
- 120000
61+
- call: waitForTransportReady
62+
args:
63+
- ref: env
64+
- 120000
65+
- resetTransport: true
66+
- set: parentSessionKey
67+
value:
68+
expr: "buildAgentSessionKey({ agentId: 'qa', channel: 'qa-channel', accountId: 'default', peer: { kind: 'direct', id: 'alice' }, dmScope: env.cfg.session?.dmScope, identityLinks: env.cfg.session?.identityLinks })"
69+
- set: childLabel
70+
value:
71+
expr: "`${config.childLabelPrefix}-${randomUUID().slice(0, 8)}`"
72+
- set: chainNonce
73+
value:
74+
expr: randomUUID().slice(0, 8)
75+
- set: chainFiles
76+
value:
77+
expr: "[1, 2, 3, 4].map((index) => `${config.chainFilePrefix}-${chainNonce}-${index}.txt`)"
78+
- set: proofFile
79+
value:
80+
expr: "`issue-109025-exec-proof-${randomUUID()}.txt`"
81+
- set: proofPath
82+
value:
83+
expr: path.join(env.gateway.workspaceDir, proofFile)
84+
- set: execCommand
85+
value:
86+
expr: |-
87+
`node -e ${JSON.stringify(`const fs=require("node:fs");const crypto=require("node:crypto");const marker="${config.completionPrefix}:"+crypto.randomUUID();fs.writeFileSync(${JSON.stringify(proofFile)},marker+"\n");process.stdout.write(marker+"\n");`)}`
88+
- call: fs.writeFile
89+
args:
90+
- expr: path.join(env.gateway.workspaceDir, chainFiles[0])
91+
- expr: "`${chainFiles[1]}\n`"
92+
- utf8
93+
- call: fs.writeFile
94+
args:
95+
- expr: path.join(env.gateway.workspaceDir, chainFiles[1])
96+
- expr: "`${chainFiles[2]}\n`"
97+
- utf8
98+
- call: fs.writeFile
99+
args:
100+
- expr: path.join(env.gateway.workspaceDir, chainFiles[2])
101+
- expr: "`${chainFiles[3]}\n`"
102+
- utf8
103+
- call: fs.writeFile
104+
args:
105+
- expr: path.join(env.gateway.workspaceDir, chainFiles[3])
106+
- CHILD_READY
107+
- utf8
108+
- sendInbound:
109+
conversation:
110+
id: issue-109025-completion
111+
kind: direct
112+
senderId: alice
113+
senderName: Alice
114+
text:
115+
expr: |-
116+
`Issue 109025 dormant completion probe. Follow these steps exactly.
117+
1. Call sessions_spawn exactly once with runtime subagent, label ${childLabel}, and this task: "Use only the filesystem read tool. Start by reading ${chainFiles[0]}. Its trimmed contents name the next workspace file to read. Continue following one filename at a time until a file contains CHILD_READY. You must perform each read serially because later filenames are not in this task. Then reply exactly CHILD_DONE and nothing else. Do not use exec or process."
118+
2. Immediately after sessions_spawn succeeds, call sessions_yield. Do not wait for the child and do not send a normal final reply.
119+
3. When the CHILD_DONE completion event later resumes you, use the exec tool to run this exact command: ${execCommand}
120+
Do not use read or write for this step. Then reply with exactly the command's trimmed stdout.`
121+
- call: waitForCondition
122+
saveAs: expectedFinalMarker
123+
args:
124+
- lambda:
125+
async: true
126+
expr: "fs.readFile(proofPath, 'utf8').then((text) => { const marker = text.trim(); return marker.startsWith(`${config.completionPrefix}:`) && readGatewayLogs().includes(marker) ? marker : undefined; }).catch(() => undefined)"
127+
- 60000
128+
- 250
129+
- call: readSessionTranscriptSummary
130+
saveAs: parentTranscript
131+
args:
132+
- ref: env
133+
- ref: parentSessionKey
134+
- set: gatewayLogs
135+
value:
136+
expr: readGatewayLogs()
137+
- assert:
138+
expr: "(parentTranscript.assistantToolCallCounts.sessions_yield ?? 0) >= 1"
139+
message:
140+
expr: "`parent did not yield before completion; parentTools=${JSON.stringify(parentTranscript.assistantToolCallCounts ?? {})}`"
141+
- assert:
142+
expr: gatewayLogs.includes(expectedFinalMarker)
143+
message:
144+
expr: "`completion continuation did not produce the exec-created marker; marker=${String(expectedFinalMarker ?? '')}`"
145+
- assert:
146+
expr: "gatewayLogs.indexOf('CHILD_DONE') >= 0 && gatewayLogs.indexOf(expectedFinalMarker) > gatewayLogs.indexOf('CHILD_DONE')"
147+
message: child completion did not precede the exec-created continuation marker
148+
detailsExpr: "`parentSession=${parentSessionKey} parentTools=${JSON.stringify(parentTranscript.assistantToolCallCounts ?? {})} execMarker=${String(expectedFinalMarker ?? '')}`"

‎src/agents/acp-spawn.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,7 @@ describe("spawnAcpDirect", () => {
866866
expectSessionPatchFields({
867867
key: accepted.childSessionKey,
868868
spawnedBy: "agent:main:main",
869+
completionOwnerSessionKey: "agent:main:main",
869870
});
870871
expectBindingCallFields({
871872
targetKind: "session",

‎src/agents/acp-spawn.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,6 +1289,7 @@ export async function spawnAcpDirect(
12891289
params: {
12901290
key: sessionKey,
12911291
spawnedBy: requesterInternalKey,
1292+
completionOwnerSessionKey: ownership.completionRequesterSessionKey,
12921293
...admission.childSessionPatch,
12931294
...inheritedToolAllowPatch(ctx.inheritedToolAllowlist),
12941295
...inheritedToolDenyPatch(ctx.inheritedToolDenylist),

‎src/agents/embedded-agent-runner/run/run-attempt-dispatch.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,7 @@ export async function dispatchEmbeddedRunAttempt(input: {
326326
sourceReplyDeliveryMode: params.sourceReplyDeliveryMode,
327327
taskSuggestionDeliveryMode: params.taskSuggestionDeliveryMode,
328328
inputProvenance: params.inputProvenance,
329+
trustedInternalHandoff: params.trustedInternalHandoff,
329330
streamParams: params.streamParams,
330331
modelRun: params.modelRun,
331332
disableTrajectory: params.disableTrajectory,

‎src/agents/requester-tool-policy.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,51 @@ describe("resolveRequesterToolPolicies", () => {
288288
});
289289
});
290290

291+
it("restores a verified completion handoff to a distinct immutable completion owner", async () => {
292+
const controllerSessionKey = "agent:main:discord:direct:alice";
293+
const completionOwnerSessionKey = "agent:main:main";
294+
const childSessionKey = "agent:main:subagent:child";
295+
await writeSession(childSessionKey, {
296+
spawnedBy: controllerSessionKey,
297+
completionOwnerSessionKey,
298+
spawnDepth: 1,
299+
subagentRole: "orchestrator",
300+
subagentControlScope: "children",
301+
inheritedToolAllow: ["read", "exec"],
302+
});
303+
304+
const result = resolveRequesterToolPolicies({
305+
config: config(),
306+
agentId: "main",
307+
sessionKey: completionOwnerSessionKey,
308+
trustedInternalHandoff: true,
309+
inputProvenance: {
310+
kind: "inter_session",
311+
sourceSessionKey: childSessionKey,
312+
sourceTool: "subagent_announce",
313+
},
314+
});
315+
316+
expect(result.delegated).toBe(true);
317+
expect(result.requesterPolicySource).toBe("completion-handoff");
318+
expect(result.senderPolicy).toBeUndefined();
319+
expect(result.inheritedToolPolicy).toEqual({ allow: ["read", "exec"] });
320+
321+
const controllerResult = resolveRequesterToolPolicies({
322+
config: config(),
323+
agentId: "main",
324+
sessionKey: controllerSessionKey,
325+
trustedInternalHandoff: true,
326+
inputProvenance: {
327+
kind: "inter_session",
328+
sourceSessionKey: childSessionKey,
329+
sourceTool: "subagent_announce",
330+
},
331+
});
332+
expect(controllerResult.delegated).toBe(false);
333+
expect(controllerResult.requesterPolicySource).toBe("current-request");
334+
});
335+
291336
it("walks nested lineage to the projection captured from the target requester", async () => {
292337
const requesterSessionKey = "agent:main:discord:direct:alice";
293338
const parentChildSessionKey = "agent:main:subagent:parent-child";
@@ -351,12 +396,21 @@ describe("resolveRequesterToolPolicies", () => {
351396
trustedInternalHandoff: true,
352397
inputProvenance: provenance,
353398
});
399+
const mismatchedCompletionOwner = resolveRequesterToolPolicies({
400+
config: config(),
401+
agentId: "main",
402+
sessionKey: "agent:main:main",
403+
trustedInternalHandoff: true,
404+
inputProvenance: provenance,
405+
});
354406

355407
expect(untrusted.delegated).toBe(false);
356408
expect(untrusted.requesterPolicySource).toBe("current-request");
357409
expect(untrusted.senderPolicy).toEqual({ deny: ["group:runtime", "group:fs"] });
358410
expect(mismatched.delegated).toBe(false);
359411
expect(mismatched.requesterPolicySource).toBe("current-request");
360412
expect(mismatched.senderPolicy).toEqual({ deny: ["group:runtime", "group:fs"] });
413+
expect(mismatchedCompletionOwner.delegated).toBe(false);
414+
expect(mismatchedCompletionOwner.requesterPolicySource).toBe("current-request");
361415
});
362416
});

‎src/agents/requester-tool-policy.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,10 @@ function resolveDelegatedPolicy(
131131
return { delegated: false };
132132
}
133133
const parentSessionKey = resolveRequesterStoreKey(params.config, envelope.spawnedBy);
134-
if (parentSessionKey === targetSessionKey) {
134+
const completionOwnerSessionKey = envelope.completionOwnerSessionKey
135+
? resolveRequesterStoreKey(params.config, envelope.completionOwnerSessionKey)
136+
: undefined;
137+
if ((completionOwnerSessionKey ?? parentSessionKey) === targetSessionKey) {
135138
return {
136139
delegated: true,
137140
source: "completion-handoff",

‎src/agents/subagent-capabilities.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ type SessionCapabilityEntry = {
4343
subagentRole?: unknown;
4444
subagentControlScope?: unknown;
4545
spawnedBy?: unknown;
46+
completionOwnerSessionKey?: unknown;
4647
inheritedToolAllow?: unknown;
4748
inheritedToolDeny?: unknown;
4849
};
@@ -56,6 +57,7 @@ export type SessionCapabilityStore = Record<
5657
subagentRole?: unknown;
5758
subagentControlScope?: unknown;
5859
spawnedBy?: unknown;
60+
completionOwnerSessionKey?: unknown;
5961
inheritedToolAllow?: unknown;
6062
inheritedToolDeny?: unknown;
6163
}
@@ -64,6 +66,7 @@ export type SessionCapabilityStore = Record<
6466
type PersistedSubagentToolPolicyEnvelope = {
6567
sessionKey: string;
6668
spawnedBy: string;
69+
completionOwnerSessionKey?: string;
6770
inheritedToolAllow: string[];
6871
inheritedToolDeny: string[];
6972
};
@@ -330,9 +333,11 @@ export function resolvePersistedSubagentToolPolicyEnvelope(
330333
) {
331334
return undefined;
332335
}
336+
const completionOwnerSessionKey = normalizeOptionalString(entry.completionOwnerSessionKey);
333337
return {
334338
sessionKey: normalizedSessionKey,
335339
spawnedBy,
340+
...(completionOwnerSessionKey ? { completionOwnerSessionKey } : {}),
336341
inheritedToolAllow: normalizeInheritedToolAllowlist(entry.inheritedToolAllow),
337342
inheritedToolDeny: normalizeInheritedToolDenylist(entry.inheritedToolDeny),
338343
};

‎src/agents/subagent-spawn.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1463,6 +1463,12 @@ describe("spawnSubagentDirect seam flow", () => {
14631463
});
14641464

14651465
it("keeps controller ownership separate from completion ownership", async () => {
1466+
let persistedStore: Record<string, Record<string, unknown>> | undefined;
1467+
installSessionStoreCaptureMock(hoisted.updateSessionStoreMock, {
1468+
onStore: (store) => {
1469+
persistedStore = store;
1470+
},
1471+
});
14661472
await spawnSubagentDirect(
14671473
{
14681474
task: "background work",
@@ -1480,6 +1486,9 @@ describe("spawnSubagentDirect seam flow", () => {
14801486
expect(registerInput.controllerSessionKey).toBe("agent:main:telegram:default:direct:456");
14811487
expect(registerInput.requesterSessionKey).toBe("agent:main:main");
14821488
expect(registerInput.requesterDisplayKey).toBe("agent:main:main");
1489+
expect(persistedStore?.[registerInput.childSessionKey]?.completionOwnerSessionKey).toBe(
1490+
"agent:main:main",
1491+
);
14831492
});
14841493

14851494
it("persists the spawning session as the stable swarm limit owner", async () => {

‎src/agents/subagent-spawn.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,12 @@ function buildDirectChildSessionPatch(patch: Record<string, unknown>): Partial<S
363363
if (typeof patch.spawnedBy === "string" && patch.spawnedBy.trim()) {
364364
entry.spawnedBy = patch.spawnedBy.trim();
365365
}
366+
if (
367+
typeof patch.completionOwnerSessionKey === "string" &&
368+
patch.completionOwnerSessionKey.trim()
369+
) {
370+
entry.completionOwnerSessionKey = patch.completionOwnerSessionKey.trim();
371+
}
366372
if (typeof patch.spawnedWorkspaceDir === "string" && patch.spawnedWorkspaceDir.trim()) {
367373
entry.spawnedWorkspaceDir = patch.spawnedWorkspaceDir.trim();
368374
}
@@ -1500,6 +1506,7 @@ export async function spawnSubagentDirect(
15001506
});
15011507
const spawnLineagePatchError = await patchChildSession({
15021508
spawnedBy: spawnedByKey,
1509+
completionOwnerSessionKey: ownership.completionRequesterSessionKey,
15031510
...(spawnedMetadata.workspaceDir
15041511
? { spawnedWorkspaceDir: spawnedMetadata.workspaceDir }
15051512
: {}),

0 commit comments

Comments
 (0)