Skip to content

M1 source-level hardening: budget gate, treasury reserve, sanitization, outbound policy, fail-closed CI (B1–B4.1) - #417

Draft
kaydot20 wants to merge 11 commits into
Conway-Research:mainfrom
kaydot20:m1b-minimum-reserve
Draft

kaydot20 wants to merge 11 commits into
Conway-Research:mainfrom
kaydot20:m1b-minimum-reserve

Conversation

@kaydot20

@kaydot20 kaydot20 commented Oct 1, 2026

Copy link
Copy Markdown

Summary

Implements M1-A findings F1.1/F1.2 (plan budget gate), F2.1 (deterministic minimum reserve), F3.1/F3.2 (sanitize-all tool results + fail-closed task_result), F4.1–F4.3 (central outbound policy, SSRF/DNS guards, mandatory DNS on payment paths, CLI relay enforcement), F7.1–F7.3 (fail-closed CI).

Commits: 84576a0 (B1) · f85b0ca (B2) · fb4e9e2 (B3) · 341a86c (B4) · 067b8ef (B4 DNS remediation) · 0f63a17 (B5) · c08a376 (B4.1 CLI relay guard).

Draft on purpose — held for governance review; do not merge yet.

Validation status

  • Local Linux CI-mode battery: B1–B5 acceptance suites + security/financial/policy suites green (598/598 core + 443 security run).
  • tsc --noEmit (root + packages/cli): clean.
  • Source-hygiene gate: pass (4 allowlisted files). Audit gate: pass (29 advisories, all within 27 reviewed exceptions).
  • Known baseline Windows-only test failures do not reproduce on Linux CI (verified in prior runs of this suite set).

kaydot20 and others added 11 commits September 30, 2026 09:20
reviewPlan() auto mode previously approved every plan, including those
above autoBudgetThreshold (both branches returned approved: true), and a
rejection looped planning -> review -> planning unboundedly.

- Auto mode now fails closed: the authoritative cost is the computed sum
  of deterministic task-level estimatedCostCents; declared-total
  mismatches (PLAN_COST_MISMATCH), malformed/negative/non-finite costs
  (PLAN_COST_INVALID), and computed totals above the ceiling
  (PLAN_BUDGET_EXCEEDED) are all denied with machine-readable reasons.
- Orchestrator allows exactly one bounded cheaper-plan attempt after a
  budget denial; a second denial pauses the goal (existing non-looping
  "paused" status), blocks its pending tasks, and records an escalation
  for the owner. Approval clears the rejection counter so past
  rejections cannot poison future work. Raising the ceiling remains an
  owner/governance action.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
…pend paths

minimumReserveCents was declared but never enforced. Add one shared guard
(src/conway/reserve.ts) applied at every sink that moves funds:
transfer_credits, fund_child, the x402 pre-signing path, the orchestrator
SimpleFundingProtocol.fundChild helper (previously completely unchecked),
and the credit-topup helper (tier validation, solvency, cross-recipient
reserve). Self-topup (USDC->credits income) is reserve-exempt to avoid a
starvation lock; malformed/missing/NaN/infinite inputs deny fail-closed;
the exact-reserve boundary is inclusive and deterministic.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
…tion

F3.1: tool results were sanitized only for a three-tool allowlist, leaving
x402 bodies/errors, agent cards, git output, skill echoes and MCP results
as raw prompt-injection channels. Invert the default: executeTool now
sanitizes every result through sanitizeToolResult; only a small
TRUSTED_LOCAL_TOOLS allowlist of locally synthesized outputs opts out.
Error channels (unknown tool, policy denial, thrown tool errors) are
sanitized too.

