Skip to content

fix(subagents): yielded requests go unanswered after a private subagent completes - #156540

Merged
obviyus merged 12 commits into
mainfrom
fix/private-settle-owed-reply
Oct 1, 2026
Merged

obviyus merged 12 commits into
mainfrom
fix/private-settle-owed-reply

Conversation

@obviyus

@obviyus obviyus commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: a yielded request can go unanswered after a private subagent completes—or bypass message-tool-only reply settings when the parent resumes.

User Impact

The resumed parent can answer the original conversation under its configured reply policy. Automatic replies deliver normally; message-tool-only conversations keep ordinary final text private. Private child output stays internal, and replaced or reset requester sessions do not receive stale findings.

Why This Change Was Made

Yielding hands completion back to the requester; it does not grant permission to bypass reply policy. The Gateway command path now uses the existing reply-policy owner for the effective resumed run and enforces that policy at delivery, not just in prompts.

Explicit host-owned diagnostics/media retain their existing delivery grants. Suppressed plain finals do not become restart-delivery markers or trigger repeated settle turns. Successful silence, failures, pending work, and confirmed delivery remain distinct. The original requester-identity, cancellation, retry, and previously attempted private-batch protections are preserved.

No configuration, protocol, or database-schema migration is required.

Contributor credit

Original implementation and follow-up fixes by @obviyus. The final reply-policy correction and regression proof were prepared at @obviyus's request, preserving the original PR ancestry and contributor credit.

Work sessions

Evidence

Current integrated candidate

Current head: ba5e732. Main was merged without rewriting the original author history to resolve the paused-child settlement changes. The resolution preserves private completion identity as well as main’s pause notifications and requester-generation fences; prompt snapshots were regenerated through their owner.

  • 365 affected tests passed across delivery, pause, private wake, dispatch, identity and restart. The fixture-only dispatch cleanup also passed its focused rerun. Core, all 27 core-test and four root-test type graphs, formatting, prompt snapshots, planned guards, and all three Knip scans passed.
  • Full local core lint still reports an inherited max-lines failure in untouched src/agents/embedded-agent-runner/run/terminal-resolution.test.ts (1,056 > 1,000 lines), identical to captured main. The earlier coercion-helper failure described below is resolved by this main integration. No lint rule or baseline was weakened.
  • Landing is still blocked by required CI. Attempt 1 and the single bounded retry both failed the unchanged Activity recap relocated-store assertion at src/gateway/session-activity-summaries.test.ts:981 (coveredMessages: expected 3, received 2); matrix fail-fast cancelled unfinished Node lanes. The same unchanged test passed an isolated local probe, but that does not override the repeated CI failure. No timeout, assertion, baseline, or source was weakened, and no waiver or further blind retry is being requested by this proof.

Fresh exact-head live proof passed on ba5e732, tree cbb314ffa1515f22934c7e20e54ea34801b861ff, with no source/harness overlay or retry.

Current committed real-Telegram case FINAL messages / edits Actual observation after settlement Result
Message-tool-only; ordinary FINAL, no message call 0 / 0 85.911 s Pass
Automatic; ordinary FINAL 1 / 0 84.515 s Pass
Message-tool-only; actual message(final:false), then model NO_REPLY 1 / 0 85.531 s Pass

All 13 identity gates and the positive-final retention check passed in every cell. There were no private-child leaks, visible NO_REPLY, final edits, duplicate/later finals, or later model requests after settlement+30 seconds. Only model responses were deterministic; Gateway ingress, tools, accepted spawn/yield, child execution, requester settlement, delivery, and TDLib observations were real. Host-owned progress output is allowed; the negative asserts zero FINAL, not total chat silence.

The exact-head build passed in 7m48.2s. The two additional reset/SQLite test files passed all 23 tests in 52.11s. Built entry SHA256: d37c20dc8be2c02e85b3cc0561f103f68991e6818ddcdc9a5a35513faf49dd7c. All three QA finalizers completed; credential scratch, owned processes, listeners, egress bridge and disposable compute were independently verified cleaned up.

Three-cell live receipt · Build and focused checks

The earlier proof below remains historical red-to-green evidence; the current table is a separate exact-committed-head run.

Earlier correction proof

The earlier head c92ae0e leaked one ordinary parent FINAL under messages.visibleReplies=message_tool. The correction was built and exercised with real isolated Gateways, accepted private child spawn/yield/settle flows, Telegram Test Server transport, and a TDLib QA user. Only model responses were deterministic.

