Skip to content

feat(gateway): B4 — Confirmation Governor (commit-arg binding) + descriptor producer bridge - #59

Merged
supmo668 merged 4 commits into
mainfrom
mangyinm/syntropy-mcp-b4
Jul 10, 2026
Merged

supmo668 merged 4 commits into
mainfrom
mangyinm/syntropy-mcp-b4

Conversation

@supmo668

@supmo668 supmo668 commented Jul 10, 2026 •

Copy link
Copy Markdown

openclaw-syntropy-agentic-chat B4 (Governor + food-logging gate). Additive/inert (disabled-by-default plugin; core bridge behavior-preserving, no marker⇒byte-identical). T4.1 PendingConfirmStore (128-bit CSPRNG cnf_ ids, externalId-isolated, single-use atomic consume, TTL). T4.2-4.4 ConfirmGovernor — the A&D CRIT fix (commit-arg binding): preview wrapper (requires_confirm⇒descriptor+gateway-stamped pending, NO backend commit; gated on config commitTools allowlist, NEVER on backend-supplied requires_confirm = anti-compromise invariant) + deterministic confirm-parse (event.prompt, not LLM) + arg-reconstruction commit guard (params=previewArgs⊕constraint-validated confirmedFields, MODEL PARAMS DISCARDED; consume-before-allow; externalId+server+commit_tool bound). A4 producer bridge: payloads.ts lifts a governor-marked (details.__openclaw_component) tool result onto channelData={type:component,component} = B3's consumer's producer (grounding: AgentToolResult had no channelData; B3 consumer had no producer). CTO-RATIFIED (A4 refinement accepted — minimal, behavior-preserving, characterization-tested). QG: 4 reviewers+scorer heavy-security, 17 findings/14 FIXED incl. 2 commit-path FAIL-OPENS red-first (SEC-COLLISION cross-server-name-collision→ungated-commit; CODE-STALE-EXTID identity-downgrade→unverified-commit) + REDoS caps + forge-marker strip. CRIT kernel proven sound (confirmed-X-committed-Y impossible), cross-user/replay/TOCTOU verified. Gates: tsgo 0, 743 tests, sealed 60/60, B3 consumer unregressed. Receipt qgr-pr-prep-20260710-1610-d646258 ✓. 🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added configurable confirmation controls for mutating MCP actions.
    • Added secure preview, confirm, cancel, and commit workflows with expiration, single-use protection, and identity validation.
    • Added component handoff so confirmation details appear reliably in assistant responses.
  • Bug Fixes
    • Blocked unauthorized, replayed, expired, or invalid commit attempts.
    • Prevented forged component markers and unsafe field edits from being accepted.
  • Tests
    • Added comprehensive coverage for confirmation flows, security boundaries, expiration, and response rendering.

supmo668 and others added 4 commits July 10, 2026 15:15
…urity-critical pending-confirmation state (128-bit CSPRNG cnf_ ids, externalId user-isolation gating every read, single-use atomic consume delete-then-return, TTL + sweepExpired, sessionKey never an auth input) + 17 tests

Generated-With: Claude Code
Co-Authored-By: openclaw <[email protected]>
Co-Authored-By: Claude <[email protected]>
… A&D CRIT fix. Preview wrapper (requires_confirm ⇒ descriptor + gateway-stamped pending, no commit; commit_tool allowlist-gated) + deterministic confirm-turn parse (before_agent_start event.prompt, edits validated vs editableFields+constraints, NOT via LLM) + arg-reconstruction commit guard (params = previewArgs ⊕ constraint-validated confirmedFields, MODEL PARAMS DISCARDED; consume-before-allow single-use; externalId-isolated; pending binds to its commit_tool). + A4 producer bridge (marked-only tool-result → payload.channelData lift in embedded-runner, behavior-preserving). CRIT props red-first: confirmed-X-committed-Y impossible, no-pending/hallucinated/replay/cross-user all blocked. 714 tests green, tsgo 0, sealed 60/60