F3.2: worker task_result envelopes were trusted: missing success defaulted
to true, output/error were persisted raw, and any taskId was accepted.
Missing/undeclared success is now a failure (fail-closed), content passes
the same taint boundary, and collectResults drops results for tasks not in
this orchestrator's task graph.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
Every outbound HTTP request now passes src/net/policy.ts: scheme is
https-only (loopback http behind an explicit dev flag), literal private/
reserved/metadata addresses and malformed hostnames are denied, and
purpose allowlists gate payment traffic. ResilientHttpClient follows
redirects manually (max 3) and re-validates every hop, so a redirect can
no longer bypass validation to reach private addresses. DNS-resolution
validation is resolver-anchored (clients may inject one; requireDnsResolution
fail-closes when absent).

x402Fetch applies the SSRF gate pre-signature; fetchAgentCard rides the
policy-checked client and validates IPFS CIDs before gateway splicing;
CLI send/fund relay fetches are guarded. The web_fetch -> x402_fetch
harness alias is removed: silently redirecting web fetches to the payment
tool was a surprise-spend vector. Payment-domain allowlists are not wired
into the default tool path (would deny ordinary paid fetches under the
shipped policy defaults); SSRF statics run unconditionally.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
Remediation of the M1-B4 acceptance gap: production payment requests must
resolve the hostname and validate every returned A/AAAA address against
the private/special-use blocklist before the first fetch and before any
signature. Resolution now runs whenever it is required or a resolver is
injected, defaults to system DNS (node:dns), and fails closed on resolver
failure, empty answers, or malformed output. The x402 transport requires
DNS on every hop (precheck, probe, paid retry, and each redirect
destination); tests inject fake resolvers instead of weakening
enforcement. All topup entry points (tool, heartbeat, inline loop,
startup, spawn-402) thread the optional config.dnsResolver through, so
the B2 self-topup rescue works unchanged with a public resolution.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
F7.1: remove the `timeout ... exit 0` bypasses that turned vitest hangs
into green CI. The hang is fixed properly in vitest.config.ts (forks
pool with singleFork, bail-on-first-failure in ci mode); a step timeout
now fails the job. The security suite is its own required gate running
the explicit hardening-acceptance file list.

F7.2: the dependency audit is fail-closed. pnpm audit's exit code is
unusable for gating (it exits 0 whenever ignore entries apply), so
scripts/audit-gate.mjs parses `pnpm audit --json` and fails on any
high/critical advisory outside an explicit reviewed exception list
(dev/toolchain paths only), and fails closed on unusable audit output.
A scheduled daily audit re-runs against fresh advisory data.

F7.3: add scripts/check-source-hygiene.mjs — a fail-closed gate banning
raw fetch()/execSync() outside the sanctioned network client, the
loopback Ollama discovery, the two policy-guarded CLI commands, and the
audited Conway exec fallback.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
Closes the F4.2 gap left by B4: packages/cli send/fund issued raw
relay fetch() calls with no SSRF enforcement. Both commands now
pre-validate the target through assertOutboundAllowed (purpose
"relay", mandatory DNS tier) before any signing or payload
construction, and transmit via a single guarded transport
(packages/cli/src/lib/relay-fetch.ts) that re-validates every
redirect hop, strips Authorization on cross-origin redirects, and
converts 303 to GET without a body.

The source-hygiene allowlist shrinks accordingly: the send.ts and
fund.ts exceptions are removed and relay-fetch.ts is the only raw
fetch() call site in the CLI. Regression suite
(packages/cli/src/__tests__/relay-policy.test.ts, 29 tests) proves
public-HTTPS allow, literal-private deny, DNS private/mixed/failure
deny, malformed-host bypass deny, redirect-to-private deny before
the redirected fetch, and zero side effects on denial.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
…diation)

Root cause of the fail-closed CI hang (both matrix jobs, 2/2
deterministic): estimateTokens handed arbitrarily large strings to
the real js-tiktoken cl100k_base encoder, whose pure-JS BPE cost is
superlinear on degenerate inputs — a single 100 KB same-character
run measures ~26 s at 10 KB and extrapolates to hours, blocking the
event loop. buildContextMessages legitimately builds 100-500 KB
turns (budget enforcement is its purpose), so the first oversized
estimate froze the vitest worker before any test executed; the
parent then never exited and CI killed the step at 15:00. The same
path would freeze the live agent loop on a huge tool result.