Live case Final messages / edits Recorded observation after settlement Result
Message-tool-only; ordinary parent FINAL, no message call 0 / 0 87.641 s Pass
Automatic; ordinary parent FINAL 1 / 0 85.346 s Pass
Message-tool-only; actual message send, then model NO_REPLY 1 / 0 78.187 s Pass

All cases verify configuration, message-tool availability, accepted spawn/yield receipts, exact child/requester-settle identities, successful terminal run, and no later final or retry identity. Observation excludes teardown. Host-owned progress/status messages are recorded; the negative proves no FINAL, not total chat silence.

The send-then-NO_REPLY control explicitly uses final:false so the existing message-tool terminal hook permits the later model response. The initial default-final control correctly delivered once and terminated immediately; that fixture mismatch was retained and only the corrected control rerun. The zero-final negative assertion was not weakened.

  • 509 focused tests passed, covering command policy/preparation, delivery, maintenance, announcement and yielded-settle behavior, and global/group/default/unavailable-tool policy boundaries.
  • Build, core typecheck, all 27 core-test typecheck graphs, focused type-aware lint, formatting, and the remaining planned guards passed. The opt-in Telegram harness passed syntax, formatting, lint, and credential-free silence-oracle self-checks.
  • Earlier candidate’s inherited failure (now resolved by main integration): check:changed stopped at the coercion-helper guard for untouched scripts/ci-build-manifest.mjs:101 (parseBoolean). The same guard failed on a clean detached c92ae0e baseline. No guard or baseline was relaxed; this is not an all-gates-green claim or a request to bypass enforced CI.
  • Independent AutoReview found no actionable P0–P2 issues in the source correction. Final harness review found a positive-control edge case where a progress edit could erase the final. The oracle now checks the final message’s retained state; a credential-free red/green self-check proves that edit is rejected. The retained live controls contain no such edit.
  • No live group-override or nondeterministic-model claim is made. Group policy and failure/reset/retry siblings use boundary tests.
  • QA credentials, processes, egress bridges, listeners, and disposable compute were released and verified.

This earlier live proof used the exact pre-commit candidate bytes on c92ae0e; all 12 source-file hashes in the first correction commit matched that tested candidate. The later main-integration edits are covered separately above. Five hashes identify the live harness; after capture, its offline verdict check was strengthened to reject a final erased by an edit, and an unused mock-helper export was removed without changing its implementation. Existing sanitized timelines independently satisfy that stronger check. Tracked correction patch SHA256: b9c312ff8153f1f9d4f5ca97222206a1dbac1abc61feb3efb87895733efffb20. Committing those unchanged bytes is not presented as a separate live run.

Test cost and earlier evidence

Whole-file wall cost with pnpm test <file> --maxWorkers=1:

  • src/commands/agent.test.ts: 79 tests, 179.11 s.
  • src/agents/command/delivery.test.ts: 67 tests, 42.18 s.
  • subagent-announce-delivery.test.ts: 266 tests, 40.90 s.
  • subagent-announce-delivery.yielded-settle.test.ts: 18 tests, 34.31 s.

These are existing-suite/import costs, not incremental case-only costs. New cases reuse existing fixtures; the long Telegram composition remains opt-in, outside per-PR unit CI. Current-head CI timing is not yet available.

Earlier Telegram proof and original implementation context predates this correction and is not relabeled as current proof.

Current-head live proof (ce4907a3ba7d)

Telegram Test Server, real Gateway and ingress, scripted model, fresh isolated state per cell. Build dist matches the head.

Cell Setup Result
message-tool-ordinary visibleReplies: message_tool, resumed parent writes plain final 0 finals
automatic-ordinary automatic room, same final exactly 1 final
message-tool-send tool-only room, parent sends via message, then NO_REPLY exactly 1, no duplicate
reset-pending /new while the private child is still running child killed, wake removed, 0 finals after the reset ack
reset-admitted /new while the marked settle turn is held at the model turn aborted, intentional_non_delivery, 0 finals
upgrade-released batch written by the published 2026.9.7 Gateway (no marker), candidate restarted on the same state settle turn produced FINAL, nothing sent (watched 337s after settle); heartbeat turn sent nothing
upgrade-stripped candidate-written batch with the marker removed while stopped 0 finals (396s window)
upgrade-control same flow with the marker exactly 1 final

