Skip to content

Secure IPC with per-group namespaces to prevent privilege escalation#3

Merged
gavrielc merged 1 commit intomainfrom
claude/secure-ipc-access-Ni9l4
Feb 1, 2026
Merged

Secure IPC with per-group namespaces to prevent privilege escalation#3
gavrielc merged 1 commit intomainfrom
claude/secure-ipc-access-Ni9l4

Conversation

@gavrielc
Copy link
Copy Markdown
Collaborator

@gavrielc gavrielc commented Feb 1, 2026

Each container now gets its own IPC directory (/data/ipc/{groupFolder}/)
instead of a shared global directory. Identity is determined by which
directory a request came from, not by self-reported data in IPC files.

Authorization enforced:

  • send_message: only to chatJids belonging to the source group
  • schedule_task: only for the source group (main can target any)
  • pause/resume/cancel_task: only for tasks owned by source group

https://claude.ai/code/session_018nmxNEbtgJH7cKDyBSQGAw

Each container now gets its own IPC directory (/data/ipc/{groupFolder}/)
instead of a shared global directory. Identity is determined by which
directory a request came from, not by self-reported data in IPC files.

Authorization enforced:
- send_message: only to chatJids belonging to the source group
- schedule_task: only for the source group (main can target any)
- pause/resume/cancel_task: only for tasks owned by source group

https://claude.ai/code/session_018nmxNEbtgJH7cKDyBSQGAw
@gavrielc gavrielc merged commit ade9f2d into main Feb 1, 2026
@gavrielc gavrielc deleted the claude/secure-ipc-access-Ni9l4 branch February 1, 2026 18:40
deverman pushed a commit to deverman/nanoclawswift that referenced this pull request Feb 2, 2026
…Ni9l4

Secure IPC with per-group namespaces to prevent privilege escalation
@chidev
Copy link
Copy Markdown

chidev commented Feb 3, 2026

QA Fixes Applied

Changes in commit f187ad4:

  1. Unsafe cast fixed: Added isValidRuntime() validation that checks CONTAINER_RUNTIME env var against allowed values (container, podman, docker). Throws descriptive error for invalid values.

  2. Silent catch blocks fixed: Added logger.debug() call in catch block during runtime detection, logging which runtime failed and why before trying the next.

  3. Rebased onto refactor/dedupe-logger: Now uses shared logger import from PR Fix security: only expose auth vars to containers, not full .env #2.

TypeScript compiles cleanly.

Rlin1027 referenced this pull request in Rlin1027/NanoGemClaw Feb 6, 2026
Added admin commands for main group only:
- /admin stats - Show uptime, memory, group count
- /admin groups - List all registered groups with features
- /admin tasks - List all scheduled tasks with status
- /admin help - Show available commands

Features:
- Commands only work in main group for security
- Rich formatted output with emojis
- Shows group feature indicators (search, custom prompt)
Peyton-Spencer referenced this pull request in omniaura/nanoclaw Feb 11, 2026
Add Slack as a secondary channel using Socket Mode (WebSocket, no public
URL). Mirrors the Discord pattern: workspace-level shared context,
JID-based routing, image attachments, share_request tool integration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
gavrielc added a commit that referenced this pull request Feb 17, 2026
…ting

Code fix:
- migrate.ts: migrateExisting() now calls recordCustomModification()
  to register the migration patch in state.yaml (was writing patch to
  disk but never recording it in state tracking). Also switched from
  shell-interpolated diff to execFileSync for path safety.

Doc updates to resolve 11 inconsistencies between architecture docs
and v0.1 implementation:
- #7: Base is now documented as updating after every skill apply
  (accumulated-state model), not only during core updates
- #1: State example uses name: (matching AppliedSkill type), not skill:
- #2: file_hashes documented as flat single-hash, with three-part
  (base/skill/merged) noted as future
- #3-5: Missing fields (installed_at, path_remap, author, license,
  tested_with, post_apply, etc.) documented as planned for future
- #9: Manifest example updated to use core_version: 0.1.0
- #11: Execution order updated to match actual implementation
  (backup, lock, base update, test rollback steps)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
mehdimashayekhi added a commit to mehdimashayekhi/nanoclaw that referenced this pull request Feb 21, 2026
P0 #1 - Cursor Safety (CRITICAL):
- Move cursor advance to INSIDE handleClearCommand on success path only
- Pass clearCommand timestamp to handleClearCommand
- Advance cursor in empty message case to prevent infinite reprocessing
- On error, cursor stays at old position → /clear can be retried
- Prevents permanent message loss if API call fails

P0 qwibitai#3 - Token Limit Protection:
- Add progressive truncation: start with 500 messages, reduce by 25% if > 150k chars
- Hard cap at 150k characters (~37.5k tokens, well under 200k limit)
- Prevents API errors from oversized context
- Logs actual character count and message count used

P0 qwibitai#4 - Permission Control (SECURITY):
- Add is_from_me check before executing /clear
- Only bot owner can clear conversations
- Prevents malicious group members from wiping history
- Returns clear error message to unauthorized users

All fixes prevent production failures and security vulnerabilities.
tunmaker pushed a commit to tunmaker/nanoclaw that referenced this pull request Feb 24, 2026
…Ni9l4

Secure IPC with per-group namespaces to prevent privilege escalation
blaykeelder1-commits pushed a commit to blaykeelder1-commits/nanoclaw that referenced this pull request Feb 25, 2026
- Fix IDLE_TIMEOUT default from 30min to 5min (was same as CONTAINER_TIMEOUT,
  causing containers to always be hard-killed instead of graceful shutdown)
- Fix message cursor: defer lastAgentTimestamp advancement until agent
  succeeds, preventing permanent message loss on timeout