QGR-Finding: A
Generated-With: Claude Code
Co-Authored-By: openclaw <[email protected]>
Co-Authored-By: Claude <[email protected]>
…s fixed red-first: SEC-COLLISION (guard now resolves the SURFACED tool name + server-binds the pending so a collision-prefixed commit tool stays gated; fail-closed catch keys on surfaced name too) + CODE-STALE-EXTID (invalidate externalId cache on identity downgrade). Plus SEC-REDOS (unconditional pattern/value caps), DESIGN-REPROMPT (guard blocks unstaged confirm + surfaces re-prompt, no silent commit of un-edited previews), CODE-SILENT-DROP (synthesize ui.summary carrier when no text payload), SEC-FORGE-MARKER strip+re-validate, cap-lastwins, firstline-nonblank; +29 coverage locks (all constraint branches, guard-throw, proto, expiry-guard, xuser-parse, marker-drift). 743 tests green

QGR-Finding: SEC-COLLISION
Generated-With: Claude Code
Co-Authored-By: openclaw <[email protected]>
Co-Authored-By: Claude <[email protected]>
…ion Governor (security-critical)

Generated-With: Claude Code
Co-Authored-By: openclaw <[email protected]>
Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Confirmation flow

Layer / File(s) Summary
Pending confirmation storage
extensions/syntropy-mcp/src/pending-confirm-store.ts, extensions/syntropy-mcp/src/pending-confirm-store.test.ts
Adds owned, expiring, single-use pending confirmations with staging, cancellation, and cleanup.
Preview, confirm, and commit enforcement
extensions/syntropy-mcp/src/governor.ts, extensions/syntropy-mcp/src/governor.test.ts
Adds descriptor preview minting, deterministic confirmation parsing, field validation, and fail-closed commit guarding.
Plugin configuration and runtime hooks
extensions/syntropy-mcp/openclaw.plugin.json, extensions/syntropy-mcp/src/index.ts, extensions/syntropy-mcp/src/index.test.ts
Adds per-server commit-tool allowlists, identity caching, preview stamping, confirmation hooks, and commit enforcement.
Tool-result component propagation
src/agents/pi-embedded-runner/run/payloads.ts, src/agents/pi-embedded-runner/run.ts, src/agents/pi-embedded-runner/run/payloads.component-bridge.test.ts
Carries validated component markers into assistant payload channelData, including synthesized silent-output payloads.
Workstream receipt
workstreams/openclaw/qgr/...pr-prep-20260710-1610-d646258.md
Adds QGR metadata, hash attestations, procedural records, and verification results.

Estimated code review effort: 4 (Complex) | ~60 minutes

Poem

I’m a rabbit with a guarded gate,
Staging carrots while confirmations wait.
Pending IDs hop, then vanish on use,
Fields stay tidy, with no tricks to abuse.
Payloads carry a component bright—
A careful burrow, wired just right.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning It describes the work, but it does not follow the required template sections or include most mandatory fields. Rewrite the description using the repo template: add the required headings, summary bullets, change type, scope, linked issue, verification, evidence, compatibility, recovery, and risks.
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately highlights the main change: the Confirmation Governor and descriptor bridge.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch mangyinm/syntropy-mcp-b4

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

Copy link
Copy Markdown

⚠️ Formal models conformance drift detected