The yielded-final contract is accepted as a maintainer decision on this PR.

@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: S size: M and removed size: S labels Sep 23, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 23, 2026
@clawsweeper

clawsweeper Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 1:56 AM ET / 05:56 UTC (Revision 18).

ClawSweeper review

What this changes

The PR lets yielded parents answer after private subagents finish while enforcing conversation reply settings, requester identity, intentional silence, and legacy batch privacy.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main still suppresses yielded parents’ automatic replies after private completion. No blocking introduced defect was found, the prior upgrade findings are resolved, and the accepted contract has relevant live proof.

Priority: P1
Reviewed head: e53ebf580dba72e8acef5152f5caa1d4a7ad3d51

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong production-path proof and focused owner-based repairs resolve the prior blockers without a new actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Real Gateway and Telegram Test Server proof exercises private spawn, yield, settlement, reply-policy delivery, pending/admitted resets, and published 2026.9.7 state upgrade. Observed zero/one/one finals and rejected stale delivery cover the changed boundary; those production paths are unchanged since the tested ce4907a head. Stored marker compatibility is independently supported by upgrade observations and SQLite reopen coverage.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Real Gateway and Telegram Test Server proof exercises private spawn, yield, settlement, reply-policy delivery, pending/admitted resets, and published 2026.9.7 state upgrade. Observed zero/one/one finals and rejected stale delivery cover the changed boundary; those production paths are unchanged since the tested ce4907a head. Stored marker compatibility is independently supported by upgrade observations and SQLite reopen coverage.
Evidence reviewed 11 items Pinned introduction and review continuity: Reviewed the introduced f3f0241..e53ebf5 delta. The settlement, command delivery, spawn description, Telegram harness, and prompt snapshots are unchanged from the previously reviewed and live-tested ce4907a head; the scoped comparison exited successfully with no differences. The supplied test merge is stale and was not used to claim merged-result behavior.
Still necessary on current main: Fetched main still sets parentOnly whenever a completion batch contains private children, independently of requester yield. The merged requester-tool repair addresses tool availability, not this remaining delivery policy.
Frozen delivery policy and upgrade safety: The yield writer persists yieldedFinalDeliverable in the existing batch payload. Settlement requires that marker before making private findings’ parent continuation deliverable; missing markers retain the private policy. This resolves both retained historical upgrade findings without rewriting existing batches.
Findings None None.
Security None None.

How this fits together

Subagent settlement returns completed child findings to the requesting agent. The resumed agent’s reply then passes through conversation policy and durable channel delivery.

flowchart TD
  A[Requester yields] --> B[Persist completion batch]
  C[Private child finishes] --> B
  B --> D[Check requester and batch authority]
  D --> E[Resume parent with private findings]
  E --> F[Apply conversation reply policy]
  F --> G[Deliver permitted reply]
  F --> H[Record intentional silence]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +165, Tests +864, Docs +87, Other +786. Total +1902 across 41 files.

View PR surface stats
Area Files Added Removed Net
Source 14 309 144 +165
Tests 20 1049 185 +864
Docs 4 88 1 +87
Config 0 0 0 0
Generated 0 0 0 0
Other 3 786 0 +786
Total 41 2232 330 +1902

Review metrics

Metric Value Why it matters
Runtime versus regression growth Runtime production +165 net lines; tests, support, and fixtures +864 net lines Production growth is explained by delivery classification, shared filtering, and frozen batch policy; the separate opt-in live harness is excluded from these totals.

Stored data model

Persistent data-model change detected: serialized state: .agents/skills/telegram-e2e-userbot/scripts/reply-policy-checkpoint.mjs, serialized state: .agents/skills/telegram-e2e-userbot/scripts/run-reply-policy-user-e2e.mjs, unknown-data-model-change: .agents/skills/telegram-e2e-userbot/scripts/reply-policy-checkpoint.mjs, unknown-data-model-change: .agents/skills/telegram-e2e-userbot/scripts/run-reply-policy-user-e2e.mjs. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Technical review

Best possible solution:

Use the existing settlement and reply-policy owners to deliver current yielded parents’ answers while keeping private findings and legacy batches confidential.

Do we have a high-confidence way to reproduce the issue?

