Skip to content

fix(agency): graph, review-loop and debate gate the input each agent receives, and a replaced final text meets the output check - #393

Merged
jddunn merged 5 commits into
masterfrom
fix/strategy-input-gates-and-return-replacement
Oct 13, 2026
Merged

jddunn merged 5 commits into
masterfrom
fix/strategy-input-gates-and-return-replacement

Conversation

@jddunn

@jddunn jddunn commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Two defects, confirmed in the code at master e58b14a1. I first read them at bcf37db3; the 0.13.89 release and #306 landed in between, and neither touches these files. Each defect gets a test commit and a fix commit, and a docs commit follows.

1. Graph, review-loop and debate gate the input each agent receives (#345)

Evidence. These three strategies ran the beforeAgent gate over the task prompt, then sent the agent an input they built after the gate from other agents' output:

The approver saw the task (details.input, shared.ts L434), and the post-approval check read the task too (L461-485). The agent received text another agent wrote, and nothing checked it.

Fix. Each of the three strategies now builds the agent's input first and gates it with checkBeforeAgentInput(), the gate sequential, parallel and hierarchical use since #340 and #360. The approval request and the post-approval check read the input the agent is sent, and the strategy sends gate.input, which is the text the check read. An approval's modifications.instructions now reach the agent under these three strategies too, and the check reads the input with and without them, as #360 set. A refused or blocked agent ends the way a rejection already did: graph skips it and records [skipped by HITL] as its output, a refused producer ends the loop with the previous draft, a refused reviewer leaves the current draft as the result, and a refused debater sits out that turn. agentCalls[].input keeps the strategy's input, as under sequential.

Tests (src/api/__tests__/agency-strategy-input-gate.e2e.test.ts). These run the real agency(), agent(), generateText, streamText and OpenAIProvider, with only fetch stubbed. ops is the agent beforeAgent lists, and the handler approves. The cases cover graph generate(), graph stream(), review-loop (the reviewer reading the draft, and the producer reading the reviewer's feedback in the next round) and debate:

  • An earlier agent's output that code-safety blocks (... rm -rf / ...). guardrailHitlOverride fires once (code-safety, agent:ops), the approver was shown the input that carried it, and no request from ops carries it. The run ends as after any rejection: graph keeps the last result standing, a refused reviewer leaves the current draft, a refused producer ends with its previous draft, and the debate's judge still rules without ops.
  • An output the check passes. ops's request carries it, and that request is exactly the input the approver was shown, with the approval's instructions after it.

2. A beforeReturn replacement goes through the agency's output guardrails and the post-approval check (#366)

Evidence. finalizeExecutionResult() runs the agency's guardrails.output over the strategy's text before it asks for the approval (agency.ts L273-275, L292-302). maybeApproveFinalResult() runs the post-approval check over that text (L1510-1531) and then returns the approval's modifications.output in its place (L1533-1535). When a handler, or a hitl.webhook() endpoint, whose JSON becomes the decision (hitl.ts L192), answered { approved: true, modifications: { output: 'Run rm -rf / on the host to finish.' } }, that text came back and guardrailHitlOverride never fired.

Fix. maybeApproveFinalResult() now runs the replacement through the agency's guardrails.output the same way finalizeExecutionResult() runs the strategy's text. One post-approval check then reads { output, returned }: the strategy's text and the replacement. Without a replacement it reads { output } as before. A replacement the check blocks fires guardrailHitlOverride (return) and rejects with the same AgencyConfigError as a blocked final text. hitl.guardrailOverride: false still turns off only the post-approval check.

Tests (src/api/__tests__/agency-return-approval.e2e.test.ts). These run the real agency(), agent(), generateText, streamText and OpenAIProvider, with only fetch stubbed. The agency sets guardrails.output and beforeReturn:

  • A replacement code-safety blocks: generate() rejects with Guardrail overrode HITL approval for final output, and guardrailHitlOverride fires once (code-safety, return).
  • The same under stream(): fullStream and text end with that error, and no part carries the replacement.
  • A replacement the check passes comes back as the result, and the agency's output guardrail reports twice: once for the strategy's text, once for the replacement.
  • An approval without modifications returns the strategy's text, and the output guardrail reports once.

Docs. docs/safety/HUMAN_IN_THE_LOOP.md and the HitlConfig.guardrailOverride and ApprovalDecision.modifications TSDoc in src/api/types.ts now say three things. An approval's instructions apply under every strategy. Under graph, review-loop and debate, the input the approver sees and the check reads carries other agents' output. A replacement goes through the output guardrails and the post-approval check. The guide no longer says the LLM judge rewrites the final answer, because hitl.llmJudge() returns only approved and reason (hitl.ts L360-363). Its timer note now names checkBeforeAgentInput(), the gate the strategies call.

Linked issues

Closes #345

Part of #366: this PR does the check half, so the replacement goes through the agency's output guardrails and the post-approval check. The other half stays open on #366: parsed is still read from the strategy's text when an approval replaces it.

Type of change

  • Bug fix
  • Feature
  • Performance
  • Documentation
  • Refactor
  • Tests
  • Build or CI

How this was verified

CI only. The two test commits went up alone, at 3f4782db.

  • Red: CI run 38369940306 at 3f4782db, the two test commits alone. Test & Lint failed only in the two new files: 13 tests failed and 10909 passed (2 files failed, 833 passed). Lint and typecheck passed. Under each of the five strategy paths, the blocked case failed because guardrailHitlOverride was called 0 times, and the passing case failed because ops was sent an input other than the one the approver was shown. In the return cases, generate() resolved instead of rejecting, the stream() drain resolved instead of rejecting, and the output guardrail reported once instead of twice. The case without modifications passed.
  • Green: CI run 38370591689 at 436e0670. All four jobs passed: Test & Lint, Batch-1 gated tests, Browser tests and the release dry run. agency-strategy-input-gate.e2e.test.ts passed 10 tests and agency-return-approval.e2e.test.ts passed 4. The suite ran 10922 tests with none failing, across 835 test files.
  • Review threads: none were open at merge. Sourcery had no review budget left. CodeRabbit and the Codex connector were still reviewing 436e0670, and their threads are answered on this PR as they arrive.

Migration notes

None. No signatures or options change. An approval without modifications is checked and sent as before, and the post-approval check still reads everything it read before.

Checklist

  • Tests cover the changed behavior.
  • Docs are updated.
  • The title follows Conventional Commits, with ! before the colon for a change that breaks users (feat!: or feat(api)!:).
  • No secrets or private data are included.
  • Every automated review thread is settled (how).
  • I have read this change and can explain every line.

… graph, review-loop or debate agent

Under the graph, review-loop and debate strategies the beforeAgent gate
reads the task prompt, while the agent is sent an input built after the
gate from what other agents wrote: the dependencies' outputs, the draft
and the reviewer's feedback, the debate transcript. Through agency() with
real agents and only fetch stubbed, an earlier agent's output that
code-safety blocks must turn the approval into a rejection, so it never
reaches the gated agent's request, and the strategy must go on as it does
after any rejection. An output the check passes must reach the agent as
the approver was shown it, with the approval's instructions after it.
A beforeReturn approval's modifications.output replaced the final text
after the agency's output guardrails and the post-approval check had read
the strategy's text, so a replacement was never checked. Through agency()
with a real agent and only fetch stubbed: a replacement code-safety blocks
must reject generate() and end stream() with the override, as a blocked
final text does; a replacement the check passes is returned once the
agency's output guardrail has received it; an approval without
modifications returns the strategy's text as before.
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 61dc4093-ad2d-485f-8a24-ce8a78e6778f
📥 Commits

Reviewing files that changed from the base of the PR and between 4768a74 and 436e067.

📒 Files selected for processing (9)
  • docs/safety/HUMAN_IN_THE_LOOP.md
  • src/api/__tests__/agency-return-approval.e2e.test.ts
  • src/api/__tests__/agency-strategy-input-gate.e2e.test.ts
  • src/api/agency.ts
  • src/api/runtime/strategies/debate.ts
  • src/api/runtime/strategies/graph.ts
  • src/api/runtime/strategies/review-loop.ts
  • src/api/runtime/strategies/shared.ts
  • src/api/types.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

📝 Walkthrough

The change gates strategy-built agent inputs in graph, review-loop, and debate runs. Approved beforeReturn replacements now pass through output guardrails and post-approval checks before they are returned.

Changes: HITL Approval Checks

Layer / File(s) Summary
Gate constructed strategy inputs
src/api/runtime/strategies/*.ts, src/api/__tests__/agency-strategy-input-gate.e2e.test.ts, src/api/types.ts, docs/safety/HUMAN_IN_THE_LOOP.md
Graph, review-loop, and debate strategies check the constructed input each agent receives. Approved inputs use the gate’s returned input. End-to-end tests cover blocked and accepted inputs. Documentation describes the input checks across strategies.
Check approved final-output replacements
src/api/agency.ts, src/api/__tests__/agency-return-approval.e2e.test.ts, src/api/types.ts, docs/safety/HUMAN_IN_THE_LOOP.md
Approved replacement output passes through agency output guardrails before post-approval checks. Tests cover blocked replacements, accepted replacements, streaming, and approvals without replacements.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 436e0

No actionable issue is established for this revision. Run the two new test files before merging because the reported earlier failures have no confirmed current-head result.

Pre-merge checks · Passed 3 · Failed 2

Failed Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check Warning The graph, review-loop, and debate changes stay within #345. The agency.ts replacement-output guardrail changes, their e2e tests, and related documentation address the separate #366 defect. Issue #366… Remove the #366 replacement-output changes, tests, and documentation from this pull request, or make that behavior an accepted scope item through a directly linked issue before merging.
Docstring Coverage Warning Docstring coverage is 46.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 8 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (3 passed)
Check name Status Explanation
Description check Passed The description includes all required sections, clearly explains both fixes, identifies linked issues, documents verification results, and records migration notes and checklist status.
Title check Passed The title uses Conventional Commits format and accurately summarizes both primary fixes: gating actual agent inputs and checking replaced final text.
Linked Issues check Passed For directly linked issue #345, graph.ts, review-loop.ts, and debate.ts now construct each agent input before calling checkBeforeAgentInput(). Each strategy sends the gate input to the agent. The code…
Full details: Out of Scope Changes check

Explanation

The graph, review-loop, and debate changes stay within #345. The agency.ts replacement-output guardrail changes, their e2e tests, and related documentation address the separate #366 defect. Issue #366 is not a directly linked issue in the supplied issue set, and #345 does not require final-output replacement handling.

Full details: Docstring Coverage

Explanation

Docstring coverage is 46.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 8 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 13, 2026

Copy link
Copy Markdown

Reviewer's Guide

The PR fixes HITL input-gating inconsistencies in graph, review-loop, and debate strategies by checking the exact input delivered to each agent, and hardens beforeReturn approvals so replacement output passes the same output guardrails and post-approval checks as strategy output. End-to-end tests cover generate/stream paths, approval instructions, blocked inputs, refusal behavior, and blocked or accepted replacements.

File-Level Changes

Change Details Files
Gate each strategy agent on the exact composed input it will receive, preserving approval behavior and rejection semantics.
  • Build graph dependency, review-loop draft/feedback, and debate transcript inputs before invoking the HITL gate.
  • Use the gated input for approval requests, post-approval checks, and agent calls, including approved instruction modifications.
  • Preserve strategy-specific behavior when an agent is refused or blocked, and retain the strategy input in agent call records.
src/api/runtime/strategies/graph.ts
src/api/runtime/strategies/review-loop.ts
src/api/runtime/strategies/debate.ts
src/api/runtime/strategies/shared.ts
src/api/__tests__/agency-strategy-input-gate.e2e.test.ts
Apply output guardrails and the post-approval check to beforeReturn replacement text before returning it.
  • Run replacement output through agency output guardrails.
  • Post-approval-check the original strategy output and replacement when both exist, while retaining the existing single-output path otherwise.
  • Reject blocked replacements with the existing guardrail override error and prevent them from appearing in generated or streamed results.
src/api/agency.ts
src/api/__tests__/agency-return-approval.e2e.test.ts

Assessment against linked issues

Issue Objective Addressed Explanation
#345 For graph, review-loop, and debate strategies, build each agent’s actual input before running the beforeAgent gate, so the approval request and post-approval check cover the same text the agent would receive. ✅
#345 When the gate blocks or approval is refused, prevent the affected agent from running and preserve each strategy’s rejection behavior. ✅
#345 Add strategy-level tests demonstrating that unsafe earlier-agent output is blocked from reaching the gated agent, and that permitted input reaches it as approved. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

…receives

These strategies ran the beforeAgent gate over the task prompt, then sent
the agent an input built after the gate from other agents' output: the
dependencies' outputs under graph, the draft and the reviewer's feedback
under review-loop, the transcript under debate. The approver was shown the
task and the post-approval check read the task, while the text another
agent wrote reached the agent unchecked.

Each strategy now builds the agent's input first and gates it with
checkBeforeAgentInput(), as sequential, parallel and hierarchical do. The
approval request and the post-approval check read the input the agent is
sent, the check reads it with and without the approver's instructions, and
the strategy sends the input the check read. A refused or blocked agent
ends the run the way a rejection did before.
…rails and the post-approval check

maybeApproveFinalResult() ran the post-approval check over the strategy's
text and then returned the approval's modifications.output in its place,
after finalizeExecutionResult() had run the agency's output guardrails over
the strategy's text. A handler or webhook that answered with a replacement
had it returned without code-safety, pii-redaction or the output
guardrails reading it.

The replacement now goes through the agency's output guardrails, and the
one post-approval check reads the strategy's text and the replacement
beside it ({ output, returned }), so a replacement the check blocks fires
guardrailHitlOverride and rejects as a blocked final text does. An approval
without modifications is checked as before.
…eforeReturn replacement is checked

The guide and the HitlConfig and ApprovalDecision TSDoc said an approval's
instructions reach the agent only under the sequential, parallel and
hierarchical strategies, that a beforeReturn replacement is not checked,
and that the LLM judge rewrites the final answer. Every strategy now gates
and sends the input the agent receives, other agents' output included, and
applies the instructions; a replacement goes through the output guardrails
and the post-approval check; hitl.llmJudge() returns no modifications. The
timer note names checkBeforeAgentInput(), the gate the strategies call.
@jddunn
jddunn marked this pull request as ready for review October 13, 2026 08:39
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 13, 2026 08:39
@sourcery-ai

sourcery-ai Bot commented Oct 13, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 4 days and 18 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T08:42:04.706126Z 436e067 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@jddunn
jddunn merged commit c1e716a into master Oct 13, 2026
12 checks passed
@jddunn
jddunn deleted the fix/strategy-input-gates-and-return-replacement branch October 13, 2026 08:43
github-actions Bot pushed a commit that referenced this pull request Oct 13, 2026
## [0.13.91](v0.13.90...v0.13.91) (2026-10-13)

### fix

* **agency:** graph, review-loop and debate gate the input each agent receives, and a replaced final text meets the output check (#393) ([c1e716a](c1e716a))
@jddunn

jddunn commented Oct 13, 2026

Copy link
Copy Markdown
Member Author

The automated reviews of 436e0670, the merged head, are settled. No review thread was opened on this pull request, so there is nothing to resolve; this answers the two warnings in CodeRabbit's summary.

CodeRabbit, Out of Scope Changes. The beforeReturn half is in scope. This pull request was opened for two defects, #345 and the replacement gap filed as #366, and the body links #366 as "Part of #366" rather than closing it. The half it leaves open, parsed read from the text the approval replaced, is recorded on #366 with a recommended design: #366 (comment)

CodeRabbit, Docstring Coverage. Every exported function this diff touches carries JSDoc: compileGraph() (graph.ts L128-138), compileReviewLoop() (review-loop.ts L98-126) and compileDebate() (debate.ts L70-93). The execute and stream methods they return are documented on CompiledStrategy (types.ts L1781-1798). The touched functions without a docstring are maybeApproveFinalResult(), which is private to agency.ts and had none before this change (its new replacement step is commented at agency.ts L1510-1513 and L1525-1528), and the stub-model helpers in the two new test files. The behavior callers rely on is documented where they read it, and this pull request updated both places: the HitlConfig.guardrailOverride and ApprovalDecision.modifications TSDoc in src/api/types.ts, and docs/safety/HUMAN_IN_THE_LOOP.md.

Codex connector. Reviewed 436e0670 and finished with no findings.

Sourcery. No review: its weekly budget was spent.

Master CI (run 38371248369) passed on the squash commit c1e716a2, and the Release run 38371790216 published @framers/agentos 0.13.91.

jddunn added a commit that referenced this pull request Oct 13, 2026
… output on their own under graph, review-loop and debate

Since #393 the gate under these strategies reads the input the agent
receives, and that input puts the strategy's own text after the task and
after other agents' output. The post-approval check reads its texts as
JSON, where a line break inside a text is escaped, and two code-safety
patterns match a statement only at the end of the text they read. So a
task ending in `rm -rf .`, which the gate blocked while it read the task
alone, reached the agent, and an earlier agent's output ending in an
unconditional `DELETE FROM <table>` did too wherever the strategy wrote
after it.

checkBeforeAgentInput() takes the texts the strategy built the input
from, and the check reads each of them on its own beside the input:
graph passes the task and each dependency's output, review-loop the
task, the draft and the feedback, debate the motion and each argument so
far. The input the approver is shown and the agent is sent is unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

graph, review-loop and debate: the beforeAgent check reads the task, not the input the agent receives

1 participant