Remediation: text above BPE_TOKENIZE_MAX_CHARS (8,000 chars) takes
the conservative ceil(len/4) heuristic instead of the encoder —
bounded, deterministic, and within the estimator's documented
tolerance. Normal-size text still uses the real tokenizer.

Also fixes a latent test bug found during bisect: require("crypto")
in an ESM package replaced with a node:crypto import.

Regression tests pinned to the exact CI-hang shape (20 x 100 KB
turns, 100 KB degenerate string): the suite that previously hung
indefinitely now completes in ~12 s (32/32).

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
…tion)

Second defect the fail-closed full-suite run exposed after the
tokenizer fix unblocked the scheduler suite: buildTickContext awaited
the on-chain USDC balance read (real viem/Solana RPC, no timeout)
and the credits balance without any bound, so a slow endpoint froze
the tick — deterministic locally but timing-dependent on CI runners,
where 'prevents concurrent tick execution' timed out at 30 s and
bail=1 skipped the remaining 37 files.

Both fetches are now hard-bounded (5 s): on timeout the balance
degrades to 0 — the same conservative fallback the existing error
path uses — and the next tick retries. A stalled RPC can no longer
freeze the production heartbeat either.

Two deterministic regressions prove the tick completes when each
fetch never resolves (22/22 in the scheduler suite, ~16 s).

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
…iation 3/3)

Root cause of the recurring CI scheduler-suite timeout: one
inference-client retry test created vi.spyOn(globalThis, "setTimeout")
while fake timers were active and never restored the spy. That spy
pins the fake timer implementation on the worker's globals in a way
that survives useRealTimers(), mockRestore(), afterAll re-sync, and
unstubGlobals — freezing real setTimeout in every suite that runs
after it in the shared single-fork worker. This also silently
disabled the new 5 s balance-fetch bound (setTimeout-based),
resurfacing the RPC stall inside the overlap-prevention test.

Proven by minimal reproduction (fake timers + global setTimeout spy
= leak; bare fake timers = no leak) and a real-timer canary.

Remediation: capture backoff delays via a plain delegating wrapper
with try/finally restore instead of a global spy under fake timers.
Defensive useRealTimers() hygiene added to the scheduler suite, plus
a fail-fast real-timer canary guard that names the actual cause if
this pattern ever regresses.

Interaction pair (leaker -> victim) now passes 46/46 in ~13 s
(previously deterministic 30 s timeout).

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
…emediation 4/4)

The planner-backed delegation test isolated the agent workspace by swapping
process.env.HOME, but AgentWorkspace resolves its basePath via os.homedir().
The swap never worked on Windows (homedir uses USERPROFILE) and is
permanently neutralized in full-suite runs once an earlier suite replaces
the process.env object (provider-registry, inference-client,
inference-failover), so plan artifacts persisted under the real home and
the tempHome assertions failed even though delegation behaved correctly.
Stub os.homedir directly (the workspace.test.ts pattern) and restore all
mocks in afterEach. No assertions changed; product code untouched.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
@kaydot20

kaydot20 commented Oct 1, 2026

Copy link
Copy Markdown
Author

M1 hardening validation summary

M1_SOURCE_HARDENING_PREFLIGHT_PASS · M1_CI_VALIDATION_PASS

Gate Result
Fork CI run 36907790631 — success
Node 20 71 files / 1909 tests passed
Node 22 71 files / 1909 tests passed
Security tests (both nodes) 561/561 passed
security-audit PASS
source-hygiene PASS

Exact validated head: ecae43a (branch m1b-minimum-reserve).

Final commit is test-fixture-only (os.homedir stub for workspace isolation in the local-worker-harness suite); no product code changes since the planner/heartbeat/tokenizer hardening commits. CI runs use bail: 1 fail-closed mode — no timeouts raised, no gates weakened.

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