Yes: current main makes any batch containing private children parent-only, suppressing automatic parent delivery after yield. The discussion supplies real Telegram reproduction; this read-only review did not execute a current-main reproduction.

Is this the best way to solve the issue?

Yes: the patch extends existing settlement and reply-policy owners, preserves legacy state, and distinguishes confirmed delivery, intentional silence, failures, and pending continuations.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d3fbeaac8fbd.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P1: A yielded agent workflow can complete successfully while leaving the original channel request unanswered, including a reported 2026.9.7 incident.
  • merge-risk: 🚨 compatibility: The accepted change adds persisted delivery-policy semantics; source and published-driver upgrade proof preserve existing markerless batches.
  • merge-risk: 🚨 security-boundary: The accepted change permits parent channel delivery after private completion, with live reset rejection and source checks preserving confidentiality and requester authority.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Real Gateway and Telegram Test Server proof exercises private spawn, yield, settlement, reply-policy delivery, pending/admitted resets, and published 2026.9.7 state upgrade. Observed zero/one/one finals and rejected stale delivery cover the changed boundary; those production paths are unchanged since the tested ce4907a head. Stored marker compatibility is independently supported by upgrade observations and SQLite reopen coverage.
  • proof: sufficient: Contributor real behavior proof is sufficient. Real Gateway and Telegram Test Server proof exercises private spawn, yield, settlement, reply-policy delivery, pending/admitted resets, and published 2026.9.7 state upgrade. Observed zero/one/one finals and rejected stale delivery cover the changed boundary; those production paths are unchanged since the tested ce4907a head. Stored marker compatibility is independently supported by upgrade observations and SQLite reopen coverage.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The PR changes whether a yielded parent’s answer appears in Telegram; supplied Test Server proof covers that visible behavior.

Evidence

What I checked:

  • Pinned introduction and review continuity: Reviewed the introduced f3f0241..e53ebf5 delta. The settlement, command delivery, spawn description, Telegram harness, and prompt snapshots are unchanged from the previously reviewed and live-tested ce4907a head; the scoped comparison exited successfully with no differences. The supplied test merge is stale and was not used to claim merged-result behavior. (e53ebf580dba)
  • Still necessary on current main: Fetched main still sets parentOnly whenever a completion batch contains private children, independently of requester yield. The merged requester-tool repair addresses tool availability, not this remaining delivery policy. (src/agents/subagents/announce/subagent-announce.requester-settle-wake.ts, d3fbeaac8fbd)
  • Frozen delivery policy and upgrade safety: The yield writer persists yieldedFinalDeliverable in the existing batch payload. Settlement requires that marker before making private findings’ parent continuation deliverable; missing markers retain the private policy. This resolves both retained historical upgrade findings without rewriting existing batches. (src/agents/subagents/announce/subagent-announce.requester-settle-state.ts:115, e53ebf580dba)
  • Reply policy and final-effect authority: Command delivery filters automatic output through the existing source-reply policy; post-run persistence applies the same filter before granting restart-delivery custody. Settlement checks requester session and lifecycle identity, and durable delivery retains current-authority checks at platform dispatch and adapter handoff. (src/agents/command/delivery.ts:369, e53ebf580dba)
  • Accepted contract and verified decision authority: The September 24 and October 1 decision comments accept yielded parent replies under normal conversation policy, private child confidentiality, silence, reset rejection, and markerless upgrade privacy. The read-only collaborator endpoint verified obviyus has role_name maintain, supporting the decision despite inconsistent author-association fields. The acceptance still matches this diff.
  • Real Telegram and authority proof: The captured PR body records ce4907a real Gateway/Telegram Test Server observations: ordinary tool-only final produces zero finals; automatic final and explicit message send each produce exactly one; reset during pending child execution and admitted settlement produce zero stale finals. Published 2026.9.7 markerless state remains silent after candidate restart, with marked state providing the positive control. The changed production paths are unchanged at the reviewed head. Earlier proof also records no raw private-child leakage. Only model responses were scripted; ingress, tools, settlement, transport, and TDLib observation were real. (ce4907a3ba7d)