- Add webhook rate limiting (30 req/min/IP)
- Add webhook signature verification (HMAC-SHA256 via openphone-signature)
- Add Zod schema validation for webhook payloads
- Add 1MB body size limit on webhook requests
- Add nginx reverse proxy config with TLS, rate limiting, security headers
- Add fail2ban filter/jail for webhook abuse detection
- Add structured audit logging for security events
- Update setup-vps.sh: nginx/certbot install, close port 3100 externally
- Document secret rotation procedure and webhook security in SECURITY.md
- Mark bugs #2 and qwibitai#3 as FIXED in DEBUG_CHECKLIST.md

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
disruptDevWS added a commit to disruptDevWS/forge-os-pipeline that referenced this pull request Feb 26, 2026
…tecture dir

Bug qwibitai#2 — parseArchitectureBlueprint() now derives silo names from
"### Silo N:" headings, skips non-silo tables (Parts 2-4), prioritizes
URL column over Page column, and deduplicates by slug. Fixes 61
duplicates in "Uncategorized" → 22 pages across 5 named silos.

Bug qwibitai#3 — syncDwight() now checks architecture/ directory as fallback
for semantically_similar_report.csv when auditor/ report is empty.
Fixes semantic conflicts showing 0 despite data existing.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
asantopietro pushed a commit to asantopietro/nanoclaw that referenced this pull request Mar 1, 2026
Closes qwibitai#3

Updates both workflow `branches` filters from `main` to `k8s/main` so CI runs on PRs targeting the correct base branch.

Co-authored-by: NanoClaw Agent <nanoclaw-bot@gitea.cluster.lab1.lan>
Reviewed-on: https://gitea.cluster.lab1.lan/asantopietro/nanoclaw/pulls/11
Co-authored-by: nanoclaw-bot <nanoclaw@nowhere.net>
Co-committed-by: nanoclaw-bot <nanoclaw@nowhere.net>
mitzimare referenced this pull request in Bootjack/nanoclaw Mar 1, 2026
Implements polling-based auto-deployment that detects changes to the main
branch and automatically deploys them to the host system.

Features:
- Polls origin/main every 60 seconds (configurable) for new commits
- Executes full deployment: pull, install deps, build, restart service
- Sends real-time notifications to main chat about deployment progress
- Handles uncommitted changes by stashing them
- Verifies service is running after deployment
- Comprehensive error handling and notifications

Configuration:
- AUTO_DEPLOY_ENABLED (default: true)
- AUTO_DEPLOY_POLL_INTERVAL (default: 60000ms)

Changes:
- src/auto-deploy.ts: Core deployment logic and polling loop
- src/index.ts: Wire up auto-deploy on startup
- src/config.ts: Add auto-deploy config, export PROJECT_ROOT and HOME_DIR
- docs/AUTO_DEPLOYMENT.md: Comprehensive documentation

This will enable PR #2 to deploy automatically once PR #3 is merged.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
danielmrdev pushed a commit to danielmrdev/nanoclaw that referenced this pull request Mar 3, 2026
- always use dtasks list qwibitai#3 Trabajo
- YAML frontmatter in notes field with project/priority/type
- example command, field reference table, and strip guidance
cingram referenced this pull request in cingram/cambot-agent Mar 7, 2026
…ages

Scans email (and other untrusted channel) content for prompt injection
patterns using cambot-core's regex detector. When detected, logs full
forensic details and wraps content in an isolation envelope warning the
agent not to follow embedded instructions. Never blocks — defense in depth.

Wired as middleware #3 in the bus pipeline (after dedup, before outbound
guard). 51 tests covering safe emails, injection attacks, bypass techniques,
and false positive avoidance from the content-pipe playground scenarios.

Also removes dead RedactionResult import from lifecycle-interceptor.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
dptts added a commit to dptts/nanoclaw that referenced this pull request Mar 7, 2026
Implements batching of rapid-fire Forgejo webhook notifications to prevent
duplicate agent invocations and wasted API usage. When multiple notifications
arrive in quick succession (e.g., merging multiple PRs), they are now batched
and sent as a single combined message.

Features:
- Per-group batching queues with configurable timeout (5s default)
- Size-based flush (immediate delivery at 5 notifications)
- Timer-based debouncing (resets on each new notification)
- Graceful shutdown (flushes all pending batches on SIGINT/SIGTERM)
- Configurable via environment variables (can be disabled if needed)

Implementation:
- New BatchManager class in src/webhooks/batch-manager.ts
- Integration in src/index.ts webhook callback
- Configuration in src/config.ts (WEBHOOK_BATCH_*)

Batched messages are separated with "---" divider for visual clarity.

Addresses issue qwibitai#3: https://forgejo.bigpoe.lan/danny/nanoclaw/issues/3

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
5queezer added a commit to 5queezer/nanoclaw that referenced this pull request Mar 14, 2026
- migrate-memories.mjs: pass apiKey for LanceDB Cloud URIs (medium #1)
- Throw on old schema without scope column instead of silent warn (medium #2)
- Log hint when rerank API key is present but RERANK_PROVIDER unset (medium qwibitai#3)
- Validate vectorDim early for custom providers (low qwibitai#4)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
akasha-scheuermann pushed a commit to rscheuermann/nanoclaw that referenced this pull request Mar 14, 2026
…Ni9l4

Secure IPC with per-group namespaces to prevent privilege escalation
bebekim referenced this pull request in bebekim/goodclaw Mar 14, 2026
Secure IPC with per-group namespaces to prevent privilege escalation
Jeffrey-Keyser referenced this pull request in Jeffrey-Keyser/nanoclaw Mar 15, 2026
Channel onMessage callbacks now trigger agent dispatch immediately
after persisting to SQLite, eliminating the 2-second POLL_INTERVAL
latency. The startMessageLoop polling function is removed entirely.
Recovery of pending messages at startup is preserved.

Closes #3

Co-Authored-By: Claude <noreply@anthropic.com>
Jeffrey-Keyser referenced this pull request in Jeffrey-Keyser/nanoclaw Mar 22, 2026
Resolves conflict between agency-hq-dispatcher split (#2/#3) and
exponential backoff (#8). Ports dispatchSkipTicks and backoff logic
into dispatch-loop.ts, updates dispatchTask to return boolean for
failure tracking, and clears backoff state on success/blocked/stop.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Quirds pushed a commit to thankyourobot/tyr-aios that referenced this pull request Mar 24, 2026
…ge to both files

onboarding-patterns.md:
- Reorder pillars: Workspace Orientation moves from qwibitai#5 to qwibitai#3, before Access and Rhythms
- Add sequencing rationale at top of Five Pillars section
- Add operational notes nudge to Completing Onboarding

gap-analysis.md:
- Add operational notes nudge to Relationship to Onboarding: agent should write
  a brief ops note in projects/gap-analysis/ before closing onboarding so future
  sessions don't need to re-read the reference file

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
bryantb2 referenced this pull request in bryantb2/nanoclaw Mar 28, 2026
Nightly review proposals #1, #2, #3 — applied from fleet-ops analysis:

- Subagent Selection table: REQUIRED mapping of task types to specialist
  subagents. general-purpose reserved for uncategorized work only.
- Agent Teams REQUIRED criteria: auto-parallel for 2+ independent tasks,
  3+ unrelated modules, or explicit user request. Sequential execution
  when criteria are met is a process violation.
- QA Review Policy: mandatory completion gate with exact 4-step sequence.
  No exceptions, even for simple changes.

Co-Authored-By: Agent Fleet <fleet@krewtrack.com>
nightcrawlerxme added a commit to nightcrawlerxme/nanoclaw that referenced this pull request Mar 30, 2026
feat: upstream PR integrations + autonomous intelligence (webhook, Outlook, Google Workspace, skills marketplace)
luisherranz pushed a commit to luisherranz/nanoclaw that referenced this pull request Mar 31, 2026
Critical bugs:
- Bug qwibitai#4: Remove sequence from content hash to prevent duplicates on
  repeated PreCompact calls. Hash is now sha256(session_id:role:content).
- Bug qwibitai#5: storeMessages() now returns count of newly inserted messages.
  PreCompact only creates leaf summaries for newly inserted messages,
  preventing re-summarization of already-stored content.

Should-fix:
- #1/qwibitai#10: Add dbInitialized flag to skip redundant schema setup on
  repeated initLcmDatabase() calls (fast path for MCP tool calls).
- qwibitai#6: Depth-capped condensation now attempts API summarization first,
  falls back to truncated concatenation with 10K token cap instead of
  unbounded blob.
- qwibitai#7: Skip API call entirely when neither ANTHROPIC_API_KEY nor
  ANTHROPIC_AUTH_TOKEN is set, go straight to deterministic fallback.

Nice-to-have:
- qwibitai#3: Remove duplicate LcmMessage/LcmSummary from src/types.ts.
  Single source of truth is container/agent-runner/src/lcm-store.ts.
@Nate-Vish Nate-Vish mentioned this pull request Mar 31, 2026
5 tasks
morrowgarrett added a commit to morrowgarrett/nanoclaw that referenced this pull request Apr 1, 2026
#1 AbortController idle timeout (PR qwibitai#1572):
- Aborts hung SDK queries after 5min of no messages
- Configurable via QUERY_IDLE_TIMEOUT env var
- Container exits with error for host retry

qwibitai#2 Session JSONL rotation (PR qwibitai#700):
- Rotates session files exceeding 5MB
- Prevents container timeouts from session bloat
- Auto-creates fresh session on rotation

qwibitai#3 Per-group .mcp.json config (PR qwibitai#1515):
- Groups can define MCP servers in .mcp.json
- Servers auto-discovered and tools auto-allowed
- No code changes needed to add group-specific MCP

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
morrowgarrett added a commit to morrowgarrett/nanoclaw that referenced this pull request Apr 2, 2026
All 7 container features re-applied after confirming the earlier hang
was caused by API rate limiting, not code issues. SDK v0.2.76 confirmed
to support abortController.

#1  AbortController idle timeout (5min, configurable)
qwibitai#3  Per-group .mcp.json config (auto-discovered servers + tools)
qwibitai#6  Frozen memU memory snapshot (query once at start, hybrid RAG)
qwibitai#11 Skill-as-markdown auto-loading from /workspace/group/skills/
qwibitai#12 Structured compaction summary (last-compaction-summary.md)
qwibitai#13 Peer channel MCP tools (peer_send, peer_status via SSH)
qwibitai#14 Recall MCP tool (FTS5 cross-session message search)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
gkarolyi pushed a commit to gkarolyi/nanoclaw that referenced this pull request Apr 2, 2026
Quirds added a commit to thankyourobot/tyr-aios that referenced this pull request Apr 8, 2026
Adversarial review surfaced 10+ issues with the junction table migration
and maintenance features. Resolved the ones that matter most for
pre-production deploy:

Schema cleanup:
- Collapsed all 7 LCM migrations into base schema (DBs will be wiped
  before production, no upgrade path needed)
- Dropped dead JSON columns (source_message_ids, parent_summary_ids,
  child_summary_ids) that were write-only after junction table refactor
- Removed legacy session_id→conversation_id rename
- Removed lcm_schema_version and migration framework entirely

API cleanup:
- StoreSummaryInput now takes sourceMessageIds/childSummaryIds as arrays
  (was: JSON-stringified strings)
- Removed silent try/catch on JSON parse failures
- Removed the range-based fallback in lcm-subagent read_source
  (junction tables are authoritative)
- Renamed getCoveredLeafIds → getCoveredSummaryIds (name was a lie:
  returned any covered summary, not just leaves)

Dead code removal:
- Deleted lcm-transcript-repair.ts entirely (was wired at wrong point
  in architecture: applied to stored messages, but our pipeline never
  re-sends those to an API, so it was fixing a problem we don't have)
- Removed unused repairToolPairing import in lcm-helpers.ts

Safety & correctness:
- Pruning safety floors: minRetainedConversations (default 1) and
  maxDeleteFraction (default 0.5), with force=true override
- Integrity check qwibitai#3 (leaf lineage) bumped from warning to error
  since getMessagesForSummary has no fallback path
- Integrity check qwibitai#4 (condensed lineage) same treatment
- Integrity check qwibitai#5 (orphans) rewrote N+1 query loop as a single
  JOIN query using the junction table index

DR script (aios-infra):
- Extended dr-test.sh with LCM integrity checks: summarization stall
  detection, orphan leaf/condensed summary detection, schema verification

125 tests passing, tsc clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
luisherranz pushed a commit to luisherranz/nanoclaw that referenced this pull request Apr 10, 2026
Critical bugs:
- Bug qwibitai#4: Remove sequence from content hash to prevent duplicates on
  repeated PreCompact calls. Hash is now sha256(session_id:role:content).
- Bug qwibitai#5: storeMessages() now returns count of newly inserted messages.
  PreCompact only creates leaf summaries for newly inserted messages,
  preventing re-summarization of already-stored content.

Should-fix:
- #1/qwibitai#10: Add dbInitialized flag to skip redundant schema setup on
  repeated initLcmDatabase() calls (fast path for MCP tool calls).
- qwibitai#6: Depth-capped condensation now attempts API summarization first,
  falls back to truncated concatenation with 10K token cap instead of
  unbounded blob.
- qwibitai#7: Skip API call entirely when neither ANTHROPIC_API_KEY nor
  ANTHROPIC_AUTH_TOKEN is set, go straight to deterministic fallback.

Nice-to-have:
- qwibitai#3: Remove duplicate LcmMessage/LcmSummary from src/types.ts.
  Single source of truth is container/agent-runner/src/lcm-store.ts.
foxsky added a commit to foxsky/nanoclaw that referenced this pull request Apr 12, 2026
The 11 rows previously classified as docs-describe-missing were
semantically misclassified due to a decision-table rule gap:
rule qwibitai#3 assumes total=0 means "not shipped", but for these rows
total=0 actually means either (a) shipped in code but zero prod
usage, (b) presence/state rule that produces no events (Phase 2
probe was the wrong tool), or (c) ambiguous between dormant and
broken attachment logging.

Reclassified:
- R018, R019, R027, R032, R033, R041 -> stale-in-prod
  (shipped, documented, zero prod usage; docs retained)
- R043, R055 -> in-sync
  (state/read-path behaviors, probe was wrong tool)
- R062, R063, R064 -> stale-in-prod with rule-gap note
  (attachment path; cannot distinguish dormant from broken)

Each reclassified row has explicit Notes explaining the rationale.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
dm-j pushed a commit to dm-j/nanoclaw that referenced this pull request Apr 13, 2026
…Ni9l4

Secure IPC with per-group namespaces to prevent privilege escalation
johnhojohn969 pushed a commit to johnhojohn969/nanoclaw that referenced this pull request Apr 14, 2026
Risk/execution overhaul — makes the bot safe to run on real money and
replaces per-coin tuning with a universal volatility-normalized formula.

Fix qwibitai#3 — Exchange-side SL/TP (real-money safety net):
- Entry market orders now include attachAlgoOrds with ATR-derived
  slTriggerPx + tpTriggerPx, so positions are protected on the exchange
  even if the bot goes offline between cron cycles.
- Main bot: new syncExchangeSl() amends the live conditional algo
  (cancel-and-recreate fallback via orders-algo-pending) whenever the
  local trailing-SL tier advances, keeping exchange SL in lockstep.
- Store slAlgoClOrdId + currentExchangeSlPrice in state.openData.

Fix qwibitai#4 — Session rules actually enforced:
- New getCurrentSession() (UTC: asian<8, london<13, ny).
- Entry logic now applies session_rules[session].max_leverage and
  size_multiplier instead of only passing them to Claude for logging.

Fix #5a — OI divergence with real previous OI:
- OKX has no public per-instrument historical OI endpoint, so roll a
  state.oiHistory cache: pushOiSample() writes current OI each cycle,
  pickOiPrev() returns the oldest sample inside a 2–8h window.
- analyzeMarket() signature extended with oiPrev; both call sites
  (hold loop + scan loop) pass it through.
- Kills the `analyzeOIDivergence(oiCurrent, oiCurrent, ...)` no-op that
  silently disabled 4 OI signal weights.

Fix #5b — Funding-rate trap F&G fusion:
- analyzeFundingTrap() now receives the real fg object instead of
  hardcoded {value: 50}; `combined_with_fear/greed` flags finally fire.

Fix qwibitai#6 — Risk dialed down:
- risk_per_trade_main: 0.08 → 0.01 (8x reduction; 1% per trade)
- hard_limits.max_risk_per_trade: 0.08 → 0.02 (ceiling for selfEvolve)
- max_positions_main: 2 → 4 (room for ETH/SOL/XRP/DOGE/SUI scan)
- max_drawdown_main: 0.20 → 0.15 (tighter DD circuit-breaker)
- Added risk_per_trade_lab 0.005, max_positions_lab 4, max_leverage_lab 5
- instruments[] now matches WATCHLIST (ETH/SOL/XRP/DOGE/SUI)
- Params version bump 0 → 1 with update_reason=atr_universal_fix_v1

Universal per-instrument formula (replaces hardcoded per-coin tuning):
- New atr(rawCandles, 14) helper computes True Range on 1H candles.
- New getInstrumentProfile() returns {atr, atrPct, sizeMult, maxLev,
  k_sl=1.5, k_tp=3.0}. sizeMult is log-normalized from 24h USD volume
  ($10M→0.4, $1B→1.0). maxLev is volatility-capped: ~0.12/atrPct.
- analyzeMarket() now computes and returns the profile per instrument.
- Entry sizing replaces equity*risk*lev*sizeM/ctUsdVal with:
    riskUsd  = equity × risk% × session × liquidity × signal
    notional = riskUsd × (price / (k_sl × ATR))
    sz       = notional / ctUsdVal
  So SUI/DOGE get smaller positions automatically (higher ATR%) while
  keeping the same USD risk as ETH. No per-coin tuning required.
- Initial SL/TP prices derive from ATR: SL = entry ± 1.5×ATR, TP =
  entry ± 3.0×ATR (1:2 R:R), passed both to attachAlgoOrds and stored
  in state.openData for the tier-ladder override below.

Trailing-SL ladder (main bot):
- At t0 (hwm below t1 threshold), prefer the stored ATR-derived
  atrSlUplRatio over the fixed -7% margin-% default, so the initial
  stop scales with the coin's natural volatility.
- Tiers t1..t5 unchanged; still drive exchange-SL sync on advance.

Lab bot (okx-trader-lab.js):
- Same helpers/fixes (ATR, profile, session rules, OI cache, FR fix,
  attachAlgoOrds at entry).
- Skips exchange-side SL tier sync because lab's pnlPct is
  equity-scale rather than uplRatio-scale — initial attach SL/TP
  still provides the safety net.
johnhojohn969 pushed a commit to johnhojohn969/nanoclaw that referenced this pull request Apr 14, 2026
Closes the short-term reactivity gap left by fix qwibitai#3. Fix qwibitai#3 protected
the downside (exchange-side hard SL/TP) but trailing-ladder advancement
and new-signal detection were still gated by the 30-min cron. Now:

A. OKX native trailing stop (move_order_stop)
  - New placeTrailingStop() helper in both main and lab. After the
    market entry fills, posts a server-side trailing algo with:
      - callbackRatio  = max(0.006, 0.8 × atrPct)   (main)
                       = max(0.005, 0.6 × atrPct)   (lab — tighter)
      - activePx       = entry ± 0.5 × ATR          (main)
                       = entry ± 0.3 × ATR          (lab)
      - reduceOnly, posSide-aware, algoClOrdId deterministic
  - Runs on OKX matching engine at tick speed, so profit-locking
    trails between cron cycles without the bot doing anything. This
    eliminates the "hwm swings inside a cycle" hole in the tier ladder.
  - Coexists with the conditional hard SL (attachAlgoOrds from fix qwibitai#3)
    — hard SL is the never-worse-than floor; trailing stop takes over
    once activePx is hit. Whichever fires first closes the position.
  - Stores trailAlgoClOrdId / trailCallbackRatio / trailActivePx in
    state.openData[instId] for future amendment or diagnostics.
  - Open notifications now include "Trail:X%@$Y" line.

B. 5-minute cron cadence (README.txt)
  - Main:  */5   (every 5 min)
  - Lab:   2-59/5 (offset 2 min from main to reduce race on params.json)
  - 6x faster scan→entry reaction for short-term signals.
  - API load stays well inside OKX rate limits (≈40 calls/cycle × 12
    cycles/hr = 480 public calls/hr vs 20 req/2s ceiling).

C. Report throttling — avoid spamming Telegram every 5 min
  - New state.lastFullReportTs + state.lastPosCount
  - Full HTML report sent when ANY of:
      1. ≥25 min since last full report (baseline ~30-min cadence)
      2. Any critical alert this cycle
      3. Self-evolve bumped params.version
      4. Position count changed (open/close)
  - Otherwise prints a "[REPORT] Throttled — next full report in Xm"
    console line and skips the Telegram send.
  - Per-cycle OPEN/CLOSE/DRAWDOWN/AUDIT notifications are untouched;
    only the periodic monitor report is throttled.
  - Lab bot doesn't send a periodic report so no throttling needed
    there; event notifications still fire on every cycle.

After this commit, reaction matrix becomes:
  exit on SL/TP:         <1s (exchange conditional)    ← fix qwibitai#3
  exit on trailing:      <1s (exchange move_order_stop) ← this commit
  new signal → entry:    up to 5 min (was 30)          ← this commit
  alert on critical:     up to 5 min (was 30)          ← this commit
  periodic dashboard:    ~25 min (throttled)           ← this commit
gavrielc added a commit that referenced this pull request Apr 18, 2026
Additive change — existing code paths still run via inline fallbacks.
Prepares core for per-module extractions in PR #3 onward.

Four registries added with empty defaults:
  - delivery action handlers (delivery.ts)
  - router inbound gate (router.ts)
  - response dispatcher (index.ts)
  - MCP tool self-registration (container/agent-runner/src/mcp-tools/server.ts)

Default modules moved to src/modules/ for signaling:
  - src/modules/typing/       (extracted from delivery.ts)
  - src/modules/mount-security/ (moved from src/mount-security.ts)

Both are imported directly by core — no hook, no registry. Removal
requires editing core imports.

Migrator now keys applied rows by name (uniqueness) so module
migrations can pick arbitrary version numbers. Stored version column
is auto-assigned as an applied-order sequence.

sqlite_master guards added around core calls into module-owned tables
(user_roles, agent_destinations, pending_questions). No-ops today;
load-bearing after the owning modules are extracted.

MODULE-HOOK markers placed at scheduling's two skill-edit sites
(host-sweep.ts recurrence call, poll-loop.ts pre-task gate). PR #4
replaces the marked blocks when scheduling moves to its module.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
gavrielc added a commit that referenced this pull request Apr 18, 2026
…modules

Phase 2 / PR #3 of the module refactor. Moves the approval and interactive-
question flows out of core and into src/modules/, wired through the response
dispatcher and delivery action registries.

New modules:
- src/modules/interactive/ — registers a response handler that claims
  pending_questions rows, writes question_response to the session DB, wakes
  the container. createPendingQuestion call stays inline in delivery.ts
  (guarded by hasTable) per plan.
- src/modules/approvals/ — registers 3 delivery actions (install_packages,
  request_rebuild, add_mcp_server), a response handler for pending_approvals
  (including OneCLI action fall-through), an adapter-ready hook that boots
  the OneCLI manual-approval handler, and a shutdown hook that stops it.
  OneCLI implementation (src/onecli-approvals.ts) moves into the module.

Core lifecycle hooks added (narrow, not registries):
- onDeliveryAdapterReady(cb) in delivery.ts — fires when setDeliveryAdapter
  runs (or immediately if already set). Used by approvals for OneCLI boot.
- onShutdown(cb) in index.ts — fires on SIGTERM/SIGINT. Used by approvals
  for OneCLI teardown.
- getDeliveryAdapter() getter in delivery.ts — for live-flow adapter access
  in registered delivery actions.

Core shrinks: delivery.ts 911 → 665 lines, index.ts 405 → 224 lines.
dispatchResponse now logs "Unclaimed response" instead of falling through
to an inline handler — the inline fallback moved into the two modules.

Migration files renamed to the module-<name>-<short>.ts convention:
- 003-pending-approvals.ts → module-approvals-pending-approvals.ts
- 007-pending-approvals-title-options.ts → module-approvals-title-options.ts
Migration.name fields unchanged so existing DBs treat them as already-applied.

Degradation verified: emptying the modules barrel builds clean and 137/137
tests pass. Actions would log "Unknown system action"; button clicks would
log "Unclaimed response".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
gavrielc added a commit that referenced this pull request Apr 18, 2026
Phase 1 boundary sync (5454bae) inadvertently re-applied v2's channel-
adapter deletions (v2 commit 437ba63 "move channel adapters off v2
trunk") to the channels branch. 17 adapter files and their package.json
deps were wiped:

- discord, gchat, github, imessage, linear, matrix, resend, slack,
  teams, telegram + telegram-markdown-sanitize + telegram-pairing,
  webex, whatsapp, whatsapp-cloud
- @chat-adapter/* packages, @whiskeysockets/baileys, @resend/...,
  qrcode, pino, chat-adapter-imessage, @beeper/...

Caught when testing PR #3 — the service had no channels to bind to.

Root cause: the sync merge commit message ("No channel adapter changes
required") was wrong. I checked the registry surface but not file
presence. Providers had the same failure mode during its sync, but
there it surfaced immediately via a test import; channels has no test
that imports adapter files directly, so it slipped through.

Fix: restore src/channels/*.ts and the matching package.json /
pnpm-lock.yaml entries from 0d75ca2 (last pre-sync commit). Tests pass
(198/198 vs 137/137 pre-restore — the restored telegram-pairing and
markdown-sanitize tests are back).

Going forward: channel/provider branches that carry files v2 has
deleted need `git checkout origin/<branch> -- <paths>` applied after
any v2 sync merge that touches those paths, or a merge strategy that
ignores deletions under the branch-owned directory.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
gavrielc added a commit that referenced this pull request Apr 18, 2026
PR #3 introduced a circular-import temporal-dead-zone bug that didn't
surface in unit tests but crashed the service at startup:

  src/index.ts imports './modules/index.js' for side effects
  → src/modules/interactive/index.ts calls registerResponseHandler()
  → that function is declared in src/index.ts
  → but src/index.ts's const responseHandlers = [] hasn't been
    initialized yet (we're in the middle of its module-init)
  → ReferenceError: Cannot access 'responseHandlers' before initialization

Same issue for registerResponseHandler itself (the function reference
resolves to undefined) and for onShutdown in the approvals module.

Caught when the operator started the service and systemd flagged the
process as crashing in auto-restart loop.

Fix: extract responseHandlers + registerResponseHandler + shutdownCallbacks
+ onShutdown into src/response-registry.ts, which has no dependencies on
src/index.ts or on modules. index.ts re-exports the same surface for any
existing consumers; modules import directly from response-registry.js.

The bug was latent because:
- Unit tests import pieces, never src/index.ts's main() flow.
- Host builds clean because TypeScript doesn't catch runtime circular
  init order.
- Only surfaces when the ES module loader actually executes src/index.ts
  as the entry point.

Verified: service boots on Linux host with approvals + interactive
loaded; OneCLI handler starts via onDeliveryAdapterReady callback.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
carstenf pushed a commit to carstenf/nanoclaw that referenced this pull request Apr 21, 2026
…1 to gpt-4o-mini-transcribe

- SESSION_CONFIG.audio.input.transcription.model: 'whisper-1' → 'gpt-4o-mini-transcribe'
- language='de' pin preserved (from 4db252c)
- Rationale: whisper-1 at 8kHz telephony produced garbled German even with language pinned (DEFECTS §3: "Hallo Restaurant Bellavista" → "Jan-Uwe das war es von Bellevista"); gpt-4o-mini-transcribe has documented FLEURS WER improvement on short German utterances
- Drop-in compat: only `.completed` transcription events are consumed (src/sideband.ts:330-340, src/amd-classifier.ts:213-221); `.delta` is unsubscribed (guard test in tests/sideband.test.ts:208 pins the ignore-behavior)
- New tests/config.test.ts regression guard: asserts model='gpt-4o-mini-transcribe' AND language='de'
- Cost-cap Pitfall 3 documented adjacent to config line (CAP_PER_CALL_EUR=€1.00 in src/cost/gate.ts; verify in 05.1-05 live test)
- Unblocks C2-07 (AMD verdict reliability) and QUAL-01 (live PSTN test verification)
- Full voice-bridge suite: 362 passed / 4 skipped / 0 failed; tsc clean

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
carstenf pushed a commit to carstenf/nanoclaw that referenced this pull request Apr 21, 2026
- Provides: gpt-4o-mini-transcribe as Realtime ASR model + regression test
- Defects closed: qwibitai#3 (implementation layer; live-verify gate is 05.1-05)
- Affects: 05.1-03 (AMD transcript-cue path), 05.1-05 (live verification), Phase 4 cost caps (Pitfall 3 documented inline)
- Self-check: PASSED
- 362 voice-bridge tests passing, tsc clean

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This was referenced Apr 23, 2026
carstenf pushed a commit to carstenf/nanoclaw that referenced this pull request Apr 24, 2026
- 7/8 PASS: qwibitai#2 setTimeout, qwibitai#3 idle_timeout_ms, qwibitai#4 CASE6B_PERSONA gone, qwibitai#5 tsc strict, qwibitai#6 Plan-XX refs (13 ≤ 30), qwibitai#7 suite green + D-6 byte-identical, qwibitai#8 finding file
- 1 PARTIAL: #1 LOC delta — CONTEXT baseline 7021 measure shows -274 (LOC INCREASED), but git pre-plan baseline (7529) shows +234 reduction (78% of 300 target). CONTEXT baseline was captured pre-Phase-05.2-final-merge; cross-check is the honest measurement.
- D-6 evidence: accept.test.ts:285-311 byte-identical pre/post phase
- §201 invariant tests green (audio-guard + ghost-scan + amd-classifier 3/3 files / 25 tests)
- Plan 05.2-03 D-8 invariant test green (sideband-wait-for-speech 4/4)
- silence-monitor.ts: 227 LOC VAD ladder → 49 LOC hard-safety stub (-176 LOC, biggest delta)
- persona.ts: -86 LOC (CASE6B_PERSONA deleted, dead exports retired)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
carstenf pushed a commit to carstenf/nanoclaw that referenced this pull request Apr 25, 2026
…4 warnings

Plan-checker revision round 2 fixes for Phase 05.6:

BLOCKER #1 — REQ-DIR-17 real NanoClaw-side gateway (Plan 06-01):
- Added Task 4 to Plan 06-01: ships src/voice-mid-call-gateway.ts +
  src/voice-mid-call-gateway.test.ts. Module exports checkMidCallMutation,
  registerActiveCall, deregisterActiveCall, isCallActive. Active-call
  set lifecycle bound to voice_triggers_init (register on entry) and
  voice-finalize-call-cost (deregister on completion).
- Modified ToolRegistry in src/mcp-tools/index.ts to be metadata-aware:
  register(name, handler, meta) accepts { mutating: true } and the
  invoke() dispatch path calls checkMidCallMutation BEFORE the handler
  runs. Mutating tools registered with { mutating: true } at registration
  time. 11 mutating tools enumerated.
- Updated must_haves.truths in Plan 06-01 to reflect 3-tier defense
  (agent prompt + dispatch gateway + handler-boundary sentinel) and the
  active-call set lifecycle.
- Updated success_criteria + frontmatter (files_modified, artifacts,
  key_links) to add the new gateway module + its integration points.

BLOCKER qwibitai#2 — FAIL-recovery wording (Plan 06-02 + 06-03):
- Plan 06-02 <objective> now contains an explicit FAIL-recovery policy:
  diagnose, land fix in separate plan/hot-patch (NOT in 05.6 plans),
  re-run synthetic smoke, re-execute failed step from beginning,
  three-strike escalation to ASK FOR CHAT. Policy applied to Task 2
  (synth FAIL), Task 4 (inbound FAIL), Task 6 (outbound FAIL). §201
  BREACH does NOT follow generic recovery — audit-level investigation
  required.
- Plan 06-03 Task 3 already had `git revert HEAD` recovery; now also
  notes the runtime-ENV revert window REOPENS after revert.

WARNING qwibitai#3 — Runtime-revert truth qualification (Plan 06-03):
- must_haves.truth qualified to "Step 1→Step 2 ONLY; after Step 2 the
  emergency revert path becomes `git revert <Step-2-cleanup-SHA>` per
  D-30." Same qualification added to <objective>, the Step 1 commit
  message, the Step 2 commit message, success_criteria, and the
  briefing template.

WARNING qwibitai#4 — Wrong WireGuard IP (Plan 06-02 + 06-03):
- Replaced hardcoded http://10.0.0.2:3201/ with http://127.0.0.1:3201/
  in: Plan 06-02 Task 1 step 2 (.env append + curl /health verification);
  Plan 06-03 Task 2 step 7 (.env.example update); the briefing template
  in Plan 06-03 Task 5; verification + acceptance_criteria across both
  plans. NanoClaw + voice-bridge are co-located on Lenovo1 per
  /opt/server-docs/MASTER.md + project_nanoclaw_infra memory — local
  loopback. 10.0.0.x is the WireGuard subnet, not a NanoClaw transport
  address. Both plans now also instruct: if container deploy changes
  the host, ASK Carsten for the lenovo1-internal address — do NOT
  guess; do NOT use 10.0.0.x.

WARNING qwibitai#5 — §201 audio-leak jq query (Plan 06-02):
- Aligned the jq selector with tracing-contract.md: contract specifies
  `delta` is STRIPPED and replaced with `delta_bytes` integer. Task 4
  step 4 now (a) verifies every response.audio.delta event has
  delta_bytes integer (redaction integrity), AND (b) asserts no
  response.audio.delta event retains a non-empty .delta payload (BREACH
  on any leak). Same query applied in Task 6 step 3 for the outbound
  trace.

WARNING qwibitai#6 — Du/Sie negative check missing (Plan 06-02):
- Task 4 step 6 (inbound, Du-axis) and Task 6 step 3.d (outbound,
  Sie-axis) now BOTH run a negative check: PLACEHOLDER_LEAK=$(jq -r
  '...instructions...' | grep -c '{{[a-z_]\+}}'); test
  "$PLACEHOLDER_LEAK" -eq 0 — BREACH on any unsubstituted {{...}}
  token. Positive Du/Sie token check stays as before; negative
  placeholder-leak check added on top.

Files modified:
- .planning/phases/05.6-container-agent-integration-cutover/05.6-01-PLAN.md
- .planning/phases/05.6-container-agent-integration-cutover/05.6-02-PLAN.md
- .planning/phases/05.6-container-agent-integration-cutover/05.6-03-PLAN.md

Phase scope unchanged — fixes are corrective, not additive scope. The
new src/voice-mid-call-gateway.ts file is NEW SOURCE CODE that the
executor (later /gsd-execute-phase) writes; the planner only updates
the PLAN.md task spec.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
charlie17 added a commit to charlie17/nanoclaw that referenced this pull request Apr 26, 2026
…ded claude-usage Chart.js

Bug surface during D6 browser smoke (post-fold-qwibitai#2 SPA fetch-path patch): dashboard
data loaded successfully (model pills populated, "Updated" timestamp set), but all
chart canvases rendered blank. Cause: Bridge's CSP at web.ts:64 had
`script-src 'self' 'unsafe-inline'` — no allowance for `https://cdn.jsdelivr.net`.
claude-usage's SPA loads Chart.js from that CDN; browser blocks the load on CSP
violation; canvases never paint despite valid /api/data response.

Fix: amend script-src to include `https://cdn.jsdelivr.net`. Minimal-blast-radius
change — only allows the specific CDN domain claude-usage uses, no broader
relaxation. CSP nonce hardening (BRIDGE-BUILD-SPEC §12.1 deferred-features) remains
a future cleanup; this is the same `unsafe-inline` posture, just with one more
script-src entry.
manarde added a commit to manarde/nanoclaw that referenced this pull request Apr 27, 2026
…ew items qwibitai#2 + qwibitai#3 — P1)

These two fixes both touch the host_mcp_query spawn flow and naturally
collapse into one structural change.

qwibitai#2: child.on('error') previously unlinked the request file and wrote a
decline reply but did NOT clear softTimer/killTimer or remove the entry
from hostMcpActiveChildren. Per Node semantics 'exit' may not fire after
'error', so the exit-handler cleanup might never run — leading to a
spurious "timed out" reply 120s after the original error AND a permanent
slot leak in the concurrency map (after 4 spawn errors the cap is
exhausted, DoS).

qwibitai#3: hostMcpLastRun was stamped inside child.on('spawn'), which is async.
The synchronous debounce check in processTaskIpc therefore returned
before the stamp landed. With the IPC watcher serializing tasks, two
same-{group,scope} task files in one poll cycle BOTH passed debounce —
debounce was effectively bypassed for bursts up to the concurrency cap.

Combined fix:
- Stamp hostMcpLastRun SYNCHRONOUSLY immediately after spawnHostClaude()
  returns without throwing. Order: spawn → stamp → register listeners.
- Drop the now-redundant child.on('spawn') listener.
- Extract performCleanup() — clears softTimer + killTimer, drops the map
  entry, unlinks request + mcp-config files. Idempotent via a
  `cleanedUp` boolean to handle the 'error'-then-'exit' race.
- child.on('error') now: rolls back the debounce stamp
  (hostMcpLastRun.delete) so a failed spawn doesn't burn the user's
  budget, calls performCleanup(), then logs and synthesizes the decline
  reply. Subsequent 'exit' fires no-op via the cleanedUp guard.
- child.on('exit') calls performCleanup() in its finally block (same
  semantics as before).

Tests:
- T1: assert debounce stamps synchronously (no spawn-event emit needed).
- T7b (new): two same-{group,scope} dispatches back-to-back in the same
  tick → only first spawns, second gets "too fast".
- T9 (rewritten): under fake timers, fire 'error', assert request +
  mcp-config unlinked, decline reply written, debounce rolled back, map
  entry cleared, vi.getTimerCount()===0, advancing past the timeout
  window produces NO spurious second reply, child.kill never called.
- T9b (new): error-then-exit cleanup is idempotent (no double map
  churn, no duplicate decline reply).
- T7: stop emitting 'spawn' (not needed anymore).

Ref: docs/plans/2026-04-24-001-feat-host-mcp-proxy-plan.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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.

3 participants