The formal models extracted constants (generated/*) do not match this openclaw PR.

This check is informational (not blocking merges yet).
See the formal-models-conformance-drift artifact for the diff.

If this change is intentional, follow up by updating the formal models repo or regenerating the extracted artifacts there.

@supmo668
supmo668 merged commit 91bcbaf into main Jul 10, 2026
9 of 13 checks passed
@supmo668
supmo668 deleted the mangyinm/syntropy-mcp-b4 branch July 10, 2026 23:16

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@extensions/syntropy-mcp/src/governor.ts`:
- Around line 411-430: The pattern validation in the c.pattern branch still uses
Node’s backtracking RegExp engine, allowing backend-controlled patterns such as
nested quantifiers to stall the event loop. Replace the new RegExp construction
and re.test call with a non-backtracking RE2-based matcher, or isolate matching
in a worker with a hard timeout and terminate over-budget execution; preserve
the existing length checks and invalid-pattern error handling.

In `@src/agents/pi-embedded-runner/run.ts`:
- Around line 966-968: Limit the component descriptor scan performed by
extractComponentChannelData() to tool-result messages generated during the
current turn rather than the session-wide attempt.messagesSnapshot; filter or
pass the current-turn message collection when constructing the assistant
payload’s channelData.

In `@src/agents/pi-embedded-runner/run/payloads.ts`:
- Around line 66-77: In the component-marker handling logic, retain the
validated result returned by parseComponentDescriptor instead of discarding it.
Update the carrier assignment to forward that parsed descriptor rather than raw
shape.component, ensuring sanitized fields are surfaced through the channel
path.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6f1a2835-0e43-4345-9d8b-471fa88a856c

📥 Commits

Reviewing files that changed from the base of the PR and between 1d36170 and c3c28f3.

📒 Files selected for processing (11)
  • extensions/syntropy-mcp/openclaw.plugin.json
  • extensions/syntropy-mcp/src/governor.test.ts
  • extensions/syntropy-mcp/src/governor.ts
  • extensions/syntropy-mcp/src/index.test.ts
  • extensions/syntropy-mcp/src/index.ts
  • extensions/syntropy-mcp/src/pending-confirm-store.test.ts
  • extensions/syntropy-mcp/src/pending-confirm-store.ts
  • src/agents/pi-embedded-runner/run.ts
  • src/agents/pi-embedded-runner/run/payloads.component-bridge.test.ts
  • src/agents/pi-embedded-runner/run/payloads.ts
  • workstreams/openclaw/qgr/SyntropyHealth-Applications-mo-openclaw-openclaw-SyntropyHealth-Applications-qgr-pr-prep-20260710-1610-d646258.md

Comment on lines +411 to +430
if (c?.pattern !== undefined) {
// ReDoS guard (CWE-1333): the pattern is BACKEND-controlled and could be
// catastrophic-backtracking. Cap the pattern source AND the tested value
// length UNCONDITIONALLY — independent of whether the backend set
// maxLength — before compiling or testing, so a malicious pattern/value
// can never stall the event loop.
if (c.pattern.length > MAX_PATTERN_LENGTH) {
return `field "${field.name}" has an invalid pattern constraint`;
}
if (value.length > MAX_PATTERN_TEST_LENGTH) {
return `field "${field.name}" is too long to validate against the pattern`;
}
let re: RegExp;
try {
re = new RegExp(c.pattern);
} catch {
return `field "${field.name}" has an invalid pattern constraint`;
}
if (!re.test(value)) return `field "${field.name}" does not match the required pattern`;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🌐 Web query:

Does Node.js V8 irregexp use backtracking (ReDoS possible with catastrophic patterns)?

💡 Result:

Yes, the standard Node.js (V8) regular expression engine, known as Irregexp, is a backtracking engine [1][2]. Because it uses backtracking, it is susceptible to Regular Expression Denial of Service (ReDoS) when processing catastrophic patterns—regular expressions that can lead to exponential time complexity when matched against crafted input [2][3][4]. To mitigate this, V8 introduced an experimental, non-backtracking regular expression engine (based on a Thompson-style NFA) that guarantees linear-time execution [5][2][3]. However, this engine: - Is not enabled by default in Node.js [2][3]. - Must be explicitly enabled using the --enable-experimental-regexp-engine flag [6][7]. - Lacks support for certain advanced features, such as backreferences and some types of look-arounds [6][2][3]. - Serves as an opt-in alternative; if an unsupported feature is used or the engine is not enabled, Node.js falls back to the default backtracking Irregexp engine [8][9][3]. Consequently, most Node.js applications remain vulnerable to ReDoS if they process untrusted input with complex regular expressions, as the default behavior remains backtracking-based [2][3]. Developers are often advised to use static analysis tools to identify vulnerable patterns or consider alternative libraries (such as those providing bindings for Google's RE2 engine) if they require non-backtracking performance for untrusted input [6][4].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant file region with line numbers.
file="extensions/syntropy-mcp/src/governor.ts"
wc -l "$file"
sed -n '360,470p' "$file" | cat -n

echo
echo "---- search constants/usages ----"
rg -n "MAX_PATTERN_LENGTH|MAX_PATTERN_TEST_LENGTH|pattern" extensions/syntropy-mcp/src/governor.ts extensions/syntropy-mcp/src -g '!**/node_modules/**'

Repository: Syntropy-Health/openclaw

Length of output: 9154


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the file and map its structure.
fd -a "governor.ts" .
ast-grep outline extensions/syntropy-mcp/src/governor.ts --view expanded || true

Repository: Syntropy-Health/openclaw

Length of output: 1611


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the surrounding implementation and the source of the constraint object.
file="extensions/syntropy-mcp/src/governor.ts"

echo "=== around target lines ==="
sed -n '390,445p' "$file" | cat -n

echo
echo "=== relevant symbols in governor.ts ==="
rg -n "MAX_PATTERN_LENGTH|MAX_PATTERN_TEST_LENGTH|new RegExp\\(|pattern\\.length|pattern:|validate.*pattern|constraint" "$file"

echo
echo "=== broader project search for RE2/safe-regex/regexp engine alternatives ==="
rg -n "re2|safe-regex|regexp.*timeout|non-backtracking|experimental-regexp-engine|pattern constraint" extensions/syntropy-mcp -g '!**/node_modules/**'

Repository: Syntropy-Health/openclaw

Length of output: 4231


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find the type that defines `c` and the field metadata source.
rg -n "interface .*pattern|type .*pattern|pattern\\?: string|maxLength|pattern" extensions/syntropy-mcp/src -g '!**/node_modules/**'

# If a likely type is found, show its definition file in context.

Repository: Syntropy-Health/openclaw

Length of output: 3426


Use a non-backtracking regex strategy here. The length caps reduce exposure, but they don’t prevent catastrophic backtracking in Node’s default RegExp engine for short adversarial patterns like (a+)+$. Since c.pattern is backend-controlled, this path can still stall the event loop; use RE2 or run the match under a hard timeout/worker budget.

🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 424-424: Do not use variable for regular expressions
Context: new RegExp(c.pattern)
Note: [CWE-1333] Inefficient Regular Expression Complexity. Security best practice.

(regexp-non-literal-typescript)


[warning] 424-424: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(c.pattern)
Note: [CWE-1333] Inefficient Regular Expression Complexity

(regexp-from-variable)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@extensions/syntropy-mcp/src/governor.ts` around lines 411 - 430, The pattern
validation in the c.pattern branch still uses Node’s backtracking RegExp engine,
allowing backend-controlled patterns such as nested quantifiers to stall the
event loop. Replace the new RegExp construction and re.test call with a
non-backtracking RE2-based matcher, or isolate matching in a worker with a hard
timeout and terminate over-budget execution; preserve the existing length checks
and invalid-pattern error handling.

Source: Linters/SAST tools

Comment on lines +966 to +968
// A4: surface any component descriptor a tool result marked
// (Confirm Governor) onto the assistant payload's channelData.
toolResultMessages: attempt.messagesSnapshot,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Determine messagesSnapshot construction, scope, and the role string used for tool results.
rg -nP -C4 'messagesSnapshot' src/agents/pi-embedded-runner
rg -nP -C3 'role:\s*["'\'']toolResult|role:\s*["'\'']tool' src/agents/pi-embedded-runner

Repository: Syntropy-Health/openclaw

Length of output: 20289


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the payload helper and snapshot plumbing, then inspect the exact logic.
ast-grep outline src/agents/pi-embedded-runner/run/payloads.ts --view expanded
ast-grep outline src/agents/pi-embedded-runner/run/attempt.ts --view expanded
ast-grep outline src/agents/pi-embedded-runner/run/types.ts --view expanded

# Read the relevant sections with line numbers.
sed -n '1,220p' src/agents/pi-embedded-runner/run/payloads.ts | cat -n
sed -n '820,1210p' src/agents/pi-embedded-runner/run/attempt.ts | cat -n
sed -n '1,120p' src/agents/pi-embedded-runner/run/types.ts | cat -n

# Look for tests or call sites that characterize the snapshot scope and toolResult role.
rg -n -C3 'extractComponentChannelData|toolResultMessages|messagesSnapshot|role:\s*"toolResult"' src/agents/pi-embedded-runner/run

Repository: Syntropy-Health/openclaw

Length of output: 50380


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the payload assembly around the component bridge and the surrounding tests.
sed -n '360,430p' src/agents/pi-embedded-runner/run/payloads.ts | cat -n
sed -n '1,180p' src/agents/pi-embedded-runner/run/payloads.component-bridge.test.ts | cat -n

# Check whether any code filters toolResultMessages down to the current turn.
rg -n -C2 'toolResultMessages\s*:|messagesSnapshot\b|extractComponentChannelData\(' src/agents/pi-embedded-runner/run | head -n 120

Repository: Syntropy-Health/openclaw

Length of output: 19142


Scope the component scan to this turn attempt.messagesSnapshot is session-wide, so extractComponentChannelData() can reuse an older role: "toolResult" marker and attach stale channelData to a later assistant reply.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/agents/pi-embedded-runner/run.ts` around lines 966 - 968, Limit the
component descriptor scan performed by extractComponentChannelData() to
tool-result messages generated during the current turn rather than the
session-wide attempt.messagesSnapshot; filter or pass the current-turn message
collection when constructing the assistant payload’s channelData.

Comment on lines +66 to +77
const shape = marker as { type?: unknown; component?: unknown };
if (shape.type !== "component" || !shape.component || typeof shape.component !== "object") {
continue;
}
// Defense-in-depth: re-validate the descriptor on the channel path (the
// gateway re-validates too, but this path may not). A forged/invalid
// descriptor is dropped rather than surfaced.
if (!parseComponentDescriptor(shape.component)) {
continue;
}
// Last-wins: the most recent valid component of the turn is surfaced.
carrier = { type: "component", component: shape.component };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether the schema strips/passes unknown keys and how data is shaped.
fd -t f 'component-descriptor.schema.ts' src | xargs -I{} ast-grep outline {} --items all
rg -nP -C3 '(passthrough|strict|strip|ComponentDescriptorSchema\s*=)' src/gateway/component-descriptor.schema.ts

Repository: Syntropy-Health/openclaw

Length of output: 2915


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the payload extraction logic and descriptor parsing shape.
sed -n '1,220p' src/agents/pi-embedded-runner/run/payloads.ts
printf '\n---\n'
sed -n '1,240p' src/gateway/component-descriptor.schema.ts

Repository: Syntropy-Health/openclaw

Length of output: 15638


Surface the parsed descriptor, not the raw marker payload. parseComponentDescriptor already sanitizes the marker before returning it; forwarding shape.component here re-emits the unsanitized input and can preserve stripped unsafe keys in channelData.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/agents/pi-embedded-runner/run/payloads.ts` around lines 66 - 77, In the
component-marker handling logic, retain the validated result returned by
parseComponentDescriptor instead of discarding it. Update the carrier assignment
to forward that parsed descriptor rather than raw shape.component, ensuring
sanitized fields are surfaced through the channel path.

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.

1 participant