Likely related people:

  • joshavant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (17 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-30T08:54:16.345Z sha ba5e732 :: blocked before merge. :: none
  • reviewed 2026-09-30T09:15:12.255Z sha ba5e732 :: blocked before merge. :: none
  • reviewed 2026-09-30T09:32:45.758Z sha ba5e732 :: blocked before merge. :: none
  • reviewed 2026-09-30T10:23:53.835Z sha 3772335 :: needs real behavior proof before merge. :: [P1] Preserve pre-upgrade pending batches as private
  • reviewed 2026-09-30T15:27:23.185Z sha 90ba179 :: needs real behavior proof before merge. :: [P1] Keep markerless pending batches private on upgrade
  • reviewed 2026-10-01T01:49:32.916Z sha e2abf2d :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-01T02:38:58.762Z sha ce4907a :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-01T05:11:08.964Z sha ce4907a :: needs maintainer review before merge. :: none

@obviyus

obviyus commented Sep 23, 2026

Copy link
Copy Markdown
Collaborator Author

Telegram Test Server proof: yielded private subagent

Real Telegram DM on Telegram's Test Server, driven by the leased QA user (TDLib recorder), against a fresh Gateway built from each commit. The model is a content-routed mock (source below) so every run takes the same path:

  1. User sends PARENT_ASK_7Q ….
  2. Parent calls sessions_spawn with completionTarget: "parent" (accepted), then sessions_yield (status: "yielded").
  3. Child answers CHILD_PRIVATE_RESULT_7Q.
  4. Settle turn: the parent is resumed with the child's result and answers with the scripted settle reply.

Gateway config patch: tools.profile: "coding", tools.codeMode: false, tools.toolSearch: false. This only makes sessions_spawn a direct tool for the mock. The same patch was used in all three cells.

Cell Build Settle reply Settle turn got child result Bot messages seen by the user
baseline main @ d0de886 (merge base) OWED_FINAL_OK_7Q yes Working → edited to Working / Subagent (succeeded). Final never sent.
candidate PR @ c16d2f6 OWED_FINAL_OK_7Q yes Working → Working / Subagent (succeeded), then OWED_FINAL_OK_7Q, and the progress card is deleted
candidate PR @ c16d2f6 NO_REPLY yes Working → Working / Subagent (succeeded). Nothing else sent

What this proves:

  • Bug reproduced on main: the resumed parent writes its answer, and Telegram never receives it. This is the incident.
  • Fix: the same answer reaches the user in the original DM.
  • Silence still works: with NO_REPLY the bot sends nothing.
  • Child output stays private: CHILD_PRIVATE_RESULT_7Q never appears in any bot message in any cell. It only reaches the parent's settle turn.

Not covered by this run: the other cases (mixed batches, a replaced requester session, and replaying a batch an older build already tried) are covered by the unit/integration tests in this PR, not by live Telegram. In the NO_REPLY cell the progress card stays on screen (as Working / Subagent (succeeded)) instead of being removed; this PR doesn't change that.

Run facts: every cell exited 0 with recordingComplete: true. The runner released its lease, left no listeners or processes, and removed its credential scratch (scratchRemovedAfterExit: true). The credential doctor reported ok: true before the runs.

Command (per cell, from each checkout's root):

E2E_ROOT_CONFIG_PATCH='{"tools":{"profile":"coding","codeMode":false,"toolSearch":false}}' \
E2E_MOCK_SERVER_PATH=private-settle-mock.mjs \
E2E_TELEGRAM_MOCK_RESPONSE=OWED_FINAL_OK_7Q  # or NO_REPLY \
node .agents/skills/telegram-e2e-userbot/scripts/run-mock-sut-user-e2e.mjs \
  --gateway-port <port> --mock-port <port> --dm --timeout-ms 90000 \
  --text 'PARENT_ASK_7Q delegate the audit privately, then tell me the result.' \
  --record events.ndjson --output summary.json
Mock provider (private-settle-mock.mjs)
#!/usr/bin/env node
// Content-routed mock for PR #156540: parent spawns a private child, yields,
// then the settle turn answers. Routing is by request content so concurrent
// parent/child requests cannot be served out of order.
import { createHash } from "node:crypto";
import fs from "node:fs";
import http from "node:http";

const port = Number(process.env.MOCK_PORT);
const requestLog = process.env.MOCK_REQUEST_LOG;
const settleReply = process.env.SUCCESS_MARKER || "OWED_FINAL_OK";
const CHILD_TASK = "CHILD_TASK_7Q audit the fixture and report";
const CHILD_RESULT = "CHILD_PRIVATE_RESULT_7Q";

function sse(res, events) {
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" });
  for (const e of events) res.write(`data: ${JSON.stringify(e)}\n\n`);
  res.end("data: [DONE]\n\n");
}
const usage = { input_tokens: 64, output_tokens: 16, total_tokens: 80, input_tokens_details: { cached_tokens: 0 } };
function textEvents(text) {
  const item = { type: "message", id: "msg_mock", role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] };
  return [
    { type: "response.output_item.added", output_index: 0, item: { ...item, content: [], status: "in_progress" } },
    { type: "response.output_text.delta", item_id: "msg_mock", output_index: 0, content_index: 0, delta: text },
    { type: "response.output_text.done", item_id: "msg_mock", output_index: 0, content_index: 0, text },
    { type: "response.output_item.done", output_index: 0, item },
    { type: "response.completed", response: { id: "resp_mock_text", status: "completed", output: [item], usage } },
  ];
}
function toolEvents(name, args) {
  const serialized = JSON.stringify(args);
  const h = createHash("sha256").update(name + serialized).digest("hex").slice(0, 10);
  const item = { type: "function_call", id: `fc_${name}_${h}`, call_id: `call_${name}_${h}`, name, arguments: serialized };
  return [
    { type: "response.output_item.added", item: { ...item, arguments: "" } },
    { type: "response.function_call_arguments.delta", delta: serialized },
    { type: "response.output_item.done", item },
    { type: "response.completed", response: { id: `resp_${name}_${h}`, status: "completed", output: [item], usage } },
  ];
}

function route(body, text) {
  const input = Array.isArray(body.input) ? body.input : [];
  const calls = input.filter((i) => i?.type === "function_call").map((i) => i.name);
  if (!Array.isArray(body.tools) || body.tools.length === 0) return { kind: "side", events: textEvents("ok") };
  // The child session never sees the parent's ask; it is checked first because its
  // own system prompt also carries subagent context.
  if (!text.includes("PARENT_ASK_7Q") && text.includes("CHILD_TASK_7Q"))
    return { kind: "child", events: textEvents(CHILD_RESULT) };
  if (calls.includes("sessions_yield") && text.includes("[Subagent Context]"))
    return { kind: "settle", events: textEvents(settleReply) };
  if (!calls.includes("sessions_spawn"))
    return {
      kind: "parent-spawn",
      events: toolEvents("sessions_spawn", { task: CHILD_TASK, completionTarget: "parent", mode: "run", context: "isolated" }),
    };
  if (!calls.includes("sessions_yield")) return { kind: "parent-yield", events: toolEvents("sessions_yield", {}) };
  return { kind: "parent-after-yield", events: textEvents("NO_REPLY") };
}

http
  .createServer((req, res) => {
    const url = new URL(req.url, "http://x");
    if (req.method === "GET" && url.pathname === "/v1/models") {
      res.writeHead(200, { "content-type": "application/json" });
      return res.end(JSON.stringify({ object: "list", data: [{ id: "gpt-5.5", object: "model" }] }));
    }
    let raw = "";
    req.on("data", (c) => (raw += c));
    req.on("end", () => {
      if (url.pathname !== "/v1/responses") {
        res.writeHead(404);
        return res.end();
      }
      const body = JSON.parse(raw || "{}");
      const input = Array.isArray(body.input) ? body.input : [];
      const tools = (body.tools ?? []).map((t) => t.name).filter(Boolean);
      const r = route(body, raw);
      if (requestLog)
        fs.appendFileSync(
          requestLog,
          `${JSON.stringify({
            at: Date.now(),
            kind: r.kind,
            settleReply: r.kind === "settle" ? settleReply : undefined,
            tools,
            hasYieldTool: tools.includes("sessions_yield"),
            hasChildTask: raw.includes("CHILD_TASK_7Q"),
            hasParentAsk: raw.includes("PARENT_ASK_7Q"),
            hasChildResult: raw.includes("CHILD_PRIVATE_RESULT_7Q"),
            calls: input.filter((i) => i?.type === "function_call").map((i) => i.name),
            outputs: input.filter((i) => i?.type === "function_call_output").map((i) => String(i.output).slice(0, 400)),
            lastUser: JSON.stringify(input.filter((i) => i?.role === "user").at(-1) ?? null).slice(0, 500),
          })}\n`,
        );
      sse(res, r.events);
    });
  })
  .listen(port, "127.0.0.1", () => console.log(`mock-openai listening on ${port}`));

@clawsweeper clawsweeper Bot added proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 23, 2026
@obviyus

obviyus commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Maintainer decision on the contract change: approved, narrowly.

After sessions_yield, a parent whose batch includes completionTarget: "parent" children may deliver its own final reply to the original conversation. Everything else in the private contract stays as it was:

  • Child output stays internal wake input and is never sent to the channel.
  • NO_REPLY stays silent when nothing is owed; the yield does not force a reply.
  • The deliverable settle turn stays bound to the requester session that produced the private findings; a replaced parent gets no handoff.
  • The policy is decided once at first admission and persisted (yieldedFinalDeliverable). Batches already admitted as private turns, including by earlier builds, keep the private policy.

Update on 903aedb11066 for the open retry finding: a deliverable yielded batch now retries under fresh :retry-N idempotency keys, derived from the frozen delivery policy rather than from whether the batch contains private children. Private turns keep one key across attempts. The control-scope matcher uses the same rule, so a retried settle turn keeps authority over its children. Regressions cover both paths, and the dispatch assertion fails on the previous head. The PR's tests moved into sibling files to stay under the line cap; no assertions were removed.

This touches subagent completion delivery. It does not change NO_REPLY handling.

Landing is left to another maintainer.

@obviyus
obviyus marked this pull request as ready for review September 24, 2026 17:39
@roboclaw-bot

roboclaw-bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Adversarial review — completed

Reviewed the original c16d2f6 head in two adversarial passes, then verified the repairs at 4cf980c757d.

Findings

  1. P2 — Deliverable retries reused a cached terminal failure. A yielded private or mixed batch could exhaust retries without another delivery attempt because its idempotency key never changed. Confirmed the existing review finding. @obviyus fixed this concurrently in 903aedb; that commit is preserved. Definite failures now get fresh attempt keys, while ambiguous replays and legacy private batches retain their appropriate identities.
  2. P2 — Failed resumed turns could be credited as delivered. A timeout, error, empty result, or unsent final could close the pending completion batch without answering the user. Fixed in 4cf980c757d: session-bound deliverable settle turns require a confirmed final, successful intentional silence, or a proven handoff to the next wave.

The second repair also accounts for the real delivery path stripping NO_REPLY payloads. It reads the producer-owned terminal-reply snapshot, preserving successful normalized silence without treating failed silence as success. Private child output still has no raw-send fallback; requester-session binding remains intact.

Verification

  • Reproduced four retry-identity failures and five false-success cases before their repairs. Also reproduced the normalized-silence regression before correcting that boundary.
  • 357 delivery tests passed on the final classifier, plus private-settle, retry-identity, dispatch/cancellation, and SQLite close/reopen coverage.
  • Verified the real command-delivery normalizer suppresses NO_REPLY payloads.
  • Changed-check pipeline completed; final core and affected-test typechecks, scoped lint, and diff checks passed.
  • Final independent review found no remaining actionable P0–P2 findings in the reviewed scope.

The PR body contains detailed evidence and measured test costs. The existing live Telegram proof is from c16d2f6; I did not rerun live V2E for this follow-up. This is a review-and-repair result, not a merge or completed remote-CI claim.

@obviyus
obviyus force-pushed the fix/private-settle-owed-reply branch from 4cf980c to 67ac0bd Compare September 29, 2026 14:59
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 29, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 1, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 1, 2026
@obviyus
obviyus merged commit 9564dd6 into main Oct 1, 2026
86 of 201 checks passed
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 9564dd6.

Bug: a parent that yielded on private (completionTarget: "parent") subagents resumed as a private turn, so its own final answer was saved but never sent.

Fix: after a yield, the resumed parent answers under the conversation's normal reply rules (automatic rooms get the final; message-tool-only rooms still need the message tool). Child output stays private, NO_REPLY stays silent, a reset or replaced requester gets nothing, deliverable retries use fresh keys, and batches written by the released build stay private after upgrade.

Proof: current-head Telegram Test Server cells (reply policy, reset, and an upgrade from published 2026.9.7) plus focused regressions; ClawSweeper ready on the exact head. CI's remaining failures (core lint type errors in untouched src/state / src/gateway files, plus a max-lines failure reproducible on main) are unrelated; the PR head passes core lint locally. Merged by maintainer override.

Thanks @roboclaw-bot for the reply-policy and upgrade-path work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants