Repository navigation
feat(agents): composable termination algebra + GSAR grounding scorer - #75165
fede-kamel wants to merge 3 commits into
Conversation
|
Codex review: found issues before merge. Reviewed August 16, 2026, 3:06 AM ET / 07:06 UTC. ClawSweeper reviewWhat this changesAdds composable agent-loop termination conditions and a GSAR grounding scorer, plus tests, a live-test suite, and a demo, while deferring production wiring. Merge readinessKeep open for an explicit maintainer product/architecture decision. The PR adds a large uncalled core surface, and the latest review on this exact head still has two GSAR correctness blockers. Priority: P3 Review scores
Verification
How this fits together
flowchart LR
A[sessions_send request] --> B[Bounded A2A flow]
B --> C[Alternating agent replies]
C --> D[Fixed cap or skip token]
D --> E[Announcement decision]
F[Proposed stop algebra] --> G[No production caller]
G --> B
Decision needed
Why: Current main already has a specific bounded A2A owner and no caller for this standalone API; carrying a dormant core surface is a product and architecture choice. Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +615, Tests +2805, Other +466. Total +3886 across 10 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Defer the branch behind the tracking issue until an agent-loop owner defines trusted evidence, selects the integration boundary, and repairs the GSAR scoring defects in that production design. Do we have a high-confidence way to reproduce the issue? Not applicable: this is a new capability, while current main already has a bounded A2A loop and no production caller for the proposed API. Is this the best way to solve the issue? No: standalone core groundwork before an owner-selected integration is not the best path, and the latest exact-head review retains two scoring defects. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 063ce57caf23. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (11 earlier review cycles; latest 8 shown)
|
bad8739 to
c5b42b0
Compare
How the live proof uses the OpenClaw SDKThe live test ( The call chain:
This matters for two reasons: 1. The proof is not synthetic. The algebra and GSAR conditions are checked against real token streams that went through the production transport — including streaming, backpressure, and abort signal handling. A mock HTTP client would not catch timing-sensitive bugs. 2. The conditions compose with the real loop. Running it: # With a stored OpenClaw profile (pnpm openclaw auth add anthropic)
OPENCLAW_LIVE_TEST=1 pnpm test:live -- src/agents/termination.algebra.live.test.ts
# Or with a raw key
OPENCLAW_LIVE_TEST=1 ANTHROPIC_API_KEY=sk-ant-... pnpm test:live -- src/agents/termination.algebra.live.test.ts
# Demo (no key needed — uses realistic mock responses through the same SDK types)
node --import tsx/esm scripts/demo-gsar-algebra.tsFull demo output + script: https://gist.github.com/fede-kamel/db4abad67be723c4610f1a84aee07590 |
bcb1a96 to
01cbd30
Compare
|
@steipete when you get a chance — rebased onto main, mergeable, 78 checks passing. The "Real behavior proof" check fails because the PR body lacks that formal section; the branch already includes live tests against the Anthropic API. Happy to add the section with captured output, or if easier you can apply the |
bd4c89c to
4678e3e
Compare
|
Rebased onto current @vincentkoc — flagging for review when convenient (composable termination algebra + GSAR grounding scorer for agent runs). |
4678e3e to
9213b17
Compare
|
This pull request has been automatically marked as stale due to inactivity. |
9213b17 to
ce0ddd2
Compare
cf54127 to
498e305
Compare
|
The two proof-accuracy findings from the July 5 review are fixed in ff12a4cf9f:
Verified by running the demo end-to-end ( The remaining blocker is the product/API decision the review routed to maintainers — whether library-only core termination/GSAR primitives should merge ahead of a production integration point (see the review's option 1 vs 3). Happy to move the modules to a different home (plugin SDK / agent-core) or park this behind #77981 if that's the preferred direction. |
|
The July 6 blocking finding is fixed in f1b5f4a1e6: @steipete — with the safety semantics fixed and the demo/proof mismatches from July 5 already addressed, the only remaining blocker is the product call the reviews route to you: accept the library-only core termination/GSAR primitives as groundwork (review option 1), relocate them (plugin SDK / agent-core), or park behind #77981 until the |
|
@fede-kamel thanks for the PR. ClawSweeper is still waiting on real behavior proof before this can move forward. Useful proof can be a screenshot, short video, terminal output, copied live output, linked artifact, or redacted logs that show the changed behavior after the fix. Please redact private tokens, phone numbers, private endpoints, customer data, and anything else sensitive. Once proof is added to the PR body or a comment, ClawSweeper or a maintainer can re-check it. |
|
@clawsweeper re-review Proof refreshed at the current head A fresh live-Anthropic capture was attempted today but is blocked: the local API credential now returns HTTP 401 |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
🔴 Live integration proof — real
|
| Layer | Real or replaced |
|---|---|
A2A loop (runSessionsSendA2AFlow, turn management, role swap) |
✅ real production code |
Prompt scaffolding (buildAgentToAgentReplyContext / buildAgentToAgentAnnounceContext) |
✅ real |
Control tokens (REPLY_SKIP / ANNOUNCE_SKIP handling) |
✅ real |
| Announce delivery routing (gateway seam) | ✅ real code, injected recorder via testing.setDepsForTest (same seam the colocated a2a tests use) |
LLM stack (completeSimple / extractAssistantText, openai-completions API) |
✅ real |
| Model | 🔴 live meta-llama/Llama-3.3-70B-Instruct-Turbo (Together endpoint) |
Step executor (runAgentStep) |
🔁 replaced: routes the exact message + extraSystemPrompt the loop hands it to the live model instead of a running gateway |
Two sessions: research orchestrator (agent:main:discord:group:research) ↔ fact-checker (agent:main:discord:group:factcheck). Task: verify three Eiffel Tower claims. Anthropic credentials are mid-rotation on this machine (see previous comment), so this uses a different live provider through the same OpenClaw LLM stack — which also demonstrates the algebra is provider-agnostic.
Results — 3/3 green in 13.5s
| # | Scenario | Setup | Outcome |
|---|---|---|---|
| 1 | Today's shipped behavior | flat maxPingPongTurns=4, no quality gate |
Fact-checker verified all 3 claims in round one — the loop still burned all 4 turns on drift ("Was the antenna part of the original design?" → "What year was it added?" → "1957"), then ANNOUNCE_SKIP. 6 live LLM calls, 4 wasted. |
| 2 | The follow-up wiring this PR enables | same sessions + GroundednessCondition(parseTaggedPartition).or(MaxIterations(4)) |
Exits after 1 of 4 turns at grounded:proceed:s=1.000, the moment all claims are confirmed grounded. |
| 3 | Safety (OrCondition first-stop-wins semantics) |
broken GSAR scorer (judge endpoint down) .or(MaxIterations(2)) |
Scorer error surfaces on turn 1 (visible, not swallowed); MaxIterations still fires on schedule at turn 2 — the rejecting sibling cannot delay or mask the hard bound. |
Scenario 1 is the failure mode this PR addresses, reproduced in the shipped code path with a real model. Scenario 2 is the fix: 4 turns → 1 turn.
Terminal capture (live run)
[a2a-live] step 1 (target): Confirmed: (1) The Eiffel Tower was completed in 1889. (2) It was designed by Gustave Eiffel's company. (3) It is approximately 330 meters tall, including the a
[a2a-live] step 2 (requester): Was the antenna part of the original design?
[a2a-live] step 3 (target): No, the antenna was not part of the original design. It was added later.
[a2a-live] step 4 (requester): What year was the antenna added?
[a2a-live] step 5 (target): The antenna was added in 1957, and later modified.
[a2a-live] step 6 (target): ANNOUNCE_SKIP
[a2a-live] scenario 1: round-one + 5 production-loop steps (ping-pong budget 4 + announce), llmCalls=6, announced=no (ANNOUNCE_SKIP)
[a2a-live] step 1 (target): Claims:
[a2a-live] step 2 (requester): All claims are verified [G]. No follow-up question needed.
[a2a-live] gsar turn 1: G=1 U=0 X=0 K=0
[a2a-live] scenario 2: exited after 1 of 4 ping-pong turns, reason=grounded:proceed:s=1.000
[a2a-live] step 1 (target): Confirmed: (1) The Eiffel Tower was completed in 1889. (2) It was designed by Gustave Eiffel's company. (3) It is approximately 330 meters tall, including the a
[a2a-live] turn 1: scorer failure surfaced (GSAR judge endpoint is down), loop continues under the hard bound
[a2a-live] step 2 (target): Confirmed details: original height 324m, antenna added later, increasing total height to around 330m.
[a2a-live] scenario 3: exited at turn 2 reason=max_iterations scorerErrors=1
Test Files 1 passed (1)
Tests 3 passed (3)
Duration 13.50s (transform 1.01s, setup 160ms, import 836ms, tests 12.42s, environment 0ms)
Branch status: squash-rebased onto current origin/main at 277e1d2c7d3 — the 19-commit series collapsed to its final, purely additive tree (termination/GSAR modules byte-identical to the proof capture; the deadcode-allowlist entries moved to config/knip.config.ts where the allowlist now lives; suites re-run green at the rebased head, 141/141). The harness above is kept out of the branch for now; happy to add it as a colocated live test here or land it with the follow-up sessions_send integration PR — maintainers' call.
Squashed rebase onto current origin/main (previous head f1b5f4a1e6; the 19-commit series collapsed to its final, purely additive tree). - src/agents/termination.ts: TerminationCondition algebra (TextMention, ReplyPattern, MaxIterations, TimeLimit, CustomCondition, and/or composition; OrCondition runs branches concurrently first-stop-wins so hard bounds fire even when a sibling stalls or rejects) - src/agents/gsar.ts: GSAR typed-grounding scorer (arxiv:2604.23366) with parseTaggedPartition, LLM-judge and hybrid scorers, calibration helpers, GroundednessCondition - colocated suites (141 tests) + live-API suite + standalone demo - knip entries moved to config/knip.config.ts (allowlist file was retired on main)
|
@clawsweeper re-review Branch squash-rebased onto current |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…uites Current main typechecks tests with noUncheckedIndexedAccess; assert known-in-bounds indexed reads (turn fixtures, score arrays, cycling scorer helpers) non-null, matching existing test style.
|
CI status at head |
|
@steipete surfacing this one for a product-interest read — review is clean at this point, and the one remaining item is the placement call the review routed to you. What it is: an AND/OR-composable termination algebra for agent loops plus a GSAR grounding scorer that gates loop exit on evidence-grounded output (e.g. Where it stands:
Fresh proof at the current head
The open question is placement: core |
|
If the size is what's holding this up, I'm happy to split it. The termination Happy to do that unprompted if it's easier to review that way. |
|
cc @vincentkoc — since the open question here is architecture placement (core |
|
Closing this implementation while leaving #77981 open for the product and owner-boundary decision. This branch is now conflicting and contributes 3,886 lines of library/demo/test groundwork without a production caller. Its own scope explicitly defers the trusted-evidence contract and If maintainers choose a concrete runtime caller and trusted evidence source in #77981, the implementation should start from that narrow contract on current main rather than revive this branch. |
Closes #77981
What this does
Today an OpenClaw agent-to-agent loop runs for a fixed number of turns no matter what happens inside it: if the subagent nails the answer on turn 2, the loop still burns the remaining turns; if it is hallucinating, the loop keeps going anyway and returns the junk. This PR adds the missing vocabulary for saying when an agent loop should stop: small termination conditions — "stop when the reply signals completion", "stop after N turns", "stop when the answer is actually backed by evidence" — that compose with
.and()/.or()into stopping rules that are safe by construction (a soft quality signal OR'd with a hard turn cap always terminates, and an AND guard never exits early on an unsupported answer). The evidence-based condition implements GSAR (Kamelhar 2026, arXiv:2604.23366), which classifies each claim in a reply as grounded / ungrounded / contradicted / complementary and turns that partition into a 0–1 score with proceed / regenerate / replan tiers — so a loop can exit the moment the answer is grounded, and keep pushing (within budget) while it is not. Both ship as standalone, fully-tested library primitives (src/agents/termination.ts,src/agents/gsar.ts) with unit + live-API coverage.Proof 1 — the algebra saves turns
Claude naturally signals completion. GPT does not. The combinator captures this difference without any provider-specific code.
Proof 2 — soft signals must be paired with a hard bound
Proven by the hallucinating-provider scenario: Claude never says DONE, GSAR score never reaches 0.80 —
MaxIterationsfires at turn 5 every time. Budget holds.The AND combinator lets you guard against vague early answers:
Proof 3 — GSAR score formula (arxiv:2604.23366 §3.2)
6 structural properties proven in the suite:
Proof 4 — GSAR decision tiers and threshold stability
calibrateThresholds()recovers the paper defaults from labeled examples. Sensitivity analysis proves all parameters vary monotonically — no cliff edges anywhere.Proof 5 — GSAR wired into a recovery loop
Real behavior proof
MaxIterationsbudgets, wasting turns when a provider has already produced a satisfactory answer or is actively hallucinating. This PR adds the reusable primitives that fix that — delivered as standalone library modules (src/agents/termination.ts,src/agents/gsar.ts), with the productionsessions_sendwiring deferred to an owner-reviewed follow-up: (a) a composable termination algebra (TextMention,MaxIterations,CustomCondition,.and(...),.or(...)) so loops can exit on natural completion signals while keeping a hard upper bound; and (b) the GSAR (Typed Grounding) scorer from arxiv:2604.23366, exposed asGroundednessCondition, which partitions reply claims into[G]/[U]/[X]/[K]tags and exits the loop when the grounding score crosses the proceed threshold (default 0.80). The two compose:new GroundednessCondition(scorer).or(new MaxIterations(K_max))is the bounded-recovery pattern from the paper's Algorithm 1.f1b5f4a1e6(the revision that adds first-stop-winsOrConditionsemantics, so hard bounds fire even when a sibling async branch stalls or rejects). The branch has since been squash-rebased onto currentorigin/mainas277e1d2c7d3(current head099435a8cdadds only non-null assertions in the test suites for main's stricter indexed-access typechecking); the termination/GSAR modules, suites, and demo script are byte-identical to the captured revision (verified withgit diff f1b5f4a1e6..277e1d2c7d3 -- <those files>returning empty; the only other change is the deadcode allowlist entries moving toconfig/knip.config.ts, where the allowlist now lives on main). The colocated suites were re-run green at the rebased tree: 5 files, 141 tests passed, and the demo below re-runs cleanly there too. The end-to-end demo atscripts/demo-gsar-algebra.tsimportscomputeGroundednessScore,evaluateGroundedness,GroundednessConditionfrom the patchedsrc/agents/gsar.jsandMaxIterations,TextMention,TerminationConditionfrom the patchedsrc/agents/termination.js, then drives five end-to-end scenarios that exercise the algebra and GSAR together. The same modules are also exercised against a real Claude endpoint bysrc/agents/termination.algebra.live.test.tsunderOPENCLAW_LIVE_TEST=1; captured Anthropic-API output from that suite is preserved earlier in this PR body.node --import tsx/esm scripts/demo-gsar-algebra.tsfrom the worktree. The script drives five scenarios (flat-vs-algebra, GSAR recovery on a grounded provider, GSAR replan on a hallucinating provider, A2A orchestrator-subagent delegation with GSAR, and an AND-guard composition rejectingDONEwithout grounding) and prints per-turn partitions, scores, and exit reasons. The same path is exercised against real Anthropic withOPENCLAW_LIVE_TEST=1 ANTHROPIC_API_KEY=... node scripts/test-live.mjs -- src/agents/termination.algebra.live.test.ts.node --import tsx/esm scripts/demo-gsar-algebra.tsagainst the patched modules (captured atf1b5f4a1e6; byte-identical modules on the rebased branch, where the demo re-runs cleanly):The colocated suites were re-run at the rebased branch in the same worktree (
pnpm test src/agents/termination.test.ts src/agents/gsar.test.ts src/agents/gsar.calibration.test.ts src/agents/gsar.openclaw.test.ts src/agents/termination.complex.test.ts), terminal capture:MaxIterationsat turn 5, GSAR exits at turn 2 once the partition is fully grounded, hallucinating provider replans through turns 1–2 and only proceeds at turn 3 once the partition shifts to all-grounded, A2A orchestrator+subagent exits at turn 2 with the subagent's three grounded claims, and the AND guard correctly rejectsDONEat turn 1 (because the underlying claim is ungrounded) and only releases at turn 2 when bothDONEand full grounding hold. The 146-test colocated suite at the same HEAD covers the newOrConditionsafety semantics (rejecting-sibling, never-settling-sibling, and error-propagation paths) alongside the algebra, GSAR scoring, calibration, and property suites.OPENCLAW_LIVE_TEST=1 pnpm test:live -- src/agents/termination.algebra.live.test.ts) was re-run on 2026-07-22 but the local Anthropic credential now returns HTTP 401authentication_error(key was rotated); the two loop-safety tests that don't depend on reply content still passed (flat budget always fires; hallucinating prompt never exceedsMaxIterations), while the four assertions requiring real reply text failed on empty replies — a credential issue, not a code regression (verified by a direct status-only probe of the resolved credential: HTTP 401). The previous live-API output preserved earlier in this PR body (5 independent runs showingflat=5 algebra=1 reason=text_mention:DONEconsistently, plus the per-turn GSAR partition trace) remains the authoritative real-API reference; a fresh capture will be posted once the key is rotated.Reviewer notes
RegExp.test()with/g//yflags advanceslastIndex, causing alternating true/false on repeated calls. Fixed withthis.pattern.lastIndex = 0before each check. Regression coverage included.gsar.tsis a library module imported only by colocated coverage today — declared as knip entries inconfig/knip.config.ts(the standalone allowlist file was retired on main).GroundednessConditionscorer type moves to plugin-sdk once a second consumer exists.