Skip to content

fix: message gate stability, security, 429 retry & load performance (v0.13) - #134

Merged
rlaope merged 1 commit into
masterfrom
feat/v0.13-gate-stability-performance
Nov 30, 2026
Merged

rlaope merged 1 commit into
masterfrom
feat/v0.13-gate-stability-performance

Conversation

@rlaope

@rlaope rlaope commented Nov 30, 2026

Copy link
Copy Markdown
Owner

Summary

Hardens the message gate, policy boundaries, transport rate-limit resilience, memory/queue bounds, and hot-path performance across Slack, Discord, Telegram, and the local terminal.

Security & Policy Boundaries

  • Subagent & case-safe tenant isolation (core/policy.ts): Derives delegated subagents' tenant scope from session.header.cwd with case-folded realpathSync.native checks (macOS/Windows), blocks unmapped shared sessions from reading inside tenantRoot, and fails closed when resolvedCwd is pending.
  • Fail-closed .env & tool policy (core/policy.ts, index.ts): Protects <tenantCwd>/.env, fails closed on .env writes while workspace confinement is initializing, and returns { kind: 'deny' } if startToolPolicy throws unexpectedly.
  • Network & input hardening (core/policy.ts, netPolicy.ts, injection.ts, core/memory.ts, index.ts): Blocks IPv6-mapped metadata SSRF, validates proxy ports (1..65535) with safe socket teardown, eliminates polynomial ReDoS in injection.ts while scanning head+tail on large inputs, guards recalled past passages through guardFetchedText, and verifies resolvesInside before readFileSync in core/memory.ts.
  • Action gate (index.ts): Enforces action target channel binding and allowlist verification in handleAction, and deduplicates stale alreadyHandled notices per action ID.

Transport Resilience & Bounded I/O

  • HTTP 429 retry & safe error parsing (transports/slack.ts, transports/discord.ts, transports/telegram.ts): Bounded retry honoring Retry-After / retry_after and Discord X-RateLimit-Global, plus text-before-JSON parsing so 502/HTML responses never throw SyntaxError.
  • Bounded streaming attachments (transports/attachments.ts, transports/slack.ts, transports/telegram.ts): readBoundedBytes aborts oversized streams mid-flight; writeAttachments enforces maxFiles, post-fetch maxBytes, collision-safe case-insensitive deduplication, and maxTotalInlineChars; Telegram rejects file_path traversal; Slack enforces HTTPS and non-HTML responses.
  • Refcounted typing & handshake timeout (transports/discord.ts, transports/telegram.ts, transports/slack.ts): Refcounts typing indicators per channel/chat with immediate onUnavailable propagation on failed entries; adds a 20s Discord gateway handshake timeout (cleared on READY/RESUMED/close); deduplicates concurrent Slack loadNames() and removes cfg mutation races.

Load, Queue & Memory Performance

  • Hot-path I/O & CPU (core/state.ts, index.ts, recallContext.ts, transports/history.ts): Eliminates per-event fsyncSync stalls on health.json and alreadySeen() (atomic rename { fsync: false } + coalesced counter writes), adds O(1) sessionToKey reverse lookups, batches withdrawWaiting state writes, caches tail-bounded watch-alerts.jsonl reads, memoizes recallContext candidates with live file-change invalidation, and fast-paths CJK/Hangul in quoted().
  • Queue backpressure & lifecycle bounds (index.ts, core/state.ts, transports/composite.ts, transports/local.ts): Validates maxConcurrency (1..64), enforces maxQueuePerConversation / maxTotalQueued / maxQueueWaitMs (with clean progress/TUI cleanup on expiration), bounds long-lived Maps/Sets (state.seen timestamp-evicted at 10k, composite.owners 2k, requesterOf 5k, transport caches), prunes orphaned state.platformOf, and disposes all listeners/timers on unload.

Verification

  • pnpm run build && pnpm run typecheck: passed.
  • node test/v13-gate-perf.test.ts: 46/46 checks passed.
  • pnpm test: all 49 local unit test suites + secrets scan (416 files) passed (EXIT=0).
  • Independent adversarial review completed and all 13 findings fixed and re-verified.

Still Unverified

  • Live-model end-to-end scenarios (test/run-scenario.ts) and live gateway daemon redeploy/health-check were not executed in this environment.

…v0.13)

What was wrong:
- Delegated subagents under tenantIsolation had no state.sessions mapping,
  falling back to the shared home read scope; case-insensitive paths on
  macOS/Windows could bypass tenantRoot checks; evaluateReadScope and
  evaluateEnvFileWrite failed open while resolvedCwd was pending, and
  startToolPolicy deferred on unexpected errors.
- evaluateEnvFileWrite missed tenant <sessionCwd>/.env; evaluateFetch did not
  block IPv6-mapped metadata addresses; netPolicy CONNECT proxy could throw on
  out-of-range ports; injection.ts had polynomial ReDoS shapes and only scanned
  the head of large inputs; recallContext blocks bypassed guardFetchedText;
  core/memory.ts did not verify resolvesInside before readFileSync.
- Slack, Discord, and Telegram lacked bounded HTTP 429 retry / Retry-After
  handling and safe text-before-JSON error parsing; attachment downloads could
  buffer unbounded streams or collide on duplicate/case-variant filenames;
  Discord/Telegram typing spawned one interval per queued turn instead of
  refcounting per channel/chat.
- handleAction did not verify action target channel binding or allowlist and
  could spam alreadyHandled notices; queues had no per-conversation/global cap
  or wait TTL; withdrawWaiting, health.json, and alreadySeen called fsyncSync
  on hot paths; sessionId->key lookups and listConversations did O(N) scans;
  long-lived Maps/Sets and plugin unload listeners were unbounded/undisposed.

What changed:
- core/policy.ts, netPolicy.ts, injection.ts, core/memory.ts: confined
  subagents via session.header.cwd with case-folded path checks and blocked
  shared sessions from reading inside tenantRoot; failed closed on pending
  resolvedCwd, .env writes, and toolPolicy exceptions; blocked IPv6-mapped
  metadata SSRF; validated proxy ports (1..65535) with safe teardown; removed
  ReDoS patterns and scanned head+tail; verified resolvesInside before reading.
- transports/attachments.ts, transports/slack.ts, transports/discord.ts,
  transports/telegram.ts, transports/local.ts, transports/composite.ts,
  transports/history.ts: added readBoundedBytes streaming cap, collision-safe
  deduplication, and maxFiles/maxTotalInlineChars limits; added bounded HTTP
  429 retry + X-RateLimit-Global + non-JSON error handling; refcounted typing
  indicators with immediate onUnavailable propagation; added Discord 20s
  handshake timeout; bounded all transport LRU caches; fast-pathed CJK/Hangul.
- core/state.ts, recallContext.ts, index.ts, messages.ts: added optional
  fsync:false atomic writes for health.json and alreadySeen, timestamp-ordered
  10k seen cap, orphaned platformOf pruning, O(1) sessionToKey reverse index,
  handleAction channel binding + stale-notice dedupe, queue backpressure and
  expiration cleanup, batched withdrawWaiting, cached tail-bounded
  watch-alerts.jsonl reader, memoized recallContext with live invalidation,
  recall injection guarding, and full listener/timer disposal on unload.

How it was checked:
- pnpm run build && pnpm run typecheck: passed.
- node test/v13-gate-perf.test.ts: 46/46 checks passed.
- pnpm test: all 49 unit suites + secrets scan passed (EXIT=0).
- Independent adversarial review completed; all 13 findings fixed and
  re-verified.

Still unverified:
- Live-model end-to-end scenarios (test/run-scenario.ts) and live gateway
  daemon redeploy/health-check were not executed in this environment.

Signed-off-by: rlaope <rlaope@users.noreply.github.com>
@rlaope
rlaope merged commit c7eb946 into master Nov 30, 2026
5 checks passed
@rlaope
rlaope deleted the feat/v0.13-gate-stability-performance branch November 30, 2026 18:15
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