Repository navigation
fix: Add ARM64 Alpine compatibility for frontend Docker build - #12
oleksandr-korin wants to merge 1 commit into
Conversation
- Replace npm ci with npm install for better optional dependency handling - Add conditional installation of @rollup/rollup-linux-arm64-musl for ARM64 - Fixes build failures on Apple Silicon and ARM-based servers Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.
This is the final PR Bugbot will review for you during this billing cycle
Your free Bugbot reviews will reset on March 10
Details
You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.
To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.
| # and explicitly install rollup ARM64 Alpine binary if needed | ||
| RUN npm install && \ | ||
| if [ "$(uname -m)" = "aarch64" ]; then \ | ||
| npm install --no-save @rollup/rollup-linux-arm64-musl || true; \ |
There was a problem hiding this comment.
Silent failure masks ARM64 binary installation errors
Medium Severity
The || true at the end of the npm install @rollup/rollup-linux-arm64-musl command silently suppresses all errors, including legitimate failures like network issues or version incompatibilities. When running on ARM64 architecture, if this installation fails for a real reason, the Docker build succeeds but the container will fail at runtime when Vite/Rollup tries to use the missing native binary. This creates a confusing failure mode where builds appear successful but containers are broken.
| # and explicitly install rollup ARM64 Alpine binary if needed | ||
| RUN npm install && \ | ||
| if [ "$(uname -m)" = "aarch64" ]; then \ | ||
| npm install --no-save @rollup/rollup-linux-arm64-musl || true; \ |
There was a problem hiding this comment.
Missing version causes rollup native binary mismatch
High Severity
The @rollup/rollup-linux-arm64-musl package is installed without a version constraint, which means the latest version (e.g., 4.56.0) gets installed regardless of which rollup version npm install resolves. The native binary package version must exactly match the main rollup package version. If rollup 4.53.3 is installed but the native binary is 4.56.0, Vite will fail at runtime with module compatibility errors on ARM64 Alpine.
|
Closing as the ARM64 issue has already been resolved on main with a different approach (removing package-lock.json to let npm install the correct native binaries for the container architecture). Thank you for the contribution! |
The SLACK-001 public-link Slack integration (`db/slack.py`) was the last holdout still storing bot tokens as plaintext in SQLite, violating Architectural Invariant #12. Telegram (`telegram_bindings.bot_token_encrypted`), WhatsApp (`whatsapp_bindings.auth_token_encrypted`), and SLACK-002 (`slack_workspaces.bot_token`) all already encrypt via `services.credential_encryption` (AES-256-GCM, JSON envelope). This brings SLACK-001 in line with that pattern. Additionally, `slack_workspaces.bot_token` was rolled out with lazy encryption (encrypt-on-write + plaintext fallback at `slack_channels.py:47-49`) which left two sources of plaintext on disk: - Rows written before the encryption rollout - Rows copied from `slack_link_connections` by `_migrate_slack_channel_agents` A one-shot migration walks both tables on startup and re-encrypts any plaintext `xoxb-*` rows. Idempotent at row level (skip JSON envelopes) and at migration level (schema_migrations runner). src/backend/db/slack.py - Add `_get_encryption_service` / `_encrypt_token` / `_decrypt_token` (exact copy of the pattern in `db/slack_channels.py`, `db/telegram_channels.py`, `db/whatsapp_channels.py`) - Encrypt at `create_slack_connection` (write site) - Decrypt at `_row_to_connection` (read site, with `xoxb-*` plaintext fallback so runtime works pre-migration on legacy rows) - Caller-facing API surface unchanged — `slack_bot_token` field still contains plaintext in the returned dict src/backend/db/migrations.py - New `_migrate_slack_bot_token_encryption` registered in MIGRATIONS list - Walks BOTH `slack_link_connections.slack_bot_token` AND `slack_workspaces.bot_token`, encrypts plaintext rows in place - Hard-fail on missing CREDENTIAL_ENCRYPTION_KEY (matches the implicit pattern of every other consumer of CredentialEncryptionService) - Skips already-encrypted rows (signature: starts with `{` not `xoxb-`) - Defensive: skips silently if a table doesn't exist docs/memory/architecture.md - Reword Invariant #12 to acknowledge channel/subscription tokens as a documented exception (persisted but mandatorily encrypted), with the full list of tables under that rule - Add `slack_link_connections` DDL block; update `slack_workspaces` block to clarify the column-name vs content-type distinction tests/unit/test_slack_token_encryption.py (NEW, 14 tests) - TestRoundTrip: write encrypts, read decrypts, raw DB value is JSON envelope - TestPlaintextFallback: legacy `xoxb-*` row returns token + warning logged; corrupt envelope returns None + error logged - TestEncryptionHelpers: encrypt+decrypt isolation; encrypt raises ValueError on missing key; decrypt returns None on missing key - TestMigration: encrypts plaintext in both tables, skips encrypted, idempotent on second run, hard-fails without key, no-op on missing/empty tables Live verification on running backend: - Migration ran on startup: 1 row in each table re-encrypted (the real `ability.ai` workspace data) - On-disk now `{"version": 1, "algorithm": "AES-256-GCM", ...}` envelopes - `SlackOperations.get_slack_connection` returns the original `xoxb-...` plaintext via decrypt — caller-facing API surface unchanged Out of scope (filed separately): - Encryption tests for slack_channels.py + telegram_channels.py + whatsapp_channels.py (all shipped without dedicated test coverage): tracked in #664 - Renaming `bot_token` → `bot_token_encrypted` columns: cosmetic, would require a real schema migration; current naming works behind the service-layer encapsulation Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* fix(security): Encrypt Slack bot tokens at rest (#453) The SLACK-001 public-link Slack integration (`db/slack.py`) was the last holdout still storing bot tokens as plaintext in SQLite, violating Architectural Invariant #12. Telegram (`telegram_bindings.bot_token_encrypted`), WhatsApp (`whatsapp_bindings.auth_token_encrypted`), and SLACK-002 (`slack_workspaces.bot_token`) all already encrypt via `services.credential_encryption` (AES-256-GCM, JSON envelope). This brings SLACK-001 in line with that pattern. Additionally, `slack_workspaces.bot_token` was rolled out with lazy encryption (encrypt-on-write + plaintext fallback at `slack_channels.py:47-49`) which left two sources of plaintext on disk: - Rows written before the encryption rollout - Rows copied from `slack_link_connections` by `_migrate_slack_channel_agents` A one-shot migration walks both tables on startup and re-encrypts any plaintext `xoxb-*` rows. Idempotent at row level (skip JSON envelopes) and at migration level (schema_migrations runner). src/backend/db/slack.py - Add `_get_encryption_service` / `_encrypt_token` / `_decrypt_token` (exact copy of the pattern in `db/slack_channels.py`, `db/telegram_channels.py`, `db/whatsapp_channels.py`) - Encrypt at `create_slack_connection` (write site) - Decrypt at `_row_to_connection` (read site, with `xoxb-*` plaintext fallback so runtime works pre-migration on legacy rows) - Caller-facing API surface unchanged — `slack_bot_token` field still contains plaintext in the returned dict src/backend/db/migrations.py - New `_migrate_slack_bot_token_encryption` registered in MIGRATIONS list - Walks BOTH `slack_link_connections.slack_bot_token` AND `slack_workspaces.bot_token`, encrypts plaintext rows in place - Hard-fail on missing CREDENTIAL_ENCRYPTION_KEY (matches the implicit pattern of every other consumer of CredentialEncryptionService) - Skips already-encrypted rows (signature: starts with `{` not `xoxb-`) - Defensive: skips silently if a table doesn't exist docs/memory/architecture.md - Reword Invariant #12 to acknowledge channel/subscription tokens as a documented exception (persisted but mandatorily encrypted), with the full list of tables under that rule - Add `slack_link_connections` DDL block; update `slack_workspaces` block to clarify the column-name vs content-type distinction tests/unit/test_slack_token_encryption.py (NEW, 14 tests) - TestRoundTrip: write encrypts, read decrypts, raw DB value is JSON envelope - TestPlaintextFallback: legacy `xoxb-*` row returns token + warning logged; corrupt envelope returns None + error logged - TestEncryptionHelpers: encrypt+decrypt isolation; encrypt raises ValueError on missing key; decrypt returns None on missing key - TestMigration: encrypts plaintext in both tables, skips encrypted, idempotent on second run, hard-fails without key, no-op on missing/empty tables Live verification on running backend: - Migration ran on startup: 1 row in each table re-encrypted (the real `ability.ai` workspace data) - On-disk now `{"version": 1, "algorithm": "AES-256-GCM", ...}` envelopes - `SlackOperations.get_slack_connection` returns the original `xoxb-...` plaintext via decrypt — caller-facing API surface unchanged Out of scope (filed separately): - Encryption tests for slack_channels.py + telegram_channels.py + whatsapp_channels.py (all shipped without dedicated test coverage): tracked in #664 - Renaming `bot_token` → `bot_token_encrypted` columns: cosmetic, would require a real schema migration; current naming works behind the service-layer encapsulation Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(req): annotate SLACK-001 bot token as encrypted at rest (#453) SLACK-002 (line 809) noted "bot_token encrypted"; SLACK-001 (line 781) didn't, even after #453 brought slack_link_connections.slack_bot_token under the same AES-256-GCM regime. Mirror the annotation for parity. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Pavlo <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…244) (#684) Implements Slack's documented multi-connection Socket Mode pattern in adapters/transports/slack_socket.py. Slack's edge fans out events across active connections, so when one half-closes, siblings keep absorbing traffic — eliminating the 430 ms reconnect gap absorbed by the watchdog. Empirical basis: 7-day production ops report on ability-services showed 68 disconnect/reconnect cycles, 100% recovered by the watchdog (#278), all ending in identical "Cannot write to closing transport" — Slack's edge half-closing without a WebSocket close frame. Slack's own docs and support team recommend running multiple concurrent connections (up to 10 per app) as the architectural answer to this exact pattern. Changes - N concurrent SocketModeClient instances (default 2; range 1-10) via SLACK_SOCKET_CONNECTION_COUNT env var, clamped fail-safe on parse error - _ClientCtx dataclass per client (own watchdog task, own backoff counter) - Envelope-ID dedup ring (OrderedDict cap 1024 + asyncio.Lock) defends against possible cross-connection duplicate delivery; INFO log on hit so we measure whether Slack ever actually dual-delivers - Per-client log prefix [c=N] so ops can attribute disconnects per client - is_connected returns "any client healthy" (permissive) + new connected_count property exposes degraded mode - stop() iterates all clients/watchdogs (cleanup correctness) - Parallel start via asyncio.gather keeps boot at ~10s ceiling - Env-var WARN no longer echoes raw value (prevents accidental token leak if operator pastes app token into wrong env var) Tests - 56/56 passing (28 existing watchdog + 28 new multi-connection) - New test_slack_multi_connection.py covers env-var bounds, is_connected/connected_count semantics, dedup ring (skip + concurrent + FIFO eviction), per-client backoff isolation, partial startup, N=1 backward compat, stop() cleanup Deferred - #683 — wrap connect_to_new_endpoint() in asyncio.wait_for to prevent watchdog stall (pre-existing watchdog hole, blast-radius reduced by this PR's per-client isolation) Verified - Single-worker uvicorn confirmed (docker-compose.yml line 82, no --workers flag; line 230 comment confirms intent), so per-process dedup ring is correct - Architectural Invariants preserved (Channel Adapter ABC unchanged; no new endpoints; no new persistent storage; no Invariant #12 regression) - /review found 0 critical, 2 informational; C1 applied - /cso --diff: 0 critical / 0 high / 0 medium / 0 low Fixes #244 Co-authored-by: Pavlo <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…#1056) (#1066) * feat(voice): VoIP telephony Phase 1 — outbound calls over Gemini Live (#1056) Add outbound phone-call capability: an agent places a call via Twilio Programmable Voice + bidirectional Media Streams, bridged into the existing, UNMODIFIED Gemini Live voice service. A phone call is just a different audio transport feeding the same PCM queues. Ships as a regular OSS feature behind the `voip_available` flag, which is OFF by default (mirrors workspace_available); also requires a per-agent voip_bindings row to function. Three-layer module (Invariant #1): - routers/voip.py binding CRUD (owner) + outbound trigger + WS entry - services/voip_service.py gate/abuse checks, intent staging, Twilio dial, post-call transcript dispatch to the main agent - db/voip.py voip_bindings (encrypted Twilio AuthToken) + voip_call_logs + durable daily-cap count Audio bridge (codec work lives outside gemini_voice.py): - adapters/transports/twilio_media_stream.py Media Streams WS bridge: ticket+scope check, GETDEL staged intent (consume-once), creates the Gemini session on the connecting worker, paced 20ms 160-byte μ-law sender, clear-on-barge-in, gemini-end→Twilio-close teardown, SETNX-guarded single transcript save (source="voice"). - adapters/transports/voip_audio.py pure audioop helpers with per-direction ratecv state carried across chunks (byte-for-byte anti-click guarantee). Security / abuse controls: - Call-bound single-use WSS ticket (ws_ticket_service gains ttl_seconds; scope="voip:{call_id}", 180s) — Twilio can't send a JWT. - Rate-limit per (owner, destination) + durable per-agent daily cap + optional Idempotency-Key (Invariant #18). Owner brings own Twilio creds; AuthToken AES-256-GCM at rest (Invariant #12). - voip_* tables registered in the agent cascade registry so rename moves the binding and delete/purge wipes it (no orphans / broken-after-rename). Post-call processing (default ON): the full transcript is dispatched to the MAIN agent via task_execution_service.execute_task(triggered_by="voip") so the agent (with its real skills/memory/MCP) acts on the call. Three surfaces in sync (Invariant #13): backend router + MCP call_user tool (tools/voip.ts + client.ts + server.ts). audioop-lts pinned for py>=3.13. Tests: 27 unit tests (audio round-trip + stateful-ratecv continuity, binding CRUD + encryption, migration, service gates incl. mocked Twilio dial). Docs: requirements VOIP-001, architecture.md, feature-flow doc, CSO report. Phases 2 (inbound) and 3 (UI/observability) are out of scope here. Part of #1056 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test: fix database.db leak in test_904 that broke voip gate tests under seed ordering (#1056) The `regression diff` CI gate flagged 5 new HEAD-only failures in test_voip_service.TestPlaceOutboundCallGates under 2 of 3 random seeds (67890, 99999) — passing under 12345. Root cause was a pre-existing test-isolation leak surfaced by the new VoIP tests: test_904_agent_call_limiter._install_db_stub() mutates `database.db` ON the already-imported real `database` module object. Its autouse `_restore_sys_modules` fixture only restored the `sys.modules["database"]` *entry* (the same object) — never undoing the `.db` mutation — so the fake `_Db` singleton leaked for the rest of the session. When test_904 ran before test_voip_service under a given seed, the voip test's `importlib.reload(services.voip_service)` re-ran `from database import db` and bound `vs.db` to the leaked `_Db` fake, so `monkeypatch.setattr(vs.db, "get_voip_binding", ...)` raised AttributeError (the fake lacks voip methods). Fix: snapshot and restore `database.db` in test_904's autouse fixture. Additive, scoped to that fixture; test_904's own assertions are unchanged (the stub is still live during each test body). Verified: full `pytest unit/ -p randomly` is green for the voip gate tests and test_904 under all three CI seeds (12345/67890/99999). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Eugene Vyborov <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
* docs(architecture): add target architecture document and wire into dev workflow Introduces docs/planning/TARGET_ARCHITECTURE.md — the optimal steady-state design Trinity should converge toward (PostgreSQL, actor model coordination, async-first agent communication, fleet observability, GuardAgent security). Updates CLAUDE.md, DEVELOPMENT_WORKFLOW.md, and the groom/roadmap/sprint playbooks to distinguish current architecture (what is built today) from target architecture (where decisions should point), and to use target architecture alignment as a ranking signal during backlog grooming and issue prioritization. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(security): encrypt SLACK-001 bot tokens at rest (#453) (#667) * fix(security): Encrypt Slack bot tokens at rest (#453) The SLACK-001 public-link Slack integration (`db/slack.py`) was the last holdout still storing bot tokens as plaintext in SQLite, violating Architectural Invariant #12. Telegram (`telegram_bindings.bot_token_encrypted`), WhatsApp (`whatsapp_bindings.auth_token_encrypted`), and SLACK-002 (`slack_workspaces.bot_token`) all already encrypt via `services.credential_encryption` (AES-256-GCM, JSON envelope). This brings SLACK-001 in line with that pattern. Additionally, `slack_workspaces.bot_token` was rolled out with lazy encryption (encrypt-on-write + plaintext fallback at `slack_channels.py:47-49`) which left two sources of plaintext on disk: - Rows written before the encryption rollout - Rows copied from `slack_link_connections` by `_migrate_slack_channel_agents` A one-shot migration walks both tables on startup and re-encrypts any plaintext `xoxb-*` rows. Idempotent at row level (skip JSON envelopes) and at migration level (schema_migrations runner). src/backend/db/slack.py - Add `_get_encryption_service` / `_encrypt_token` / `_decrypt_token` (exact copy of the pattern in `db/slack_channels.py`, `db/telegram_channels.py`, `db/whatsapp_channels.py`) - Encrypt at `create_slack_connection` (write site) - Decrypt at `_row_to_connection` (read site, with `xoxb-*` plaintext fallback so runtime works pre-migration on legacy rows) - Caller-facing API surface unchanged — `slack_bot_token` field still contains plaintext in the returned dict src/backend/db/migrations.py - New `_migrate_slack_bot_token_encryption` registered in MIGRATIONS list - Walks BOTH `slack_link_connections.slack_bot_token` AND `slack_workspaces.bot_token`, encrypts plaintext rows in place - Hard-fail on missing CREDENTIAL_ENCRYPTION_KEY (matches the implicit pattern of every other consumer of CredentialEncryptionService) - Skips already-encrypted rows (signature: starts with `{` not `xoxb-`) - Defensive: skips silently if a table doesn't exist docs/memory/architecture.md - Reword Invariant #12 to acknowledge channel/subscription tokens as a documented exception (persisted but mandatorily encrypted), with the full list of tables under that rule - Add `slack_link_connections` DDL block; update `slack_workspaces` block to clarify the column-name vs content-type distinction tests/unit/test_slack_token_encryption.py (NEW, 14 tests) - TestRoundTrip: write encrypts, read decrypts, raw DB value is JSON envelope - TestPlaintextFallback: legacy `xoxb-*` row returns token + warning logged; corrupt envelope returns None + error logged - TestEncryptionHelpers: encrypt+decrypt isolation; encrypt raises ValueError on missing key; decrypt returns None on missing key - TestMigration: encrypts plaintext in both tables, skips encrypted, idempotent on second run, hard-fails without key, no-op on missing/empty tables Live verification on running backend: - Migration ran on startup: 1 row in each table re-encrypted (the real `ability.ai` workspace data) - On-disk now `{"version": 1, "algorithm": "AES-256-GCM", ...}` envelopes - `SlackOperations.get_slack_connection` returns the original `xoxb-...` plaintext via decrypt — caller-facing API surface unchanged Out of scope (filed separately): - Encryption tests for slack_channels.py + telegram_channels.py + whatsapp_channels.py (all shipped without dedicated test coverage): tracked in #664 - Renaming `bot_token` → `bot_token_encrypted` columns: cosmetic, would require a real schema migration; current naming works behind the service-layer encapsulation Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(req): annotate SLACK-001 bot token as encrypted at rest (#453) SLACK-002 (line 809) noted "bot_token encrypted"; SLACK-001 (line 781) didn't, even after #453 brought slack_link_connections.slack_bot_token under the same AES-256-GCM regime. Mirror the annotation for parity. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Pavlo <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * docs(announcements): add Cornelius voice mode video announcement Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(validation): add agent validation spec for issue #668 56 checks across 10 categories covering static file checks, YAML/JSON schema validation, security scanning, and AI-evaluable logical checks (skill coherence, CLAUDE.md quality, cross-file consistency). Serves as the canonical check list for the compatibility validation API and MCP tool. Closes-adjacent: #668 Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(monitoring): degrade fleet-status to 'unknown' instead of 500 on NULL status row (#669) (#676) `GET /api/monitoring/status` (the endpoint MCP `get_fleet_health` calls) was returning 500 whenever any `agent_health_checks` row had `status = NULL`. Root cause: the build loop did AgentHealthSummary(status=check.get("status", "unknown"), ...) `dict.get(key, default)` only returns the default when the key is *missing*. A row with the key present but value `None` returned `None`, which Pydantic v2 rejected because `AgentHealthSummary.status: str` is required. The sibling per-agent endpoint dodged this by triggering a fresh health check when no aggregate row existed, which is why `get_agent_health` worked while `get_fleet_health` 500'd in the production fleet that triggered #669. Fix: - Extract `_build_agent_summary(name, check)` and `_coerce_status(raw)` so NULL/missing/non-str status degrades to `"unknown"` consistently. Same for NULL `error_message` (would explode `.split("; ")`). - Wrap the aggregator in try/except returning a structured "unknown" payload rather than 500 (issue ask #1). Future schema drift surfaces as data, not as an outage. - Reconcile `docs/user-docs/operations/monitoring.md` — the listed `/api/monitoring/fleet-health` path doesn't exist; correct to `/api/monitoring/status`. Tests: 7 new unit tests in `tests/unit/test_fleet_status_resilience.py` covering NULL status, missing status key, missing check row, NULL error_message, non-string status, and sort-key tolerance. Does NOT fix the underlying scheduler stoppage (8 of 9 agents going months without a health-check refresh) — that root cause needs production logs and is split out as a separate ticket. Closes #669 (symptom) Refs #675 (scheduler stoppage follow-up) Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(agent-runtime): surface stdout parse failures + orphan identity for #640 debugging (#662) After diagnosing #640 against a running agent with an npx-launched stdio MCP (@upstash/context7-mcp@latest), the issue body's "MCP child inherits fd > 2" theory does not hold: Node.js spawn already isolates the MCP child to fd 0/1/2 on socketpairs. The remaining wire-corruption mechanism (some descendant outside claude's pgid acquiring agent-server's pipe write-end via setsid+dup) needs a live production trace to root-cause — single-session repro budget here isn't enough to manifest the failure (issue says ≥100 turns / 18min). What this commit does ship: make the next production failure usable by surfacing the diagnostic data the existing #618/#639 mitigations already had at hand but discarded. read_stdout (chat + headless paths) - JSONDecodeError no longer silently `pass`-swallowed. - Track count + capture first sanitised, length-capped (300 char) sample. - Surface in completion log line as parse_failures=N + WARNING with sample text when N > 0. Lets operators distinguish wire corruption (#640) from reader-leak-past-claude-exit (#520/#618) in production logs. _classify_empty_result - New parse_failure_count / parse_failure_sample kwargs (defaults preserve legacy callers — chat path doesn't wire it; backward compat covered by test_default_parse_failure_args_preserve_legacy_callers). - Detail string now includes parse_failures + raw_messages type histogram (top 6 types) + first malformed line. The histogram tells operators whether the reader caught most of the stream or stalled near the start. _kill_orphan_pipe_writers (#618) - Was logging orphan count only. - Now captures cmdline / ppid / pgid per orphan BEFORE SIGKILL (after the kill /proc/{pid} is gone) and emits one INFO line per pid, capped at 10 lines + count-only summary, so log volume stays bounded under a runaway MCP fan-out. - First pass at identifying which package consistently leaks. Issue body's "npm setsid" hypothesis is testable now without re-instrumenting. 5 new tests (33 total, all green): - test_parse_failure_count_surfaces_in_detail - test_parse_failure_sample_appended_when_present - test_parse_failure_sample_omitted_when_count_is_zero - test_raw_messages_type_summary_in_detail - test_default_parse_failure_args_preserve_legacy_callers Does not close #640. The wire-interleaving root cause remains open — but the diagnostic surface is now sufficient to identify it from a single production failure rather than needing to re-instrument and wait for the next occurrence. Issue: #640 Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(executions): block SUCCESS over CANCELLED so user cancel survives late agent reply (#671) (#681) When an operator cancels a running execution mid-flight, two writers race on the same `schedule_executions` row: Writer A — terminate handler (`routers/chat.py:~1841`) writes status = CANCELLED. Writer B — TaskExecutionService success branch (`services/task_execution_service.py:498`) writes status = SUCCESS once the agent's HTTP reply lands. Claude Code typically catches the cancel signal, emits a graceful final message, and exits 0 — so the agent reports "completed successfully" and B lands well after A. Pre-fix CAS (RELIABILITY-005, db/schedules.py): SUCCESS writes were unconditional ("agent's own completion result always wins"). When A landed first and B landed second, B silently clobbered the CANCELLED status with SUCCESS. Effects in production: - schedule's `next_run_at` advanced as if the run had succeeded, suppressing recovery on the next cron tick (silent skip) - cost telemetry counted the partial run as billable success - on-call had no signal that deliverables were incomplete - for agents with side effects (Slack post, sheet rows, CRM), wrongly- green status hid incomplete work from operators Reporter saw two consecutive incidents on bdr-agent / `Daily Lead Outreach` ending with status=success despite the operator cancelling and no Slack ping / sheet rows / final deliverable being produced. Fix: narrow the CAS carve-out so SUCCESS writes are blocked when the row is already CANCELLED, but still win over RUNNING / QUEUED / PENDING_RETRY / SKIPPED and over a phantom-stale FAILED (preserves the #378 invariant — real completions still beat misfired Phase-3 cleanup). - SUCCESS over RUNNING — wins (happy path) - SUCCESS over phantom FAILED — wins (#378 invariant preserved) - SUCCESS over CANCELLED — blocked (#671) - FAILED/CANCELLED over any terminal — blocked (RELIABILITY-005, unchanged) Tests: 5 unit tests in tests/unit/test_cancelled_not_overwritten.py covering each transition above. The exact prod race repro (`test_success_blocked_when_row_already_cancelled`) fails pre-fix, passes post-fix. Live-verified against running stack: cancel write ok: True after cancel: ('cancelled',) late-success write ok: False after late-success: ('cancelled', None, None) # response/cost NOT recorded Defense-in-depth (plumb cancel signal into the agent task-runner so its reply carries `status=cancelled` and its log says "cancelled by user" instead of "completed successfully") tracked separately as a follow-up. Closes #671 (minimum CAS guard) Refs #679 (defense-in-depth follow-up) Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(slack): multi-connection Socket Mode with envelope-ID dedup ring (#244) (#684) Implements Slack's documented multi-connection Socket Mode pattern in adapters/transports/slack_socket.py. Slack's edge fans out events across active connections, so when one half-closes, siblings keep absorbing traffic — eliminating the 430 ms reconnect gap absorbed by the watchdog. Empirical basis: 7-day production ops report on ability-services showed 68 disconnect/reconnect cycles, 100% recovered by the watchdog (#278), all ending in identical "Cannot write to closing transport" — Slack's edge half-closing without a WebSocket close frame. Slack's own docs and support team recommend running multiple concurrent connections (up to 10 per app) as the architectural answer to this exact pattern. Changes - N concurrent SocketModeClient instances (default 2; range 1-10) via SLACK_SOCKET_CONNECTION_COUNT env var, clamped fail-safe on parse error - _ClientCtx dataclass per client (own watchdog task, own backoff counter) - Envelope-ID dedup ring (OrderedDict cap 1024 + asyncio.Lock) defends against possible cross-connection duplicate delivery; INFO log on hit so we measure whether Slack ever actually dual-delivers - Per-client log prefix [c=N] so ops can attribute disconnects per client - is_connected returns "any client healthy" (permissive) + new connected_count property exposes degraded mode - stop() iterates all clients/watchdogs (cleanup correctness) - Parallel start via asyncio.gather keeps boot at ~10s ceiling - Env-var WARN no longer echoes raw value (prevents accidental token leak if operator pastes app token into wrong env var) Tests - 56/56 passing (28 existing watchdog + 28 new multi-connection) - New test_slack_multi_connection.py covers env-var bounds, is_connected/connected_count semantics, dedup ring (skip + concurrent + FIFO eviction), per-client backoff isolation, partial startup, N=1 backward compat, stop() cleanup Deferred - #683 — wrap connect_to_new_endpoint() in asyncio.wait_for to prevent watchdog stall (pre-existing watchdog hole, blast-radius reduced by this PR's per-client isolation) Verified - Single-worker uvicorn confirmed (docker-compose.yml line 82, no --workers flag; line 230 comment confirms intent), so per-process dedup ring is correct - Architectural Invariants preserved (Channel Adapter ABC unchanged; no new endpoints; no new persistent storage; no Invariant #12 regression) - /review found 0 critical, 2 informational; C1 applied - /cso --diff: 0 critical / 0 high / 0 medium / 0 low Fixes #244 Co-authored-by: Pavlo <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * docs(user-docs): add deployment guides + screenshots - Add 6 missing deploying/ spokes: local-development, single-server, public-access, upgrading, backup-and-restore, monitoring - Add 9 UI screenshots and wire into 10 existing feature docs - Update deploying-trinity.md hub with spoke navigation table Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(agent-client): circuit breaker cooldown clock no longer resets on failures while open (#687) (#688) record_failure() was resetting last_failure_time on every call, including when the circuit was already open. Continuous probe failures (cleanup re-verify, scheduler dispatches) kept the cooldown timer near zero, making the half-open transition unreachable and leaving the circuit permanently open until backend restart. Fix: only update last_failure_time when state != "open", so the 30s cooldown starts from when the circuit first opens and is not disturbed by subsequent failures. Fixes #687 Co-authored-by: Claude Sonnet 4.6 <[email protected]> * refactor(config): remove legacy unauth REDIS_URL fallbacks (#645) (#697) `config.REDIS_URL` is the canonical Redis URL gate (#589 / PR #643) — it raises at import if creds are missing. Three services bypassed that gate by reading the env var directly with an unauthenticated localhost fallback, both at the factory site and in the constructor default: redis_url = os.getenv("REDIS_URL", "redis://redis:6379") def __init__(self, redis_url: str = "redis://redis:6379"): In docker-compose these branches don't fire — REDIS_URL is always populated. But test/CI paths and ad-hoc debug shells silently fall back to unauth localhost, then hit NOAUTH at runtime instead of the clear startup-time error #589 establishes. Changes: - slot_service / ssh_service: factories drop the os.getenv fallback; constructors take Optional[str] = None and lazy-import config.REDIS_URL when called with no arg. - capacity_manager: same pattern, lazy-import in __init__. - tests/unit/conftest.py: setdefault REDIS_URL with creds before any backend import — unit tests don't share the parent conftest (norecursedirs = ..) so the env wasn't being primed. - tests/unit/test_redis_url_no_fallback.py: lint-style regression test that greps src/backend/services/ for `os.getenv("REDIS_URL"` and `"redis://redis:6379"` and fails if either resurfaces. Verified: - 30 unit tests pass in trinity-backend container (test_redis_url_no_fallback + test_capacity_manager + test_config_fail_fast) - 14 ssh_service tests + 9 redis-url-related tests pass on host venv - Live backend bootstraps cleanly: SlotService / SshService / CapacityManager all resolve REDIS_URL via config - Lint test catches regression: stashing the slot_service fix flips both assertions to FAIL with offending line:number Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(security): close TOCTOU race in webhook rate limiter (#644) (#696) * fix(security): close TOCTOU race in webhook rate limiter (#644) Pre-fix path issued a separate GET then INCR. N concurrent callers could all observe count < WEBHOOK_RATE_LIMIT before any of them incremented, slipping past the 429 and pushing the actual call rate to limit + N. Switched to INCR-then-compare (Redis INCR is atomic): increment unconditionally, then 429 the caller whose post-increment count crosses the threshold. Trade-off: blocked requests still tick the counter, slightly extending cool-down for an over-limit token. Acceptable for a rate-limiter — we only stop accepting work, we don't unwind. Tests: - tests/unit/test_webhook_rate_limit_toctou.py — pins INCR-first semantics. The structural assertion (r.get() not called) reliably catches a partial revert that re-adds the GET; the wide-window race belongs in integration tests against real Redis. - tests/integration/test_webhook_rate_limit.py — adds concurrent burst test alongside the existing #589 sequential coverage. Verified live in trinity-backend with real Redis: - pre-fix: 15/20 succeeded under 20-thread burst (limit 10) — race reproduced. - post-fix: exactly 10/20 succeeded — limit holds. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(webhooks): unblock trigger endpoint — schedule model + audit signature (#647 follow-up) While verifying #644 against a live stack, found two additional facade gaps that #648 (the WEBHOOK-001 delegation fix) didn't catch — both crash trigger_webhook before the rate-limiter even runs to completion: 1. `Schedule` pydantic model never carried `webhook_enabled` / `webhook_token` fields. The DB columns exist, but the row mapper discarded them, so `if not schedule.webhook_enabled:` raised AttributeError on every trigger call. 2. `webhooks.py:trigger_webhook` called `platform_audit_service.log()` with `actor_type="system"`. The service derives actor_type internally from actor_user / actor_agent_name / mcp_scope and has no such kwarg; every accepted webhook 500'd in the audit step. Both are tiny: - Add the two fields to `Schedule` (db_models.py). - Pull them through `_row_to_schedule` (db/schedules.py). - Drop the bogus actor_type kwarg, pass actor_ip instead — webhook callers are unauthenticated so caller IP is the only attributable signal. With these, the integration test in tests/integration/test_webhook_rate_limit.py now exercises the full HTTP path end-to-end. Live verification against the running backend: 15-way concurrent burst → 10 × 202 + 5 × 429, limit holds. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(api-keys): clipboard fallback + error feedback (#677) (#695) Both copy actions on /api-keys (Copy Config, Copy key icon) called navigator.clipboard.writeText() with no fallback and swallowed every rejection in console.error, so users in modal-focus or non-secure contexts saw nothing on the clipboard and no error. - Add `utils/clipboard.js` with a textarea + execCommand fallback, returning a boolean for caller-driven UX. - Wire ApiKeys.vue's copyApiKey / copyMcpConfig through the helper. Visual "Copied!" / green-check state only fires on confirmed success; failure shows an alert telling the user to copy manually. - Add e2e spec exercising both buttons with a granted clipboard-read permission. Verified in a real browser (admin login, /api-keys, create key, click both buttons): clipboard contained the expected MCP JSON and raw `trinity_mcp_*` key respectively; no console errors. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(monitoring): correct get_accessible_agents call signature (#682) (#694) `GET /api/monitoring/status` returned 500 TypeError for non-admin users because routers/monitoring.py called the helper with the pre-refactor two-arg signature `(email, agent_names)`. Every other call site was updated to `(current_user)` — only this one was missed. Adds a unit regression test that pins the canonical helper signature and spy-verifies the router calls it with exactly one positional User arg. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * test(harness): repro scaffolding + negative results for #640 — 6 hypotheses falsified (#693) * test(harness): repro scaffolding for #640 — controlled stdio MCP leaks Adds tests/harness/640/ — three files implementing a deterministic repro harness for the open root cause behind the reader-thread / wire-corruption failure family (#640, manifesting in #678, #630, #618, #548, #586). Background: PR #662's author tried 1.5h with `@upstash/context7-mcp` — issue body says ≥100 turns / 18min are needed to manifest. Hunting for a naturally-leaky package is unreliable. Instead this harness builds a controlled experiment: a minimal stdio MCP server with switchable leak variants, each testing one hypothesis from the issue body and #662's empirical notes. Files: - noisy_mcp_server.py — stdlib-only stdio MCP server with --leak knob: none : control / baseline stderr-flood : MCP child stderr noise setsid-child : grandchild that escapes pgid (#618 family) and retains protocol-pipe write end proc-fd-write : raw writes to /proc/self/fd/1 interleaved with MCP frames delayed-stdout : partial-line writes that race the reader at line boundary npm-wrapper : real-world npx-style boilerplate emitted to stdout BEFORE protocol handshake — most likely production culprit - run_repro.py — driver that hits an agent's chat API for N turns and measures null-cost / null-response rate (the observable symptom from #678). Exits 1 if rate exceeds --null-cost-fail-rate (default 5%) so the harness can also serve as a CI regression gate once a fix lands. - README.md — runbook: agent setup, .mcp.json wiring, expected output, caveats. Documents that parse_failures-counter assertions wait on PR #662 merging. Smoke-tested: - Simulator's CLI parses --help. - Sample initialize + tools/list session round-trips clean JSON responses with --leak=none, sidecar log captures protocol activity. - npm-wrapper variant emits the boilerplate BEFORE the JSON-RPC reply as designed. This commit is scaffolding only — actual variant characterization against a running stack is a follow-up. Each variant takes ~10-15 min of Sonnet wall-time at 50 turns, so running the full 6-variant matrix is a budgeted exercise rather than something to do in one CI pass. Refs #640 Refs #662 (parse_failures instrumentation prerequisite) Refs #678 (production manifestation that motivated this work) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * test(harness): document negative results for #640 — 6 hypotheses falsified Adds the results section to tests/harness/640/README.md after running 2 variants empirically (npm-wrapper, setsid-child) plus 4 hypotheses ruled out via static inspection of claude-cli's cli.js and Linux kernel behaviour. Also fixes a driver bug where cost was read from top-level `cost_usd` instead of `metadata.cost_usd` (real cost lives under metadata; the chat endpoint nests observability fields there). The harness as designed cannot reproduce #640 because every leak path it can exercise is on the MCP protocol pipe (claude-side), not on the agent-server claude-stdout pipe (which is where the wire corruption in #640 actually manifests). Claude+SDK isolate MCP child stdio correctly; Linux refuses /proc/*/fd/* bypass with ENXIO; Claude has no stray stdout writes in stream-json hot path. Negative results preserved so future #640 hunts don't re-walk the same paths. Real next step is landing PR #662 and getting prod-data- driven evidence on which package actually leaks. Refs #640 Refs #662 (diagnostic instrumentation prerequisite) Refs #678 (production manifestation) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * feat(voice): agent workspace page with canvas panel and Gemini panel tools (#699) (#703) * feat(voice): agent workspace page with canvas panel and Gemini panel tools (#699) Adds a full-page voice workspace at /agents/:name/workspace with a split layout: orb + controls on the left, an agent-controlled canvas panel on the right. Introduces four in-process panel tools (show_markdown, update_panel, append_to_panel, clear_panel) that let Gemini write structured content to the canvas during a voice conversation without delegating to the agent container. Panel state is polled at 300ms via a new GET /voice/{session_id}/panel endpoint. Workspace mode is gated on a new voice_available feature flag (GEMINI_API_KEY + VOICE_ENABLED) and surfaced via a BETA-badged button in AgentHeader. Security: panel content is DOMPurify-sanitised before v-html rendering; panel endpoint has session ownership checks; append_to_panel caps accumulated content at 512 KB to bound per-session memory. Tests: 7 new panel-tool unit tests (test_voice_tools.py); 5 new panel endpoint ownership tests (test_voice_auth.py). Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(voice): add VOICE-008 to requirements + voice API table in architecture Adds VOICE-008 (Voice Workspace / #699) requirements entry and Phase 4 roadmap entry. Adds voice API endpoint table to architecture.md (was entirely absent) and updates feature-flags description to mention voice_available. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]> * fix(voice): cross-worker session 403 + audit kwargs TypeError (#704 #705) (#706) #704: Voice sessions written to Redis (dual-write with in-memory) so a WebSocket worker can auth-check a session created on a different Uvicorn process. VoiceService.create/get/remove_session are now async; Redis key TTL = VOICE_MAX_DURATION + 60 (360s); Redis failure at /voice/start raises loudly rather than silently producing an intermittently-failing session ID. #705: on_tool_call callback passed legacy actor_type=/actor_id=/actor_email= kwargs that don't exist on platform_audit_service.log(), causing a TypeError that silently swallowed every voice tool-call audit record. Fixed to use actor_user=types.SimpleNamespace(id=..., email=...) matching the _resolve_actor contract; wrapped in asyncio.create_task so the audit write doesn't block. Tests: +7 Redis fallback tests (TestRedisSessionFallback in test_voice_tools.py), +1 audit attribution source-inspection test (TestVoiceAuditAttribution in test_voice_auth.py). Catalog updated: 45 voice unit tests total. Co-authored-by: Claude Sonnet 4.6 <[email protected]> * fix(voice): workspace panel flicker + Chart.js rendering in update_panel (#707) (#709) - updated_at change-detection gate in fetchPanel() prevents 3x/sec Vue re-renders and stops empty state from overwriting content when session ends - in-flight guard (panelFetching flag) prevents overlapping 300ms requests - panel content preserved on session end; reset on new session start - replace v-html+sanitizedHtml computed with ref+renderHtmlPanel(): DOMPurify.sanitize(html, {ADD_TAGS:['script']}) + _execScripts() re-clones script nodes as live DOM so Chart.js new Chart() calls execute correctly - Chart.js 4.4.0 pre-loaded via injectChartJs() on mount (CDN, id-guarded) - WORKSPACE_PANEL_INSTRUCTIONS updated: document Chart.js pre-loaded rule Fixes #707 Co-authored-by: Claude <[email protected]> * docs(architecture): update stale api-keys refs after #302 settings refactor ApiKeys.vue deleted; /api-keys now redirects to /settings?tab=mcp-keys. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * refactor(settings): tabbed layout with role-gated MCP Keys absorption (#302) (#700) Splits the 2,600-line Settings page into 5 logical tabs (General, Access, Integrations, MCP Keys, Agents) with URL ?tab= deep-linking and ROLE-001 role-gated visibility. Absorbs the standalone /api-keys page into the new MCP Keys tab; preserves bookmarks via a permanent SPA redirect. Built test-first via Canon TDD against a 12-behavior list documented at docs/planning/302-settings-test-list.md. 14 Playwright tests pass; 13 match the test-list items 1:1 plus 1 regression test pinning the non-admin admin-403-bounce fix surfaced during /review. Behavior - /settings ?tab=<id> deep links to any tab. Unknown ?tab= falls back to the user's default tab. Browser back/forward navigates tab history. - Tab visibility gates by role: admin sees all 5 tabs; non-admin sees only MCP Keys (matches today's /api-keys page being non-admin). - Default tab: General for admin, MCP Keys for non-admin. - /api-keys redirects to /settings?tab=mcp-keys (static literal target, no open-redirect surface). - NavBar "Keys" link removed; Settings link now visible to all auth users (was admin-only). Implementation - New components/settings/McpKeysTab.vue extracted from views/ApiKeys.vue (deleted). Same auth posture preserved verbatim. - New composables/useRole.js mirrors backend ROLE-001 hierarchy (user < operator < creator < admin) for client-side UI gating. - New authStore.role getter sourced from /api/users/me; new fetchUserProfile() action populates role on login + session restore. - 13 existing Settings sections wrapped with v-if matching their tab. - watch(isAdmin, ..., { immediate: true }) guards admin-only data fetches so non-admin users don't trigger 403 → router.push('/') bounce — this was the bug surfaced by /review and fixed pre-merge. Security - Backend require_admin/require_role in routers/settings.py UNCHANGED. UI hiding is convenience, not the security boundary. A non-admin who edits localStorage.user.role = 'admin' sees all 5 tabs but every admin endpoint still returns 403 — UI bypass yields zero capability gain. - /api-keys redirect target is a hardcoded literal — no user input. - /review: 0 critical (after C1 fix), 5 informational. - /cso --diff: 0 critical / 0 high / 0 medium / 0 low. Acceptance criteria status - [x] Tabbed nav with ?tab= URL query param - [x] 12+ sections organized into 5 logical tabs - [x] MCP API Keys absorbed into Settings - [~] "Each tab a separate Vue component" — only McpKeysTab.vue extracted; the other 4 tabs remain inline v-if sections in Settings.vue. Follow-up issue worth filing for full extraction (state, methods, computed props need to move per-tab). - [x] NavBar simplified (Keys link removed) - [x] Non-admin users still access MCP key management - [x] No functionality lost — covered by behavior 11 regression test Test plan - 14/14 settings-tabs.spec.js pass (13 list-driven + 1 regression) - Existing smoke.spec.js updated (no longer asserts Keys link) - 3 unrelated session-tab.spec.js failures pre-exist on dev (unaffected) Out of scope (intentionally deferred) - Full tab-as-component extraction (4 remaining) - v-show vs v-if for modal-state preservation across tab switches - Vitest unit-test infra (frontend has Playwright e2e only) Fixes #302 Co-authored-by: Pavlo <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(voice): test regression + Chart.js bundling + model default (#723) (#726) Fixes three independent regressions in the voice workspace: 1. **test_voice_auth.py collection failure** — `_stub_docker_service()` was missing `docker_client` and four other attrs that `services/__init__.py` imports; adding a template_service stub also prevents a cascade from migration code that imports `services.credential_encryption`. Set `SECRET_KEY` env var early so the real config and `test_voice_tools.py` stub both sign/verify JWTs with the same key (avoids 4001 on ownership tests). 2. **test_voice_tools.py import error** — `services.gemini_voice` stub left in `sys.modules` by `test_voice_auth.py` blocked the real import of `GeminiVoiceService`. One-line eviction before the import fixes it. 3. **Chart.js CDN → bundle** — replace the dynamic CDN script injection with a proper `import Chart from 'chart.js/auto'` + `window.Chart = Chart` in `AgentWorkspace.vue`. The CDN approach was unreliable under load; the bundled path is deterministic. `fetchPanel` null-guard updated so panel content is never overwritten by an empty response after session end. Also exposes `VOICE_MODEL` env var in docker-compose and updates the default model identifier to `models/gemini-3.1-flash-live-preview`. All 45 tests in test_voice_auth.py + test_voice_tools.py pass. Closes #723 Co-authored-by: Claude Sonnet 4.6 <[email protected]> * fix(schedules): restore auth parity on GET webhook status endpoint (#724) (#727) * docs(validate-pr): add infrastructure change check to align with DEVELOPMENT_WORKFLOW.md Adds Step 4.7 to flag docker-compose/Dockerfile changes without justification, matching the Red Flags checklist in docs/DEVELOPMENT_WORKFLOW.md. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(schedules): restore auth parity on GET webhook status endpoint (#724) GET /{name}/schedules/{id}/webhook used AuthorizedAgent which calls db.get_agent_owner() and 404s for agents not in the ownership table. POST and DELETE already use name:str + can_user_access_agent; align GET to match so all three webhook endpoints behave consistently. Fixes #724 Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]> * fix(tests): fix test import drift — 0 collection errors, all 3 target files pass (#725) (#729) * fix(tests): patch sys.modules stubs in monitoring router and skill service user agent tests Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(tests): add get_agent_default_resources stub to readiness probe test (#725) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(tests): recover real fastapi in monitoring router loader (#725) test_inject_assigned_credentials.py permanently overwrites sys.modules['fastapi'] with a Mock at collection time via sys.modules.update(). When collected after that file (alphabetically 'i' < 'm'), _load_monitoring_router() exec'd monitoring.py with a mocked APIRouter, causing @router.get() to return a Mock instead of the original async function. asyncio.run() then raised TypeError on the Mock. Fix: briefly evict the polluted fastapi entry, re-import from disk to get the real module, restore the Mock, then include the real fastapi in the patch.dict context used during exec_module. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]> * fix(agent-server): cap drain executor thread at 90 s to fix #728 CPU spin (#730) `safe_close_pipes` deadlocks on Python's BufferedReader internal lock when a subscription token is expired (no claude child ever spawns, reader threads stay alive). The deadlock wedges `asyncio.run(_drain_reader_threads(...))` in the executor thread for up to 7200 s at 87–91% CPU. Add `_drain_bounded()` in `claude_code.py`: runs the drain inside a daemon thread with a `threading.Event` + 90 s `done.wait()` budget. Replaces all 4 `asyncio.run(_drain_reader_threads(...))` call sites. `subprocess_pgroup.py` is untouched to minimise regression risk. 4 unit tests in `tests/unit/test_drain_bounded.py`. Fixes #728 Co-authored-by: Claude Sonnet 4.6 <[email protected]> * test(settings): harden #302 e2e coverage + add manual test plan (#716) Follow-up to PR #700 (issue #302). Adds 6 new Playwright tests and a manual test runbook to lift coverage from "navigation works" to "regression-safe + integration". New e2e tests (in src/frontend/e2e/settings-tabs.spec.js): F1. Every section appears under its expected tab — replaces the limited behavior 11 (4 of 13 sections) with full 13-section regression. Uses exact:true match to disambiguate "API Keys" from "MCP API Keys". F2. Parametric deep links — 4 ?tab= IDs not already covered by behavior 2 (general, access, integrations, agents). Round out the 5-ID matrix. F3. MCP Keys CRUD integration — drives create + revoke through the UI, verifies state via API queries. Uses CLEANUP_PREFIX 'test-302-e2e- cleanup' for the test key name. afterEach hook + DELETE response assertion cleans up; manual recovery one-liner documented in the file header in case the hook somehow misses (zero stray rows observed in local runs). F4. Admin login fetches /api/users/me — pins the new fetchUserProfile() wiring from auth.js so a future refactor can't silently break role- based UI gating. F5. Re-click active tab does not push duplicate history — guards against regressing the early-return guard in selectTab(). F6. Non-admin does not see MCP Server URL section in MCP Keys tab — confirms the inner v-if="isAdmin" gate (independent of the tab-level v-if) works. Test infra changes - Whole spec file marked test.describe.configure({ mode: 'serial' }) because the CRUD test creates real keys and parallel workers race against the McpKeysTab list re-fetch + ensureDefaultKey side effects in headless mode. Total runtime: ~12s serial vs ~5s parallel — acceptable. - New cleanupTestMcpKeys helper used by afterEach hook. - New CLEANUP_PREFIX constant exported in the file header comment with the docker-exec recovery one-liner. Manual test plan (docs/testing/302-settings-tabbed-layout-manual-test- plan.md): 7-section runbook covering everything the e2e suite covers plus the things only humans can verify (visual UX, real non-admin session via DevTools localStorage spoof, /api-keys bookmark redirect demo). ~25 minutes for full pass. Verified - 23/23 settings-tabs.spec.js pass in 12.2s - 0 stray test rows in mcp_api_keys after a full run - No backend, docker, or CI changes — this is purely test-infrastructure hardening for a frontend-only feature Refs #302 Co-authored-by: Pavlo <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(slack): startup recovery supervisor for transient initial-connect failures (#708) (#719) When ALL initial Socket Mode connect attempts fail at backend boot (transient DNS slowness, edge throttle, etc. exceeding the 10s connect ceiling), `start()` now spawns a recovery supervisor task that retries in the background with the watchdog's exponential backoff (60→120→240→ 300s cap) until at least one client connects, then graduates to the per-client watchdog model. Pre-fix behavior: silent permanent-offline state until manual restart. The watchdog model assumed at-least-one-connection, leaving no path out of "zero contexts" once initial gather failed. Behavior matrix: - All initial succeed → no supervisor, watchdogs run (no overhead change) - Partial succeed → no supervisor, degraded mode unchanged - All initial fail (transient) → supervisor retries, exits on recovery - All initial fail (bad creds) → supervisor retries forever; backend HTTP stays fully responsive; ERROR "STARTUP UNREACHABLE" log fires after 3 consecutive failures for operator paging - Token format invalid (no xapp- prefix) → existing early-return path preserved, no supervisor (permanent error must not spin) - stop() called mid-supervisor → supervisor cancelled cleanly, await propagates CancelledError, no zombie task main.py: stop nilling _slack_transport when initial connect fails so the supervisor task isn't orphaned. Test coverage: 10 new unit tests (TestStartupRecoverySupervisor) + 1 flipped existing (test_start_aborts_when_all_clients_fail → test_start_spawns_supervisor_when_all_clients_fail). 65/65 pass. End-to-end smoke verified against running backend with extra_hosts DNS poisoning + bad-credentials scenarios; backend HTTP confirmed responsive throughout. Co-authored-by: Pavlo <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(config+sec): align TRINITY_PASSWORD across compose files + close changeme propagation paths (#692) - docker-compose.yml: TRINITY_PASSWORD now reads ADMIN_PASSWORD directly - docker-compose.prod.yml: switch to fail-loud ${ADMIN_PASSWORD:?...} on both backend and mcp-server - .env.example: collapse duplicate FRONTEND_URL; add GOOGLE_API_KEY, LOG_*, TRINITY_DATA_PATH, HOST_TEMPLATES_PATH - src/mcp-server/src/server.ts: drop || "changeme" fallback; throw on startup when MCP_REQUIRE_API_KEY=false and no usable credential - scripts/deploy/gcp-deploy.sh: refuse to deploy if ADMIN_PASSWORD is unset or literally "changeme" - deploy.config.example: drop "changeme" default - docs: update mcp-orchestration flow, single-server deploy guide, TEST_REPORT historical note, feature-flows index Default MCP_REQUIRE_API_KEY=true mode is unaffected. Closes #692 Co-Authored-By: AndriiPasternak31 <[email protected]> Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(tests): green the unit-test suite (closes #660) (#714) Resolves all 49 failures + 2 collection errors in `uv run pytest tests/unit/`. Final state: 754 passed, 1 skipped, 0 failed across 3 consecutive runs. Production schema/migrations and backend code are untouched. Failure groups fixed: - A (14): missing backend deps in tests/requirements-test.txt - B (4): test_telegram_webhook_backfill missing platform_audit_service stub - C (2): test_fleet_sync_audit S7 partial UNIQUE index prevents seeding duplicate-binding state - D (28): test_file_upload cascading pollution from test_backlog tmp_db + test_slack_watchdog sys.modules stub - E (4+1): test_git_status_dual_ahead_behind inverted args + agent_server package shadow - F (1): test_agent_server_auto_sync same package shadow as E Also adds slackify-markdown>=0.2.0 floor for supply-chain consistency. Co-Authored-By: Andrii Pasternak <[email protected]> Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(schema): backfill schema.py to match migrations.py reality (#691) (#712) Adds 11 tables, 14 columns, and ~22 indexes that existed only in migrations.py to schema.py, restoring it as a faithful reference for the database (Architectural Invariant #3). Mechanical and additive. Migrations are append-only history. Existing databases unaffected — every new statement uses IF NOT EXISTS. Tables added: subscription_credentials, agent_notifications, subscription_rate_limit_events, slack_workspaces, slack_channel_agents, slack_active_threads, telegram_bindings, telegram_chat_links, telegram_group_configs, whatsapp_bindings, whatsapp_chat_links. Columns added: agent_ownership (full_capabilities, max_backlog_depth, voice_system_prompt), schedule_executions (source_user_id, source_user_email, source_agent_name, source_mcp_key_id, source_mcp_key_name, claude_session_id, queued_at, backlog_metadata, fan_out_id), agent_schedules (webhook_token, webhook_enabled). Indexes added: subscription, notification, rate-limit, multi-agent slack, telegram, whatsapp, plus partial indexes for execution backlog (idx_executions_queued), retry (idx_executions_pending_retry), fan-out (idx_executions_fan_out), webhook tokens (idx_schedules_webhook_token), and proactive sharing (idx_agent_sharing_proactive). Verified: name-only and strict DDL parity scripts both pass with zero missing and zero different entries. test_migrations.py 17/17. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * feat(metrics): add /metrics skill for engineering analytics Ports the metrics skill from feature/704-705-voice-bugs to dev. Provides velocity, cycle time, bug ratio, and backlog health reporting via GitHub Issues + project board data. Includes the 2026-05-07 baseline report generated during initial development. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(validation-spec): add F-011/F-012/F-013 file structure checks for architecture, requirements, and changelog docs Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * docs(arch+validation): add data-exchange principle and composability checks Add governing principle #7 to TARGET_ARCHITECTURE.md: data exchange over conversation chains as the default multi-agent composition pattern. Add Composability category (I-001–I-005) to agent-validation-spec.md: checks that agents declare output contracts, produce structured file-based outputs for downstream consumers, and enforce contracts via post-check hooks. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * chore(metrics): code-health baseline 2026-05-08 @ 1eb7b5e * feat(code-health): add /code-health skill and weekly schedule on trinity agent - Add code-health skill playbook (.claude/skills/code-health/) - Run first code health baseline: top hotspot routers/chat.py (score 6105), 14 size violations, 6 stale TODOs, 0 circular imports - Commit baseline to docs/metrics/code-health-baseline.json - Document /code-health in DEVELOPMENT_WORKFLOW.md (checklist + commands table) - Schedule weekly Monday 09:00 UTC autonomous run on trinity agent Co-Authored-By: Claude Sonnet 4.6 <[email protected]> * fix(git): use per-agent PAT fallback in github sync, helpers, and lifecycle (#735) (#739) Three callsites were ignoring per-agent GitHub PATs and calling the platform-only get_github_pat() directly, causing silent clobber of per-agent PATs on container restart and preventing agents with per-agent PATs from initializing git sync without a platform PAT also configured. - routers/git.py initialize_github_sync: get_github_pat() → get_github_pat_for_agent(agent_name) - services/agent_service/helpers.py check_github_pat_env_matches: platform PAT → agent-effective PAT (prevents spurious recreation) - services/agent_service/lifecycle.py: platform PAT update → agent-effective PAT (prevents per-agent PAT clobber on restart) 19 unit tests added (static callsite checks + logic tests for fallback chain). Fixes #735 Co-authored-by: Claude Sonnet 4.6 <[email protected]> * fix(schedules): prevent accidental re-enable via MCP update and expose retry config fields (#741) (#742) Two silent bugs in MCP schedule update path: 1. Terse `enabled` description in `update_agent_schedule` led AI models to include `enabled: true` when updating unrelated fields, re-enabling schedules the user had intentionally disabled. Added explicit warning to omit the field unless changing state is intended. 2. `ScheduleUpdateRequest` was missing `max_retries` and `retry_delay_seconds`, so Pydantic's `exclude_unset=True` silently dropped those fields before they could reach `db.update_schedule()`. Co-authored-by: Claude Sonnet 4.6 <[email protected]> * fix(subprocess): replace os.stat() with os.readlink() in orphan pipe scan (#728) (#747) os.stat() on /proc/pid/fd/N follows the symlink to the pipe inode and acquires an inode lock at the kernel level. On a D-state process this lock may be held indefinitely, causing _kill_orphan_pipe_writers to silently exit its 10 s daemon-thread cap without ever finding the orphan writer — leaving the reader thread permanently leaked. os.readlink() reads the symlink target string "pipe:[inode]" from the proc pseudo-filesystem's own metadata WITHOUT following the symlink and WITHOUT acquiring any inode lock. Safe on D-state processes. Changes: - Replace os.stat() + fdinfo flags check with os.readlink() + "pipe:[N]" match - Add our_pid = os.getpid() self-skip (handles our_pgid=None edge case) - Remove fdinfo write-flag check (no longer needed once self is excluded) Regression test: TestKillOrphanPipeWriters.test_kills_orphan_even_when_stat_raises_dstate_simulation monkeypatches os.stat to always raise OSError, verifies orphan is still found and killed. Would have FAILED against the old implementation. Complements the _drain_bounded 90 s cap from PR #730. Co-authored-by: Claude Sonnet 4.6 <[email protected]> * docs(adr): evaluate Claude Agent SDK migration (#409) (#743) Recommends DEFER. SDK does not close #285/#407 by design and introduces five observability regressions plus an unverified subscription-token auth path. Proposes completing #122 (split) on the current architecture instead, with a rescoped 6-module target that matches today's 2137-line file. Closes #409 * ci(unit-suite): add per-PR + nightly regression gates (#715) (#744) * ci(unit-suite): add per-PR + nightly regression gates (#715) Two GitHub Actions workflows that surface the dev-merge residual class of regressions earlier than reviewer time: - backend-unit-test.yml — per-PR gate. Runs the unit suite under three pytest-randomly seeds against both the PR's base-branch tip and its merge commit, then diffs the union of failing test IDs. Fails the check on new failures or missing JUnit XML (fail-closed on infra). - backend-unit-nightly.yml — cron 06:00 UTC sweep over open PRs targeting dev. Three jobs: discover (RO) → test (RO, no creds, runs untrusted PR code via pull/N/head) → comment (write, no checkout). Posts sticky regression comments via github-script. scripts/ci/diff-pytest-failures.py — JUnit XML diff utility. Tracks <failure> and <error> kinds separately, fails closed on missing or unparseable XML, ships an in-process --self-test mode (8 cases) that the workflows run before the real diff. pytest-randomly is installed in-workflow only — adding it to tests/requirements-test.txt would silently randomize tests/run-core.sh because pytest auto-discovers installed plugins. Out of scope (per #715): fixing the 34 failures + 17 errors in the existing baseline. Those belong to the #660 follow-up; this gate is the entry point that surfaces them. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * ci(unit-suite): stash diff script before base-side checkout (#715) The base-side matrix legs were failing fast because scripts/ci/diff-pytest-failures.py only exists on the PR branch — when we git switch --detach onto the target-branch tip for the base run, the file disappears and the self-test step exits 2 ("No such file"). Fix: copy the script to ~/.ci-tools/ in the merge-commit checkout before any side switch, then run the self-test against the stashed copy. The pytest run itself doesn't need the script (it just produces JUnit XML); only the diff aggregator job consumes it, and that job checks out the PR branch fresh. Caught immediately by the gate validating itself on PR #744 — exactly the dev-merge-residual feedback loop the gate is meant to provide. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * ci(unit-suite): harden nightly comment loop against marker quoting and bad JSON (#715) Two issues from the focused SQL/race/auth review: 1. Sticky-comment finder lacked an author filter. A user reply that quoted the `<!-- nightly-unit-suite -->` marker would match `existing.find(...)`, and the subsequent updateComment call would 403 (bots can only edit their own comments) — leaving the PR without a fresh sticky comment. Now requires `c.user.type === 'Bot'` or `github-actions[bot]` author. 2. One malformed status JSON in the matrix would JSON.parse-throw out of the for-loop, killing comment posting for every subsequent PR in the same nightly run. Each iteration now lives in its own try/catch and logs a per-PR warning on failure. Both caught before nightly ever fired in production. Per-PR gate is unaffected (the bug was only in the nightly comment job). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * ci(unit-suite): use trusted dev-branch diff script for nightly tamper-evidence (#715) Defense-in-depth from the /cso --diff audit. Previously the nightly's self-test and regression-diff steps invoked scripts/ci/diff-pytest-failures.py from the merged-in PR workspace, meaning a malicious PR could ship a modified diff utility that always exits 0 and produces a false "✅ Nightly clean" sticky comment. Fix: stash the trusted copy from origin/dev before the merge, then invoke ~/.ci-tools/diff-pytest-failures.py for both --self-test and the real regression diff. The stash step happens at position 2 (right after the dev checkout, before pull/N/head fetch + merge), so the file copied is always the unmerged dev-branch version regardless of PR contents. The per-PR gate is intentionally not hardened the same way — that gate is a self-check, and a PR that modifies its own diff script shows up conspicuously in the diff for the human reviewer. The nightly is the cross-PR signal that warrants tamper-evidence. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * ci(schema): schema.py vs migrations.py parity gate (#713) (#745) * ci(schema): add schema.py vs migrations.py parity gate (#713) Adds a pytest unit test (`tests/unit/test_schema_parity.py`) plus a path-filtered GitHub Actions workflow (`.github/workflows/schema-parity.yml`) that fails any PR whose `init_database()` boot-path produces tables, columns, indexes, or triggers that aren't declared in `init_schema()` alone. The check builds two in-memory SQLite snapshots — `init_schema()` only, and the full `migrations -> init_schema -> migrations` lifecycle from `database.py:139-164` — and diffs them. The full lifecycle on an empty DB is required so short-circuit migrations like `_migrate_audit_log_table` (`migrations.py:1356-1364`, returns early when `audit_log` exists) can't hide schema.py omissions of indexes/triggers. Per-column TYPE comparison via PRAGMA table_info also catches drift where schema.py and migrations disagree on a column's type — a class of bug that name-only diffing would miss. Out of scope, documented in the test docstring: reverse-direction drift (schema.py edited without a migration), constraint-level drift (NOT NULL / DEFAULT / FK / CHECK), trigger BODY drift. Future work. Closes the prevention loop for #691: PR #712 backfilled 11 tables, 14 columns, and ~22 indexes that had drifted out of schema.py over time. This gate stops the same drift from re-accumulating. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * chore(schema-parity): catalog new test + harden CI key placeholder (refs #713) - .claude/agents/test-runner.md: add test_schema_parity.py under System & Deployment, plus a Recent Test Additions (2026-05-09) entry with the full design rationale (full init_database() lifecycle, PRAGMA-based type comparison, triggers in snapshot, out-of-scope notes). - .github/workflows/schema-parity.yml: replace the invalid-hex CREDENTIAL_ENCRYPTION_KEY placeholder ("test-ci-only-...") with a valid 64-char zero-hex string. The key is never accessed on an empty in-memory DB, but if a future code path ever calls encrypt(), the workflow now produces a real test failure rather than a confusing "Invalid encryption key format" crypto error. Refs #713 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * docs(schema-parity): inline maintainer note about required-status-check timing Resolves /validate-pr suggestion: the warning about NOT adding this job to branch-protection required-status-checks on day one was only in the PR body. Move it inline as a header comment in the workflow YAML so it stays visible to anyone reading the file directly (and survives long after the PR is merged). The risk is a future module move bypassing the path filter and silently skipping the gate, then bricking unrelated PRs that don't touch DB files. Leaving it optional + self-skipping is the safe default. Refs #713 * ci(schema-parity): widen path filter to include src/backend/database.py The parity test mirrors init_database()'s migrations->schema->migrations lifecycle (database.py:139-164), but the path filter only watched src/backend/db/**. A future re-ordering of init_database() itself would slip past the gate. Add src/backend/database.py to both pull_request and push paths so changes to the lifecycle trigger the check. Refs #713 Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * fix(circuit-breaker): Redis-coordinated state with backoff + dormant (#631) (#698) Pre-fix the circuit breaker lived in a per-process dict in agent_client.py. Two uvicorn workers each tracked their own state, each probed dead agents every 30s, and `monitoring_service` (which uses raw httpx and never consulted the circuit at all) wrote 4 health_check rows per cycle for the same dead agent. With a multi-hour outage that produced 400+ failures, hundreds of concurrent SQLite writes from two workers, and the lock contention cascaded into WebSocket auth → UI unresponsive for everyone. Fix shape: 1. State moves into Redis (`agent:circuit:{name}` hash) with atomic Lua scripts for record_failure / record_success / allow_request. Single source of truth across workers; "Circuit OPENED" log fires exactly once per cluster transition because the script returns prior+new state and only one worker observes the closed→open boundary. 2. Exponential backoff on the open state — 30s → 60s → 120s → 240s, capped at 300s. After 10 consecutive open-state probes without recovery (~40min of attempts), the circuit transitions to **dormant** and stops probing entirely. 3. Probe-lock (`SET NX EX 10` on `:probe-lock` key) ensures only one worker fires the half-open probe per cooldown window. 4. `monitoring_service.check_network_health` now feeds its result into the circuit (record_success on 2xx-4xx, record_failure on connect errors / timeouts / 5xx) — previously its failures were invisible to the circuit. `perform_health_check` short-circuits to a synthetic AgentHealthDetail when the circuit is dormant: no httpx calls, no DB writes. This is the cure for the SQLite-contention root cause. 5. Operator hooks: `force_circuit_dormant(agent, reason)` and `reset_circuit(agent)`. The autonomy toggle calls them (disable→dormant, enable→reset) — disabling autonomy now stops probing for that agent (AC#5). The manual POST /api/monitoring/agents/{name}/check resets first so the probe actually runs (the documented dormant-recovery path). Fail-open: when Redis is unreachable the breaker degrades to "always allow request" — matches the rate-limiter pattern in webhooks.py and keeps a Redis blip from breaking agents that are otherwise healthy. Tests: - tests/integration/test_circuit_breaker.py — 18 tests against real Redis: state machine, backoff curve, dormant entry/exit, probe-lock cross-worker semantics, transition-logged-once, operator hooks, scan correctness, fail-open. - tests/unit/test_monitoring_dormant_skip.py — 5 tests verifying the perform_health_check bail-fast path: when dormant, no DB writes; when not dormant, the full 4-row write path runs as before. - tests/unit/test_circuit_breaker.py — kept the connection-pool and exception-hierarchy tests; the state-machine tests moved to integration since they need real Redis. Live verified end-to-end: killed agent-server inside container, drove through closed → open → dormant via repeated perform_health_check calls, confirmed 0.5ms bail-fast in dormant state with zero new DB rows; toggled autonomy off→on and observed dormant→closed transitions. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]> * feat(#411): canary invariant harness Phase 1 (S-01, E-02, L-03) (#653) * feat(#411): canary invariant harness Phase 1 (S-01, E-02, L-03) Implements the canary harness from #411 that catches the bug class behind PRs #378, #403, #129, #226 — race conditions and cross-component state drift between Redis × SQLite × agent registries that unit tests miss. Architecture (per design discussion in PR comments): - Deterministic library (src/backend/canary/) — pure-function checks shared between the watcher and the on-demand admin endpoint. No LLM reasoning anywhere — same snapshot in, same violations out. - Watcher service (services/canary_service.py) — 5-min APScheduler-style loop modeled on cleanup_service.py. Disabled by default; enable on staging/dev with CANARY_ENABLED=1. - Fleet manifest (config/canary-fleet.yaml) — synthetic load via the existing /api/systems/deploy mechanism. Without traffic the harness reports trivially-green cycles. Phase 1 invariants: - S-01 (slot–row bijection) — Redis ZRANGE vs SQL running rows; drain sentinels filtered. Critical severity. - E-02 (no phantom reversal) — terminal executions stay terminal. Phase 1 uses Redis-backed state comparison instead of Vector log diff for simplicity. Critical severity. - L-03 (delete cascades) — orphan-row scan across cross-cutting tables (agent_sharing, agent_schedules, schedule_executions [non-terminal], agent_skills, agent_tags, agent_shared_files, agent_public_links, pending operator_queue / access_requests, agent-scoped mcp_api_keys, active chat_sessions) plus orphan agent:slots:* Redis key scan. Critical for active-orchestration orphans, major otherwise. Persistence + API: - canary_violations table (migration 34, schema in db/schema.py). - GET /api/canary/violations + /violations/stats + /violations/{id} — admin-only read paths over the persisted history. - POST /api/canary/run-cycle — admin-only on-demand trigger; delegates to the same CanaryService.run_cycle() the background loop calls. Notifications: - One green→red transition emits one notification via db.create_notification(notification_type='alert', category='canary'). - Severity → priority: critical → urgent, major → high, minor → normal. - Continuing-red cycles do not re-notify; the row in canary_violations is the trend signal, the bell is the "now" signal. Tests: - 27 unit tests in tests/test_canary_invariants.py covering CanaryOperations CRUD/filters/stats, snapshot collector behaviour, each invariant's holds-and-fires cases, the L-03 critical/major severity split, and the runner registry. Smoke-test recipe (Option 1 — orphan SQL row, no code changes): # 1. Set CANARY_ENABLED=1 and restart backend (creates canary_violations # table via migration; starts the watcher). # 2. Deploy the fleet: curl -X POST -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "$(jq -Rs '{manifest: .}' < config/canary-fleet.yaml)" \ http://localhost:8000/api/systems/deploy # 3. Ba…
…kend resource (#1083) (#1273) * feat(exec): apply_result extraction + inert hardened result-callback endpoint (#1083 PR1) PR1 of fire-and-forget dispatch — a pure refactor plus a fully-hardened, fail-closed result-callback endpoint that rejects all live traffic until PR2 sets the durable async marker. Zero behavior change to current execution paths. - Extract TaskExecutionService.apply_result — the single terminal applier shared by the inline sync path and the future result-callback. Moves the SUCCESS and the httpx #678-salvage FAILED terminal writes (sanitize, cost rollup, context, CAS write, activity completion, breaker outcome, optional slot release) behind one normalized TerminalEnvelope. Every side effect is gated on the CAS bool (Codex #1/#12): a CAS-lost write does nothing — no double activity close, breaker churn, or slot drain. Producer-side classification (SUB-003, error-code, timeout-terminate) stays in execute_task. - slot_service.release_slot: gate the BACKLOG-001 drain on the ZREM result so a replayed/no-op release can't admit a backlog row past max_parallel_tasks (Codex #12). Every legitimate drain trigger removes a present member. - POST /api/agents/{name}/executions/{id}/result — agent's own MCP-key auth (mirrors heartbeat authorize_heartbeat) + ownership + a durable async-marker gate (RUNNING rows must carry claude_session_id='dispatched_async', else 409) + idempotent replay (terminal → {replayed:true}) + body-size 413 caps. - db.get_open_activity_id_for_execution: filtered by related_execution_id AND chat/schedule_start AND state='started' so a shared-eid tool_call row can't be cross-closed (Codex #8). mark_execution_dispatched gains async_dispatch=True. - config: DISPATCH_ASYNC flag + ASYNC_DISPATCH_ELIGIBLE_TRIGGERS={schedule,webhook} + dispatch_async_eligible(); compose/.env forwarding (backend-only, default off). Tests: apply_result golden + CAS-gate matrix, callback auth/ownership/replay/ marker/size matrix, DB seams; existing CAS-gate + #678 auto-retry parity green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(exec): backend cutover — async dispatch-and-return + lease reaper (#1083 PR2 lane A) Backend half of the fire-and-forget cutover (agent-server half follows). Inert until DISPATCH_ASYNC=true AND a Claude-runtime agent on a new base image ACKs 202. - execute_task: for an async-eligible trigger ({schedule,webhook}) under DISPATCH_ASYNC, send async_result=true, write the durable 'dispatched_async' marker, and on a 202 ACK return RUNNING/dispatched_async immediately, handing the slot lease to the result callback (skip the `finally` release). Any non-202 response (200 / old image / non-Claude runtime) falls through to today's synchronous handling — the safe mixed-fleet fallback. The runtime gate is enforced agent-side (decision 5). - cleanup_service lease reaper: after fail_stale_slot_execution, tag the FAILED message with the lease_expired code and close the open dispatch activity via the filtered get_open_activity_id_for_execution (the absent fire-and-forget coroutine `finally` no longer closes it). Adds TaskExecutionErrorCode.LEASE_EXPIRED. - Finding 1: _sweep_stale_executions now uses each agent's timeout+SLOT_TTL_BUFFER window (mark_stale_executions_failed gains agent_timeouts+buffer_seconds) instead of the flat 120-min default, so a legitimately-running max-timeout async turn isn't failed ~5 min before the slot reaper / canary E-01. agent_timeouts=None reproduces the prior flat behaviour exactly. Tests: dispatch-return matrix (202→RUNNING/no-release, non-202 fallback, trigger scope), stale-sweep per-agent boundary REGRESSION (timeout+buffer±ε), lease activity close; existing CAS-gate / cleanup / observability tests green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(agent): async-accept (202) + result-callback report/persist/retry (#1083 PR2 lane B) Agent-server half of the fire-and-forget cutover. When the backend sends async_result=true AND this agent runs the Claude runtime, /api/task accepts with 202 and runs the turn in a detached task that reports the typed terminal to the backend's result-callback endpoint. Inert for non-Claude runtimes / old behaviour (async_result defaults false). - services/result_callback.py: try_spawn_async gates on async_result + Claude runtime + execution_id + callback creds (else the caller runs synchronously — the non-202 fallback). _run_and_report runs the headless turn, builds a typed envelope (success → completed; HTTPException → status-mapped error_code/ terminal_reason, with metadata salvaged from the structured 502 body), persists it atomically to ~/.trinity/pending-results/<eid>.json, and delivers it with capped backoff up to the slot-lease deadline (dispatch + timeout + SLOT_TTL_BUFFER), deleting on a 2xx or a permanent 4xx. A strong-ref _inflight set defeats the asyncio weak-ref GC footgun. - main.py: startup sweep re-sends any envelope left on disk by a crash/restart, so completed work isn't lost to a phantom LEASE_EXPIRED (a late SUCCESS still overwrites it via the backend CAS). - chat.py /api/task: 202 branch before the synchronous path; models.py: ParallelTaskRequest.async_result flag. v1 limitation (T8 / #1201, P2 fast-follow): only the 502 empty-result failure path carries cost/context metadata on the async callback; 504/503 write a null-cost row until execute_headless_task exposes ctx.metadata on those paths. Tests: envelope mapping, eligibility gating, persist/resend roundtrip, and the retry-to-deadline delivery loop (2xx, permanent-4xx no-retry, transient-5xx retry, deadline). agent-server regression subset green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(architecture): document fire-and-forget dispatch subsystem + result-callback endpoint (#1083) architecture.md gains a "Fire-and-Forget Dispatch (#1083)" cross-cutting block (apply_result CAS-gating, durable async marker, callback endpoint, agent-side persist/retry/sweep, lease reaper + stale-sweep buffer fix, v1 boundaries), the result-callback endpoint row, and a pointer from the task_execution_service catalog entry. feature-flows index gains the #1083 Recent Updates row. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(exec): let a late SUCCESS callback correct a reaper LEASE_EXPIRED (#1083, Codex #2) The result-callback's idempotent-replay short-circuit fired for ALL terminal statuses, which would block a genuinely-late SUCCESS callback from reaching the CAS after the lease reaper had already FAILed the row (LEASE_EXPIRED) — directly contradicting the plan's accepted "SUCCESS overwrites a phantom FAILED" behavior. Now only the authoritative terminals (SUCCESS/CANCELLED/SKIPPED) short-circuit as a replay ACK; a FAILED row falls through to apply_result, whose CAS lets a late SUCCESS overwrite it (a duplicate FAILED is harmlessly CAS-blocked → no side-effect re-run). The async-marker gate still rejects a FAILED *sync* row (marker != dispatched_async), so the cross-path guard holds for terminals too. +2 callback tests (FAILED-async fall-through, FAILED-sync 409); architecture.md clarified. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(agent): validate execution_id charset before async dispatch (#1083) Defense-in-depth: result_callback builds a pending-results filesystem path (~/.trinity/pending-results/{execution_id}.json) and the backend callback URL from the backend-supplied execution_id. Add a strict allowlist guard (_SAFE_EXECUTION_ID = ^[A-Za-z0-9_-]{1,128}$) enforced at try_spawn_async — a value outside the token_urlsafe / UUID charset now falls back to synchronous handling and never reaches the path build or the callback URL. Adds parametrized unit tests and archives the CSO --diff audit report for the branch. Refs #1083 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(agent): containment barrier at the path-build sink (#1083, CodeQL) CodeQL py/path-injection flagged _persist/_delete: a caller-side regex guard in try_spawn_async is not recognized as a barrier for the callee sink. Move the sanitizer into _pending_path itself — resolve() + is_relative_to() containment against _PENDING_DIR (mirrors jsonl_recovery), raising ValueError on escape. The regex stays as the belt; this is the suspenders on the path-build dataflow, so a hostile execution_id can never traverse out of the pending dir. Refs #1083 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(agent): use os.path.basename to sanitize the pending-result path (#1083, CodeQL) CodeQL py/path-injection did not accept resolve()+is_relative_to() as a barrier and still flagged the path build in _pending_path/_persist/_delete. Switch to the canonical CWE-022 sanitizer: os.path.basename strips any directory components from execution_id before the join, so the write is confined to _PENDING_DIR. The resolve()+is_relative_to() containment stays as suspenders; the regex guard in try_spawn_async remains the belt. Refs #1083 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(agent): adopt the #950 normpath+startswith path-containment guard (#1083, CodeQL) resolve()+is_relative_to() and os.path.basename were both ignored by CodeQL's py/path-injection model (same dead end #950 hit before switching). Mirror the guard that actually cleared the alert there: os.path.normpath collapses any '..', an inline startswith prefix-check confirms containment under _PENDING_DIR, and the normalized value is flowed downstream to write/replace/unlink. Raises on escape; the try_spawn_async regex belt still rejects such ids upstream. Refs #1083 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
…y/citation accuracy (#1358) * docs(#945): correct postcard result-reporting + taxonomy/citation accuracy Audit-driven corrections to the actor-model postcard (the deliverable for #945, which originally landed via PR #1293/#946 with no #945 linkage): - Fix factual error: schedule_execution_completed IS emitted by the scheduler (src/scheduler/service.py) for schedule-triggered runs, but no agent-facing path consumes it and it's not emitted on the agent->agent MCP path the #946 pilot uses. Prior text wrongly said "never emitted"; the polling conclusion is unchanged. - Pin the shipped TaskExecutionErrorCode enum explicitly and note the contract adds OOM/MAX_TURNS on top, so the divergence is intentional. - Fix demotion-map citation: session_id unifies #8-#12 (not #8-#13); #13 inject_result is causation_id; drop the non-existent "continue_session". Closes #945 Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(#945): correct stale ParallelTaskRequest field count (15 -> 14) The model has 14 fields today (src/backend/models.py:97-112), not 15 — the demotion map's own code block already listed 14. Fix the prose counts ("13 of its 14 [optional]", "13 silent siblings"), the stale line-ref (:84-99 -> :97-112), and the TARGET_ARCHITECTURE mirror of the claim. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
* fix(security): credential encryption key rotation (#267) CSO finding #3: CREDENTIAL_ENCRYPTION_KEY (AES-256-GCM master for all .credentials.enc + 8 DB token columns, Invariant #12) had no rotation path — changing it bricked every existing secret. Adds an online, zero-downtime rotation mechanism: - CredentialEncryptionService gains an optional decrypt-only secondary key (CREDENTIAL_ENCRYPTION_KEY_SECONDARY = previous key): old-key ciphertext keeps opening while new writes use the primary. Single-key deploys unchanged. - rewrap(envelope) re-encrypts onto the primary (works for DB tokens AND v2 .credentials.enc archives — same envelope). - scripts/deploy/rotate-credential-key.py sweeps the 8 DB secret columns (dry-run default, --apply to write; legacy-plaintext rows skipped, not corrupted; idempotent). - Runbook docs/migrations/CREDENTIAL_KEY_ROTATION.md; compose forwards the secondary var; .env.example documents it. Deferred (separate issues, as scoped): moving the key off a plaintext env var (Docker/Swarm secrets / external manager) and an in-container .credentials.enc re-encryption pass (those migrate on next credential op via the secondary key). Related to #267 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(ci): rename SECRET_COLUMNS to satisfy CodeQL clear-text-logging (#267) The list name SECRET_COLUMNS and the 'AS secret' query alias tripped CodeQL's sensitive-data-source name heuristic, tainting the loop vars (table/pk/col) so every progress print() flagged py/clear-text-logging (3 high-severity FPs). No secret value was ever logged. Rename to ENCRYPTED_COLUMNS / enc_value to break the heuristic. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…auth (trinity-enterprise#77) (#1469) * feat(webhooks): schedule webhook config UI + optional HMAC signature auth (trinity-enterprise#77) Public schedule webhooks (WEBHOOK-001) were backend-only — mint/rotate/revoke was REST-API-only and a leaked URL token was the entire credential. This adds a first-class Schedules-tab configuration surface and an optional signature layer. Backend (the net-new work is the auth layer): - `services/webhook_signature.py` — HMAC-SHA256 over the raw body, verified constant-time against a per-webhook secret in `X-Trinity-Signature: sha256=…`. - Per-schedule signing secret: minted `whsec_…`, returned to the operator exactly once, persisted only as an AES-256-GCM envelope (Invariant #12). New columns `agent_schedules.webhook_secret_encrypted` + `webhook_auth_enabled` (dual-track migration: SQLite `agent_schedules_webhook_auth` + Alembic 0014; schema.py + tables.py updated). - `POST/DELETE /api/agents/{name}/schedules/{id}/webhook/secret` enable-rotate / disable signing (AuthorizedAgent — aligns with schedule management, the access-control decision settled per the AC). GET reports auth_enabled/has_secret (never the secret). Rotating the URL or revoking clears the secret. - Public trigger (`routers/webhooks.py`): when auth is on, verify the signature after the body is read + size-capped — FAIL-CLOSED (401 missing/invalid, 500 on an unreadable stored secret, never a silent bypass). Off by default → existing token-in-URL webhooks unchanged. Frontend (`SchedulesPanel.vue`): per-schedule Webhook panel — enable, masked/ revealable URL, one-click Copy URL, ready-to-paste example curl, rotate/revoke (with warnings), enable/rotate/disable signature, secret shown exactly once. Dark-mode aware. Docs: user-doc snippet (configure + secure a webhook, incl. an openssl signing example) + architecture (endpoints, DDL, signature-auth behavior). Tests: `test_77_webhook_signature.py` (helper: valid/tampered/wrong-secret/ missing-header/empty-body, prefix-optional) + `test_77_webhook_secret_db.py` (secret lifecycle on db_harness: mint-once, ciphertext at rest, status, trigger- path decrypt, URL-rotate/revoke clear, secret rotation). Updated the #1424 hardening test double for the new model fields. 24 passed. Also verified live against real Redis + SQLite + AES-256-GCM (mint→encrypt→trigger-path decrypt→ signature verify round-trip). MCP tool (stretch) deferred. Related to trinity-enterprise#77 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(webhooks): reconcile unit fakes/assumptions with the merged #1422 dedup change Two semantic conflicts with #1437 (merged after this branch was cut) that git merges cleanly but pytest doesn't: - test_1422_webhook_idempotency._FakeSchedule gains the ent#77 webhook_auth_enabled/webhook_secret_encrypted attributes, matching the real Schedule model, so the new signature gate doesn't AttributeError. - test_1424 small-body test now sends an explicit Idempotency-Key — since #1422 the idempotency short-circuit (its benign 409 probe) engages only for keyed calls. This failure pre-existed on dev; repaired here since this PR owns the file. All 4 webhook unit files: 28 passed. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
…se#162) (#1686) Let each user store a personal GitHub PAT so a non-admin can create an agent from a repo the shared admin token can't see. Agent creation now resolves per-agent -> owner's per-user (live) -> global, and each agent carries its creator's scope instead of the fleet-wide admin token. Shape A (create-time convenience): - users.github_pat_encrypted (AES-256-GCM, Invariant #12) + four accessors with DatabaseManager delegations; column kept out of the general user dict so it never rides /api/users/me. - resolve_github_pat(agent_name, owner_id) in settings_service returns (pat, tier); both crud.py create sites use it. Persist as the #347 per-agent PAT ONLY for tier in {per_user, fork}, never global, so a global-fallback agent keeps NULL and still receives admin rotation. - get_github_pat_for_agent relocated into settings_service (kills the service->router import, Invariant #1) and stays 2-tier per-agent -> global. The recreate/restart ladder never re-derives the per-user tier, so adding a PAT in Settings can't force-recreate a running agent (the #1560/#1557 recreate-storm class). - Self-service GET/PUT/DELETE /api/users/me/github-pat: token never echoed on read; honest 400 (GitHub rejected) vs 503 (unreachable); create's bare 500 becomes an actionable 400. - UserGitHubPatPanel.vue on the personal MCP Keys settings tab. - users column registered in rotate-credential-key.py; dual-track migration (SQLite + Alembic 0025 on head 0024). Out of scope: public-repo-no-PAT (#123), OAuth/GitHub App (#177), rotation fan-out to existing agents (fast-follow). Tests: real migrated-DB + real facade — resolution ladder, owner isolation, persist-only-user-tier, live column + encrypted round-trip, facade delegation, read-never-echoes; plus the load-bearing recreate-no-storm guard (proven to fail if the ladder goes 3-tier). Co-authored-by: Eugene Vyborov <[email protected]>
…1726) Per-user GitHub credentials (ent#162) shipped in the v0.8.5 payload documented only as architecture prose. RoE §1 requires the relevant requirements/ area file updated for a new capability — most of all for a stored user credential. - requirements/github.md §11.10 — the full capability: what it is + who sets it (self-service, owner-only 3 endpoints), the storage guarantee, and the load-bearing distinctions: * three-tier CREATE ladder (per-agent → owner's per-user LIVE → global) with tier provenance from resolve_github_pat; * persist carve-out — per_agent/per_user persist as the #347 per-agent PAT, global NEVER does, so a global-fallback agent keeps github_pat_encrypted NULL and PAT-propagation still reaches it on admin rotation (ent#162 Decision 2); * recreate/restart ladder stays 2-tier (per-agent → global) via get_github_pat_for_agent and never re-derives the per-user tier — so adding a personal token can't force-recreate a running agent; * never echoed on read (standing requirement, not just behavior); * AES-256-GCM envelope under Invariant #12 (column already listed there). - requirements/security.md §20.9 — the credential-storage-half cross-reference (stored user credential, Invariant #12, never-echoed, ownership-keyed) pointing at github.md §11.10 for the resolution mechanics. Grounded in the code (settings_service.resolve_github_pat / get_github_pat_for_agent, routers/users.py /me/github-pat), not paraphrased. Docs-only — no code/test change, safe during the v0.8.5 soak. Related to #1711 · ent#162 Co-authored-by: Claude Opus 4.8 <[email protected]>
…ial paths from name: (#1900) (#1935) * fix(templates): contain local: template id resolution on the read path (#1900) `GET /api/templates/{template_id:path}` handed `local:<name>` straight to `get_local_template`, which joined `<name>` onto the templates root with no validation. The `:path` converter permits `/`, so `local:../<x>`, `local:/<abs>/<x>` and a root-escaping symlink each read `<escaped-dir>/template.yaml` and echoed its contents in an authenticated 200. Reachable by any authenticated principal of any role — including an agent-scoped MCP key, so a prompt-injected agent qualifies. In a container the reachable set includes `/data/deployed-templates/<victim>`, where every user's uploaded template archive lands: a cross-tenant read. Two corrections to the issue's framing, both verified here: * it is NOT arbitrary file read — the filename is fixed (`template.yaml`), it must parse as a YAML mapping, and only a fixed key set is echoed. But those keys' VALUES are arbitrary YAML subtrees, not just strings. * `local:..` alone is not an existence oracle: a directory with no `template.yaml` returns the same 404 as an unknown id. Fix: `contained_template_dir(name, root)` — the two-step barrier the CREATE path has had since #950 (`crud._safe_local_template_path`), brought to the read path. A name allowlist runs BEFORE any path math (this is also what CodeQL recognises as a `py/path-injection` barrier; resolve-only was flagged high-severity twice on this codebase), then `resolve()` on BOTH sides plus `is_relative_to`. `str.startswith` is not equivalent — it passes the sibling escape `<root>-evil`. An escaping id returns `None`, so the router's 404 stays byte-identical to an unknown template: no error code, no path, no root name. A distinct error would be a NEW enumeration oracle, which is what #1759's single-sentence 404 exists to close. Rejections log at DEBUG, sanitized — the endpoint has no rate limit, so a per-rejection WARNING would be an authenticated log-flood primitive. The helper is public: the remote-template-registry work (trinity-enterprise#14) edits this same resolver family in this same module and should import it rather than copy it. Tests: every rejection test PLANTS a real `template.yaml` at the escaped location, because unpatched code returns `None` for any id whose target simply does not exist — a rejection test with nothing planted is green before and after and proves nothing. Each is labelled REPRO (verified red pre-fix) or HYGIENE (cannot be made red; contract only). The router guard lives in `tests/unit/` because no gating CI job collects `tests/test_templates.py`. `test_1900_containment_survives_a_symlinked_root` is the landmine guard for resolving both sides: a half-resolved variant passes all 130 pre-existing tests and only that test catches it. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(templates): stage .mcp.json from the validated template dir, not template name: (#1900) The second traversal sink, found by this issue's own AC #4 audit ("audit the by-name create path for the same join"). It is NOT the create path's `local:` id resolution — that has been contained since #950/#1759 via `crud._safe_local_template_path`, applied at both seams #1759 named. It is the create path's CREDENTIAL STAGING, which threw that validated path away and re-derived a directory from scratch: template_name = template_data.get("name", "") # untrusted mcp_template_path = templates_dir / template_name / ".mcp.json" `name:` comes from an uploaded template.yaml, so any `creator` reaches it via `deploy_local_agent`. `name: ../../data/deployed-templates/<victim>` read another tenant's `.mcp.json` — a credential-bearing file type under Invariant #12 — into the attacker's OWN agent, where they read it at leisure. A victim who hardcoded a token rather than a `${VAR}` placeholder leaks it. Assessed on its own axes, NOT inherited from the read sink: different trigger (`creator` role + an upload + an agent create, vs a bare authenticated GET) and a higher impact ceiling (credential values, not template metadata). Also P2, for different reasons. The derivation was also simply wrong. `name:` is not a directory name — 5 shipped templates declare a display string there ("Test Echo Agent"), so `local:test-echo` resolved to `<curated>/Test Echo Agent/.mcp.json`, which does not exist. That kills the "validate the name" framing: the value should not resolve paths at all. Fix is root-cause, not another guard: `_stage_config_files` already calls `_safe_local_template_path` itself for the `/template` bind decision, so the validated directory is available in the same function. Extract the two-root ladder as `_resolve_local_template_dir` and pass its result as `template_base_path`. The untrusted join is gone from the live path, and the #1759 "seams must agree" property becomes structural across all THREE seams (resolver, bind decision, credential stager) instead of two. Deliberately NOT threaded through `_TemplateResolution` or the return tuple: `_resolve_local_template` returns a 2-tuple that three existing tests depend on, two as monkeypatched `lambda config: ({}, None)` doubles — widening it breaks the test doubles, not just the callers. Its signature, its return arity, `_safe_local_template_path`, `_LOCAL_TEMPLATE_ROOTS`, and everything inside the CodeQL-sensitive `if template_yaml.exists():` block are untouched (#1793 had to revert exactly that reshape). The residual `template_base_path is None` arm is kept and made fail-closed: it is a public function with a `template_base_path=None` default, so a future caller can still reach it. It now contains through the same barrier as the id, which also absorbs a non-string `name:` — `Path(root) / 123` raised TypeError, i.e. an uncaught HTTP 500 during agent creation (the ent#128 bug class, one seam over). One disclosed behaviour change: a deploy-local template that BOTH declares `credentials.mcp_servers` AND ships a `.mcp.json` now gets `${VAR}` substitution, where the old curated-root lookup always missed. Verified no collision with `deploy._prepopulate_workspace_from_template`, which writes the archive's raw copy into the workspace volume: `startup.sh` copies `/generated-creds/.mcp.json` unconditionally (gated only on the directory existing) and AFTER the template-copy block (gated on `.trinity-initialized`), so the substituted file deterministically wins — which is the intended behaviour, the raw copy still carrying unsubstituted placeholders. Not one of the 26 shipped curated templates contains a `.mcp.json`, so the curated rows are provably unchanged. The crud seam tests are mandatory, not decorative: every service-level test calls `generate_credential_files` directly, so an "extracted but never wired" mistake leaves all of them green while deploy-local resolution silently regresses into the fallback arm. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: record the #1900 containment contracts for template id + credential staging Rule #1 (requirements before implementation) — `core-agent.md`: * §4.1 gains the **read-path resolution contract** as a sibling to the existing create-time contract: `GET /api/templates/{id}` resolves `local:<name>` through the same two-step barrier the create path has had since #950, and a failing name returns a 404 byte-identical to an unknown template (the #1759 non-disclosure rule). Records the deliberate, known asymmetry that `get_local_templates()` still enumerates by `iterdir()` and so could LIST a root-escaping symlink that detail and create both refuse — the listing is the outlier, and planting one needs local filesystem write access, not a request. * §4.3 records that the `credentials.mcp_servers` template lookup now resolves from the validated path rather than the template's own untrusted `name:` field, including the one disclosed behaviour change (deploy-local templates now get `${VAR}` substitution) and why the substituted file wins over the archive's raw copy. `architecture.md` gets one clause on the `templates.py` router catalog entry (the catalog rule caps entries at 2 lines, and no Cross-Cutting Subsystems block is warranted). A bug fix would normally be commit-message-only under the tiered-docs rule; the exception is that this ships a public, importable containment primitive in the exact module and resolver family the remote template registry (trinity-enterprise#14) will edit, and one catalog clause is the cheapest way that author finds it instead of copying the flaw. Not updated, deliberately: no feature-flow doc (no new vertical slice), no user docs (no user-visible change for honest callers), no schema/migration (no DB change, so the dual-track SQLite/Alembic rule does not apply). Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(feature-flows): sync template-processing + local-agent-deploy for #1900 `/sync-feature-flows` was NOT a no-op here — three concrete staleness points in `template-processing.md`, which owns the `local:` resolution surface: * The inlined two-root ladder is now `_resolve_local_template_dir`; the code block showed the pre-extraction form. * "**Two** seams read `_LOCAL_TEMPLATE_ROOTS` and must stay in agreement" was the #1759 claim and is now wrong in the direction that matters: there was always a third seam (the credential-file stager) which did NOT agree — it re-derived the directory from the template's untrusted `name:`. Corrected to three, with the extraction as the structural guarantee. * `generate_credential_files` was cited by stale line range (`:228-299`) and documented none of where the `.mcp.json` template is actually located. Replaced the fragile line-range citation with a symbol reference and added the provenance, the residual fail-closed arm, and the disclosed deploy-local substitution delta. Also documents the read-path containment (`get_local_template` → `contained_template_dir`) beside the existing #1513 catalog-curation note, including the deliberate list-vs-detail asymmetry for a planted symlink. `local-agent-deploy.md` gets one line at the credential-merge step: a deploy-local template's `.mcp.json` now resolves from the deploy-local directory, so a hostile `name:` cannot read another tenant's file and `${VAR}` substitution finally applies to that template. `credential-injection.md` was checked and NOT touched — its `.mcp.json` references are unrelated (credential inject/export/import), and the template lookup lives in template-processing. One dated row added to the feature-flows index (no new flow document — this is a fix to documented behaviour, not a new vertical slice). Tests: adds the end-to-end `test_get_template_rejects_path_traversal` beside the existing 404 test. Stated plainly in the test's own docstring that this file is root-level and collected by NO gating CI job — it runs under `/verify-local` only, so it must not be read as CI coverage. The CI-gated guard is `tests/unit/test_1900_template_id_traversal.py`. The multi-level case is percent-encoded because httpx collapses a literal `../../` client-side. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(docs,templates): state the #1900 credential-staging delta honestly (review) /review + /cso on the #1900 branch. One MEDIUM finding, verified by execution rather than by reading, plus two comment-accuracy defects. MEDIUM — the disclosed behaviour delta was described as a gain and is a loss. Three docs claimed a deploy-local template "now genuinely receives `${VAR}` substitution". It does not. `generate_credential_files` has exactly one production caller (`crud._stage_config_files`, verified by grep across src/), and it passes `agent_credentials={}` — CRED-002 injects real values AFTER creation, not at staging. So `agent_credentials.get(var_name, "")` rewrites every placeholder to the empty string. Measured against the shipped code: archive .mcp.json : {"env": {"TOKEN": "${MY_TOKEN}", "FIXED": "literal"}, "args": ["-y", "${MY_TOKEN}"]} staged .mcp.json : {"env": {"TOKEN": "", "FIXED": "literal"}, "args": ["-y", ""]} and the staged file WINS over the archive's raw copy, for exactly the `startup.sh` ordering reason the branch already documents. Net effect for a deploy-local template shipping a `.mcp.json`: its placeholders are destroyed, and nothing is substituted in. Non-placeholder content survives verbatim. This is not a reason to revert the root-cause threading — the `.env` arm of the same function has always blanked an un-supplied `credentials.env_file` variable, so blank-at-staging is the platform's model, and `.mcp.json.template` (compatibility check S-009) remains the durable record of required variables, pre-populated untouched. It IS a reason to stop advertising it as an improvement: prose stronger than the code is itself a defect (learnings 2026-07-28), and this one would have shipped into the requirements file. Corrected in requirements §4.3, template-processing.md and local-agent-deploy.md, and pinned by a new test so the flattering restatement cannot come back: `test_1900_staging_with_an_empty_credential_map_blanks_placeholders` asserts the measured output (`""`, `["-y", ""]`, `${MY_TOKEN}` absent) and that hardcoded entries are preserved. LOW — `_LOCAL_TEMPLATE_ROOTS`' own comment still said "Read at TWO seams", which is the pre-#1900 claim and stale in the direction that matters: this PR exists because the third seam did not agree. Corrected to three, naming the extraction as what makes the agreement structural. LOW — "crud -> template_service is forbidden" (helper docstring + parity-test docstring) contradicts crud.py:32, which imports this module today. The ban is on what may be GATED on it (the #1484 MagicMock harness), not on the import edge; a reader who checks the citation and finds it false is one step from "helpfully" importing the regex. Narrowed to say so. Verification performed for this review, beyond the above: * every REPRO test re-run against reverted sources — 19 of 30 red pre-fix; the 11 that are green pre-fix are all correctly labelled HYGIENE / anti-over-block / landmine-guard, so no test is decorative; * `test_1900_containment_survives_a_symlinked_root` re-proved as the sole guard for resolving both sides (a candidate-only-resolve variant fails it and nothing else); * independent attack harness, 55 hostile inputs through `contained_template_dir` and `get_local_template`: zero escapes, zero raises, zero disclosures, and every legitimate name still accepted. The only non-None hostile input is the documented `"sage\n"` `$`-parity edge, which is CONTAINED; * symlink loops, a 200 KB name and a regex-backtracking probe: no exception, no superlinear time (the endpoint is unauthenticated-adjacent and rate-limitless); * `startup.sh` re-verified independently: `/generated-creds/.mcp.json` is copied at :376-383, gated only on the directory existing, AFTER the `.trinity-initialized`-gated template blocks that end at :367. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(tests): state honestly that test_templates.py has no automated runner The docstring claimed the #1900 traversal assertions "run under /verify-local". They do not. Every automated stage collects a subdirectory -- CI runs `pytest unit/`, /verify-local runs `pytest unit/` then `pytest integration/` -- and this file is root-level, so NEITHER collects it. The assertions have no automated runner at all. Corrected to say so, with the manual invocation that does exercise them (needs a booted backend), a pointer to the CI-gated guard that actually protects the fix, and a note that giving this file a runner is a follow-up. Docstring only -- no assertion changed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Eugene Vyborov <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…) (#2145) * docs(a2a): requirements §32.5 for outbound A2A calls, before the code (#736) Trinity Rule #1 — the requirements area file is updated BEFORE implementation. Adds `docs/memory/requirements/mcp.md` §32.5 (13 FRs) covering the runtime outbound half of A2A: registry-only targets, call-time SSRF re-validation, connect-time IP pinning, registry-bound credentials, message/send-only scope, no Trinity execution row, effect_guard identity, caps/deadlines, use-not-grant authorization, a default-OFF kill switch, card-driven dialect, and the card treated as a hint rather than an authority. Four of the issue's filed ACs are recorded as REJECTED with their reasons, so the divergence from the issue text is documented rather than silent. Also corrects live doc/code drift in §32.3: it claimed the A2A management tools apply a `{self} u permitted` gate for agent-scoped keys. They do not -- `tools/a2a.ts` carries no such check -- and the gap is not cosmetic, because the backend resolves an agent key to its owner, so the two READ tools let one agent enumerate a sibling's registered outbound endpoint URLs. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(a2a): outbound call path — registry-only targets, pinned egress (#736) The runtime outbound half of A2A: a Trinity agent asks Trinity to task an external A2A agent and gets the answer back. Backend-executed, because the credential is an AES-256-GCM envelope only the backend can open, the response must be credential-sanitised before an LLM sees it, and the audit row is a Python write. No agent-server change; no new table, migration or Alembic revision. OSS-CORE BY DECISION, not by omission. The parent epic records the owner's ruling -- "Outbound = OSS" -- so there is no requires_entitlement anywhere on this path, and OSS ships a real target source rather than a seam that answers "no targets" everywhere. The target is never supplied by the caller The tool takes an endpoint NAME, not a URL. An agent's parameters are LLM-generated and prompt-injectable, so a URL parameter turns any document the agent reads into a lever on a credentialed request from inside the platform network. This is the whole security story; everything below defends it in depth. Egress controls - Call-time SSRF re-validation of every URL, including one that came out of the registry: registration checks only the scheme prefix, so "it is stored" is not "it is safe". http:// is refused at USE, never silently upgraded. - Connect-time IP pinning closes DNS rebinding rather than recording it as a residual -- the sibling template-registry validator can accept that residual because it fetches a display-only catalog; this request carries a credential. One resolution, one validated address, both hops, with the registered hostname presented for Host + SNI + certificate verification. - trust_env=False, because every other control reasons about the target IP and a proxy makes the target irrelevant. The CA context is rebuilt explicitly so that does not silently drop SSL_CERT_FILE. - No redirects on either hop; wire-byte ceilings over aiter_raw(); any Content-Encoding refused rather than decoded; DNS off the event loop; a wall-clock deadline, since httpx's read timeout is per-read and a trickling tarpit resets it forever. The card is a hint, not an authority Its declared url must be same-origin with the registered endpoint, and securitySchemes never selects the credential. That is what lets this ship while signed cards (ent#159) are blocked: it removes the card's authority instead of trying to verify it -- a scheme that warns on unsigned cards cannot bound a credentialed fetch, because an attacker simply does not sign. Errors ride in the body on HTTP 200, so the body is parsed for `error` even on 200 and mapped to 502; a status-only check reads every remote failure as success. Dedup identity is the conversation, not the recipient effect_guard keys on {endpoint_id, resolved_url, context_id, task_id} with a REQUIRED dedup_label. Inheriting send_message's "one effect per recipient per turn" shape would make a second question to the same endpoint in one execution a completed replay -- returning the answer to the FIRST question, with no error and nothing logged. Kill switch, default OFF, resolved system_settings -> env -> OFF, wired into both compose files and .env.example in this same change. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(mcp): call_a2a_agent + get_a2a_task, and tests that can fail (#736) MCP surface A new module rather than an addition to tools/a2a.ts, whose header scopes it to the A2A *management* plane and whose fail() helper is built around entitlement flags -- folding an OSS-core runtime call in there would tell an operator their outbound call needs a licence when the kill switch is simply off. Registered in toolGroups, i.e. the operatorOnly ALLOW-list {user, agent, system}, so connector and anonymous sessions can neither see nor call it. The per-call gate is SELF-ONLY for agent-scoped keys, deliberately not the {self} u permitted shape the other modules use. The backend route is self-only, so a wider check here would deny a strict subset of what the backend denies: it would block nothing while costing a getPermittedAgents round-trip per call. An inert check is worse than none, because the next reader believes it does something. client.ts carries its own AbortController. request() uses a bare fetch with no signal and nginx is proxy_read_timeout 86400, so without one the MCP client's 30-60s gateway timeout fires first and the agent sees "fetch failed" while the credentialed call completes anyway -- a side effect with no handle to poll, since task_id only comes back on success. An abort is now reported as possibly_delivered. F8 -- a real leak, fixed while here get_agent_a2a_config and list_a2a_endpoints had no agent-key gate at all. The backend resolves an agent key to its OWNER, so on a single-owner install any agent could enumerate a SIBLING's registered outbound endpoint URLs. requirements mcp.md §32.3 already claimed this gate existed; it did not. Tests Backend split in two, because the harness has to be able to express the failure. Transport properties (byte ceiling, refused compression, refused redirect, connect-time IP pin, proxy neutrality) run over a real httpx client on MockTransport with genuinely streaming responses -- httpx.Response(content=) buffers in the constructor, so aiter_raw() raises StreamConsumed against it and a ceiling test built that way proves nothing. Route, auth, dedup and seam properties run over TestClient. Two tests earn their place above the rest: - a LOOPBACK round trip: the outbound client against Trinity's own inbound server, in process. One test covers dialect selection, the same-origin pin against a real Trinity card, credential attachment and #738 federation's whole premise -- and refutes "target v1.0 only" directly, since a v1.0 client would get -32601 from Trinity. - two DIFFERENT messages to one endpoint in one execution must produce TWO outbound calls. Nothing else catches the C2 replay bug, whose symptom is a wrong answer rather than a failure. Credential redaction is tested with a NON-pattern credential (40 random chars): sanitize_text matches patterns, so a trinity_mcp_-shaped secret exercises only the case that already worked. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(a2a): flow doc, architecture rows and the user-facing outbound guide (#736) New `docs/memory/feature-flows/a2a-outbound-call.md` + its index entry: the layers table, the request walk, the gate order, the error table, and — because an unstated rejection gets re-litigated — a "why now" section that names the real driver (release-narrative completeness plus #738 being blocked on this) rather than repeating the research's stale "low-risk entry point" framing, plus why the two reframes (collapse into #738; model an A2A peer as an MCP entry) and the a2a-python SDK were rejected, and why the fetcher sits on the backend rather than in the agent container -- a decision, not a byproduct. architecture.md: the outbound routes on the `a2a.py` catalog line; three new service rows; the `utils/url_validation.py` row recording the extracted shared gate and why `validate_skills_library_url` deliberately stays out of it; the API-endpoint and settings rows; the `a2a_call.ts` MCP tool row; the new `system_settings` key in Invariant #12's list; and `a2a_outbound_available` in the feature-flags row. The `a2a_outbound.py` row states the property most likely to be lost in a later refactor: it mirrors `a2a_gate.py`'s registration shape and INVERTS its failure semantics. `a2a_gate` fails open and its docstring says that is acceptable because it is not a security boundary. This one is one -- it decides where a credential is sent -- so no provider, a raising provider and a malformed return all refuse. User doc gains Part 3: enable the kill switch, register an endpoint, call it, poll a long-running task, federate Trinity-to-Trinity, and a troubleshooting table keyed on the reason codes the tool actually returns. It also carries the disclosure that matters more than any of the controls: registering an endpoint grants that endpoint the ability to exfiltrate its own credential, because exact-value redaction cannot survive a remote that transforms the secret. Registration is a trust decision about a peer, and the doc says so. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(a2a): cache the resolved RPC target, not just the dialect (#736) Self-review found a real defect in the poll path, of exactly the class this feature keeps producing: silent, and only for one legitimate configuration. `get_a2a_task` cached the negotiated DIALECT per origin and then re-derived the RPC target from the registered URL on a cache hit. That is correct only when the operator registered a URL WITH a path. The registry field is documented as "endpoint OR Agent Card URL", so registering the ORIGIN is legitimate — and for those endpoints the first call learns the real target from the card's `url` (e.g. /a2a/bot) while a later poll re-derived `/`. Wrong endpoint, no error, and only after the cache warmed. The cache now stores the resolved target alongside the dialect: both are learned from one card read, both expire together. Regression test included. Also from self-review: - the admin GET now reads the OSS store directly instead of going through the resolver seam. A registered enterprise provider legitimately answers a different question ("what can THIS agent call?"), and an admin panel whose GET and PUT addressed different stores would be worse than no panel. - the OSS endpoint store gains its own tests: encrypt/decrypt round trip through system_settings, credential write-only semantics on update, clear, remove-by-id-or-name, the bound, write-time URL validation, and that an unreadable stored list resolves NOTHING rather than raising or falling open. - `_pinned_url` records that the SNI mechanism is a pinned-version dependency: httpcore 1.0.9 reads `extensions["sni_hostname"]` as `server_hostname`, httpcore is not pinned in the backend Dockerfile, and a future 1.x that ignored it would fail TLS closed against the IP's cert rather than connect somewhere unvalidated. Nothing short of a live handshake can pin a third party's behaviour, so the comment is the record. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(a2a): state the two residuals behind the off-loop DNS budget (#736) `asyncio.wait_for` around `asyncio.to_thread` LOOKS like a deadline and is not one, so the resolver budget now says what it actually buys: the caller gets a clean refusal, but the worker thread keeps sitting in getaddrinfo until the resolver gives up, and the default executor is bounded — a flood against a stalling resolver exhausts it, after which calls queue and time out here. Both are fail-closed, and the rate bounds run first. Recorded rather than left for a reviewer to rediscover, because this is exactly the shape the plan warned about for the call's TOTAL deadline (which wraps cancellable network awaits instead). Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(a2a): keep private-module internals out of public prose, and guard the new seam (#736) Two related fixes, both about the standing rule that public docs describe the generic open-core seam only. 1. I had written, in requirements §32.5, the flow doc, the architecture row and the seam file's own docstring, that a private module "ships no decrypt path and no outbound provider today". That is a true and load-bearing engineering fact -- it is WHY OSS owns a working target source -- but it is also per-module implementation detail about a paid module, which belongs in the private repo. The argument survives without it: a seam with no registered provider resolves nothing, so shipping only the seam would answer "no targets configured" on every install, which is not what "outbound = OSS" can mean. The grep-guard never fired on this (its pattern targets `enterprise_*` identifiers and named paid features); the rule is broader than the grep. 2. `services/a2a_outbound.py` is a new open-core seam whose docstring necessarily discusses which side owns the registry -- precisely the prose that drifts into naming a paid catalog -- and it was not in the guard's SEAM_FILES. Added, along with the two path filters, since a seam the guard greps but does not WATCH is a guard that runs at the wrong times. `a2a_gate.py` was already grepped but likewise unwatched; fixed in the same edit. This is the #1461 lesson the guard exists for: a comment in a seam is unguarded prose that discloses just as a doc does. The flow doc also now carries the note for the human that Option 4 narrows a private module's role here to per-agent scoping plus the managed UI -- and that if that scoping was deliberate monetization, the OSS list becomes the floor and a per-agent provider gates on top. A product call, deliberately not made here. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(a2a): refuse a card url that embeds credentials (#736) `_same_origin` compares `hostname`, which STRIPS userinfo, so a card declaring `https://user:[email protected]/a2a` compared EQUAL to the registered origin and passed the pin. Nothing leaked today, because `_pinned_url` drops the userinfo when it rebuilds the authority — but that is a coincidence of one helper rather than a decision, and it is exactly the kind of thing a later refactor of that helper would quietly undo. A card declaring credentials in its own URL is anomalous regardless, so it is now refused by name and logged at ERROR, with a belt test pinning that the URL the socket sees is scheme + IP + port + path whatever the authority contained. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(tests): exercise the real AES-256-GCM envelope instead of stubbing it (#736) Caught by the FULL unit suite, not by running the file: seven OSS-store tests passed in isolation and failed in-suite. They stubbed `services.credential_encryption.CredentialEncryptionService` by string target, and `tests/unit/conftest.py` restores `sys.modules` entries between tests, so by the time `a2a_outbound` resolved the class at call time it was the real one again -- which raised "Encryption key not configured". Patching harder was the wrong fix. The fixture now sets a real `CREDENTIAL_ENCRYPTION_KEY` (`monkeypatch.setenv`, per-test and immune to module restoration -- the shape `test_77_webhook_secret_db.py` and several siblings already use) and lets the genuine encrypt/decrypt cycle run. That removes the fragile patch AND makes the test better: the property worth pinning is that the endpoint list survives a real envelope round trip, which is what Invariant #12 is about. The "one row" test now asserts the property that actually matters rather than a stand-in: exactly one `system_settings` key (Option 4's decisive property -- no new table), AND neither the credential nor the URL is readable in the stored value. Under the plaintext-JSON stub that second assertion was impossible to write, which is the tell that the stub was testing the harness. Refs #736 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(a2a): close three outbound defects the review found (#736) Three findings from the security review of the outbound path, each with a regression test that fails without its fix. 1. **The resolved credential could be echoed back to the calling LLM.** `sanitize_outbound_text` guards the response body; it does not guard an `A2ACallError.detail` built from an httpx exception — and that detail reaches the agent through the 502 body and the backend log. h11 rejects an illegal header value by ECHOING it (verified: `LocalProtocolError: Illegal header value b'Bearer <token>'`), which is the documented reason `models._validate_pat_secret` exists (ent#109). A stored credential carrying a stray line break — the routine paste artifact — therefore turned a transport error into a credential disclosure. Closed at three layers: the request model and the store both refuse a header-unsafe credential without echoing it (paired with `validation_error_without_input`, so the guard closes the leak rather than relocating it into the 422), and the transport error detail is now scrubbed with the exact credential value. 2. **A sibling endpoint on the same host could receive another endpoint's credential.** The negotiated `(dialect, rpc_url)` was cached under `hostname:port`, so after any call to `https://host/a2a/alice` a poll for the separately-registered `https://host/a2a/bob` reused Alice's resolved target — delivering Bob's credential to Alice's endpoint and polling the wrong agent. A multi-tenant peer with an agent per path is exactly the deployment the registered-path rule exists to support, and two registry rows are two different trust relationships. The cache is now keyed on the registered URL, which is what `resolve_rpc_target` derives from. 3. **A malformed card `url` was a peer-triggerable HTTP 500.** `urlsplit` raises on an unterminated IPv6 authority (`https://[::1`), and that ValueError escaped the client, the orchestrator's `except A2ACallError` and the router's error map. Every card field is peer-controlled, so it is refused by name (`card_url_invalid`) like every other malformed field. Also: `_same_origin` now folds both hosts through the validator's own `canonical_host`. The validator canonicalises to the IDNA A-label and resolves that, while the comparison used raw strings — so an IDN peer declaring the punycode form its own server emits was refused as cross-origin. One normalisation used by the parser, the resolver and the comparison is the whole point of the rule; the card comparison was the one place left out of it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(mcp): wire MCP_A2A_TIMEOUT_MS so the knob is not inert (#736) `src/mcp-server/src/client.ts` reads `process.env.MCP_A2A_TIMEOUT_MS` to bound its own outbound-A2A fetches, but the variable reached neither compose file nor `.env.example` — so an operator setting it in `.env` got nothing. That is the packaging-gap class this plan itself names six recurrences of (#1039, #1056, #1891), and the two sibling knobs one line above it (`MCP_CHAT_TIMEOUT_MS`, `MCP_INLINE_AUTH_TIMEOUT_MS`) already carry the "functional via its default; wired so the lever is not inert" comment this follows. It matters more than a comfort knob: the timeout has to stay below the MCP client's own 30-60s gateway abort, because if the gateway gives up first the agent sees `fetch failed` while the credentialed outbound call completes anyway — and with no `task_id` returned it holds no handle to poll. Tuning it per deployment is the mitigation, and until now it could not be tuned. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(a2a): correct three claims the outbound docs got wrong (#736) Each of these shipped as a stated position, which is worse than an omission — a future reader trusts it and reasons from it. **1. The fail-open composition is not a composition.** `requirements/mcp.md` and the flow doc both recorded, as an accepted residual, that `rate_limiter` and `idempotency_service` "both fail open, on the same infrastructure. With Redis down this path has neither an effective rate bound nor dedup". Both halves are wrong. `rate_limiter` fails *soft*: a Redis outage drops it to `_check_inprocess`, a bounded per-worker sliding window, so the bound survives and only its scope narrows (`--workers 2` ⇒ an effective 2x, not unbounded). `effect_guard` is not on Redis at all — it claims rows in the `idempotency_keys` **table** — so a Redis outage does not touch dedup. Stating a residual that does not exist points attention away from the one that does: `execution_id` is agent-supplied and the guard fails open when it is absent. **2. There is no per-agent credential boundary to protect yet.** The self-check was documented in four places as stopping "a permitted sibling spending a neighbour's registered credential". Under the shipped OSS provider endpoints are platform-scope — every agent may name every registered endpoint — so there is no own-vs-neighbour credential. The check is still right and still wanted, for reasons that are true: it protects **attribution** (rate-limit key, audit row, activity row all name the agent that actually spent the call, so a sibling cannot launder its egress through a neighbour) and it holds the line for a future per-agent provider. Stated that way instead. **3. The registry a target resolves from was ambiguous to an operator.** The user doc said the per-agent *Outbound endpoints* panel "feeds the agent's outbound A2A calls", while `call_a2a_agent` resolves the platform list from Part 3 — so registering in the panel and calling yields `endpoint_not_found` with no clue why. The doc now says which list the resolver reads and what changes when a provider is registered for the other one. The `call_a2a_agent` tool description pointed agents at `list_a2a_endpoints` for the same reason and now does not: that tool reads the per-agent store and cannot name a callable target. There is deliberately no agent-facing listing of the platform list — the registered URLs are the shape of the fleet's integrations. Also corrects the dialect-cache description to match the code after the per-endpoint keying fix, including that only `get_a2a_task` reads the cache while `call_a2a_agent` re-reads the card on every credentialed send. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(a2a): apply the card-fetch timeout that was declared but never wired (#736) `A2A_CARD_FETCH_TIMEOUT = 10.0` was declared and commented "seconds, whole card fetch", and nothing read it: the client is constructed once with `httpx.Timeout(A2A_RPC_TIMEOUT, ...)`, so both hops ran on the RPC's 30 s budget. That is not cosmetic. The total deadline is 45 s precisely because the intended split is 10 s card + 30 s RPC + slack; on the shipped code a slow-but-not-dead card could consume 30 s of that window and leave the CREDENTIALED send 15 s, which is the hop the aggressive timeout exists to protect. The card fetch now carries its own per-request timeout and the arithmetic is asserted, so the three constants can no longer drift apart silently. A declared, commented cap that nothing applies is worse than one that was never claimed — a reader budgets against it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(a2a): cover the activity row, which nothing exercised (#736) F12 — "one `agent_activities` row per outbound call" — shipped with no test. Every existing test monkeypatches `_record_activity` to a no-op, and the writer is deliberately fail-open, so a wrong enum name or a changed `track_activity` signature would swallow itself into a WARNING and the row would simply never appear. That is the shape of a requirement that ships inert, and it matters here specifically because F12's whole justification is that the audit log is admin-gated and unwatched while this stream is the one an operator sees. Three tests drive the REAL writer against a recording activity service: the happy path (one open + one close, `AGENT_COLLABORATION`, `triggered_by=agent`, details carrying endpoint + host and NOT the URL, message or credential), the failure path (`ActivityState.FAILED` + the reason), and the fail-open guarantee. Verified by mutation: swapping the activity type, and making the write raise, each fail the new tests and nothing else. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(settings): drop two unrelated edits from the A2A change (#736) Rule #2 housekeeping on a file this PR had to touch for a different reason. `acknowledge_retention_prune` gained a SECOND in-function `from dependencies import reject_agent_principal` — the function already had one, six lines up, and the duplicate reads as though the import had been missing, which invites someone to "fix" the #1709 comment beneath it. And `set_telemetry_sharing` gained a blank line and nothing else. Both are reverted, so the settings diff is exactly the outbound-A2A surface: the endpoint-registry routes, the feature flag, and the catch-all block. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(a2a): restore the import-time sys.modules entry after each test (#736) `test_736_a2a_url_validation.py` registered the directly-loaded backend `url_validation` module under a synthetic `sys.modules` name at module scope, which tripped the #762 `lint_sys_modules` ratchet (0 -> 1, the only new violation on the branch). The registration runs at import time, before any fixture, so `monkeypatch.setitem` cannot reach it — this is the import-time case, whose sanctioned remedy is the named `_STUBBED_MODULE_NAMES` + autouse `_restore_sys_modules` pair (precedent: `tests/unit/test_telegram_webhook_backfill.py`). One adaptation over that precedent, which matters for correctness rather than for satisfying the lint: the precedent installs its stubs *inside* each test, so a snapshot taken at fixture setup is genuinely pre-stub. Here the entry is already in place by then, so the pre-stub value is captured at module scope instead — a fixture-time snapshot would simply write the entry back and leak it for the rest of the session. `tests/unit/conftest.py`'s `_POP_PREFIXES` sweep does not match this name, so nothing else was reclaiming it. Test-only change; no production source touched. Baseline deliberately NOT regenerated. Linter now exits 0; the three #736 files still pass 147/147. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(a2a): bind the kill-switch tests to the singleton the resolver reads (#736) The three kill-switch tests patched `get_setting` on the singleton reached via `import services.settings_service as ss` — which binds the parent package's `settings_service` ATTRIBUTE. Once an unhygienic test elsewhere pops + re-imports the module and the unit conftest's baseline restore puts the sys.modules ENTRY back without touching the package attr (the #1898 pollution class), the two name different module copies: the patch lands on an object `is_outbound_enabled`'s call-time `from services.settings_service import settings_service` never reads, the env leg decides, and `test_a_stored_row_overrides_the_env_in_both_directions` failed seed-dependently in CI (seeds 12345/99999) while passing in isolation and under seed 67890 — the one new failure the regression-diff job flagged. Fix: resolve the singleton via `importlib.import_module("services.settings_service").settings_service` — the same live-entry lookup the resolver itself performs — so the patch target and the resolver target cannot diverge, in either pollution direction (stale package attr, or a leaked stub entry). Verified red/green with a deterministic offender that reproduces the divergence (pop + re-import + restore the entry): the old form fails with the exact CI assertion (`assert True is False`), the new form passes; all 147 #736 tests still pass in isolation; `lint_sys_modules` unchanged. Test-only change; no production source touched. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: trinity-ability <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: trinity-ability <[email protected]>
* test(e2e): List-mode spec + five specs adjusted for the retired Agents page (ent#260) NEW dashboard-list-view.spec.js: system-row render (data-agent hooks, SYSTEM badge, detail link; deliberately no toggle-visibility assertions — CI's only agent is the guarded system agent), AC-4 mode persistence, AC-2 redirect (param stripped, saved mode NOT rewritten), ?onboarding=1 survives the redirect + opens the wizard, name-filter narrowing + filtered-empty Clear-all recovery, three-mode round-trip. smoke.spec.js: Agents nav-link assertion dropped (nav list comment updated); 'agents page loads' becomes the redirect assertion. browser-tab-titles: the Agents hop removed from the SPA chain (Dashboard → Templates still proves the client-side repaint); /agents → 'Trinity — Dashboard' joins the redirect-title test. dashboard-grid-view: header comment (three modes; exact-name toggle selectors unaffected). dashboard-stats-overflow: 'list' added to MODES — the third toggle + chassis Create button widen the controls cluster in every mode. navbar-overflow test 3: the 640px squeeze branch is now conditional on the MEASURED overflow (4-link OSS bar may fit where 5 links overflowed; an entitled build still exercises the scroll-recovery branch) — sm=640 is the floor, below it the link row hides, so narrowing further was not an option. Full e2e run defers to CI (frontend-e2e on the ui label) — the live local stack is not exercised from this worktree. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: Dashboard List view — architecture block, new feature flow, index + superseded banner (ent#260) architecture.md: Grid-view paragraph reworded to three modes; new Dashboard List view block (AgentListPanel extraction, visibleAgents seam ownership, N+1 deletion, redirect + NavBar consolidation, zero backend change). NEW feature-flows/dashboard-list-view.md (overview, data-flow diagram, decisions D1/D2/D7/D8/D11 + the two flagged plumbing calls, teardown state-loss note, testing). dashboard-grid-view.md mode-count wording. agents-page-ui-improvements.md superseded banner (kept as history). feature-flows.md: List-view index row, Agents-page row → superseded pointer, changelog entry. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): repoint cross-cutting flow docs off the retired Agents page (ent#260) /sync-feature-flows coverage pass over the full branch diff: eleven flow docs carried live current-state claims about views/Agents.vue (avatar/toggle/meter usage tables, sync-health dot renderer, system-agent display, tag bulk-ops entry points, skills-on-start entry, dark-mode coverage row, timeline-view mode-toggle description). Live references now point at components/AgentListPanel.vue / the Dashboard chassis; dated changelog entries and explicitly-labelled historical sections are left as history. Also fixes dashboard-timeline-view.md's pre-existing stale '[Graph] [Timeline]' toggle claim to the current three-mode set. Touched: agent-avatars, agent-lifecycle, agent-tags, autonomy-mode, autonomy-toggle-component, dark-mode-theme, dashboard-timeline-view, git-sync-health, internal-system-agent, parallel-capacity, read-only-mode, skills-on-agent-start. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(dashboard): review fixes — Create-button icon-only degrade + gated fetch write-through (ent#260) Two review-stage fixes on the ent#260 branch: 1. Create Agent label degrades to icon-only below `md` (title + aria-label kept). The controls cluster is flex-shrink-0; measured against the #1830 stats-ladder constants (agents-only floor 71px), the full label at 640px in grid mode (+ the third mode button) leaves ~47px — the stats-overflow spec's clip assertion would fire. This is the plan's pre-decided degrade, applied ahead of CI. 2. The fetchAgents → agentsStore.agents write-through is now gated on no active quick-tag filter (params.tags narrows the response server-side; a filtered subset must not clobber the full-fleet list agentsStore consumers read — the Executions dropdown's cold-start self-heal is length===0-gated and never recovers from a non-empty wrong value) and writes a shallow copy (array identity per store, shared row objects so in-place status/label patches still propagate). Docs synced (architecture block, flow doc, agents.js contract comment) + a learnings.md entry for the write-through class. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): §9.9 seam wording matches the implemented deviation (ent#260) The plan's D8 wired both convertAgentsToNodes call sites through the visibleAgents computed; the implementation deliberately deferred the timeline wiring to ent#261 (ReplayTimeline :agents prop switch — rewiring the node paths was rejected as timeline-mutation risk) and the code comment + flow doc + architecture all record that. §9.9 still claimed the node-rebuild call sites consume the seam — align it. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(frontend): rename Templates.vue to Library.vue (pure move) (ent#263) Byte-pure git mv with zero content edits so git rename detection holds and a parallel edit to Templates.vue (ent#260) resolves as a content merge inside Library.vue rather than a modify/delete conflict. All content changes land in follow-up commits. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(frontend): Library page + route/nav rename with /templates redirect (ent#263) - Library.vue: h1 'Library', new subtitle, templates content wrapped in an 'Agent Templates' section (own loading/error/empty states; inner headings demoted h2->h3); fetch migrated to the shared api client (Invariant #7) - router: /library route (meta.title Library) + /templates function-form redirect carrying query AND hash; route name Templates->Library (no named pushes exist) - NavBar: label Library, to=/library, active via startsWith('/library') - CreateAgentModal: its single raw-axios /api/templates call migrated to the shared api client so no half-migrated consumer of the endpoint remains Page-identity naming only (AC#4 reading): the asset-kind noun 'template' survives inside the Library (Starter/GitHub Templates sections, Use Template). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(frontend): Library skills section — fleet browse over the skills library (ent#263) - stores/skillsLibrary.js (new): fleet-scoped store, deliberately separate from stores/skills.js (KeepAlive-cached AgentDetail means SkillsPanel's clear() never fires on nav-away — shared refs would poison the cached tab); imports nothing from stores/skills.js. 4-state emptyReason discriminator (unconfigured/not_cloned/empty + error carried separately); sync() with a 180s timeout and ECONNABORTED -> status-refetch (a first clone can outlive the 30s api.js default; client timeout != server failure) - components/LibrarySkillsSection.vue (new): sync-state header leads with commit_sha + skill_count (disk-derived; last_sync is per-worker in-memory and renders only when truthy); repo URL admin-only, userinfo-stripped, labeled 'Primary source', hidden when status.sources reports >1 (#1901 forward-compat); admin Sync now; per-kind empty states teaching the next action; dormant source_name/shadowed_by slots; interpolation only - components/skills/{SkillContractChips.vue,contract.js} (new): the #183 contract-chips seam extracted from SkillsPanel so both the per-agent tab and the Library browse render package facts from one seam - SkillsPanel.vue: consumes the shared seam (local SkillMeta/formatBytes/deps removed); stores/skills.js untouched - Library.vue: skills section wired in + header jump anchors (no ?kind=) Co-Authored-By: Claude Fable 5 <[email protected]> * test: Library e2e anchors + remove dead template-endpoint tests (ent#263) - smoke.spec.js: '@smoke library page loads' asserts chrome-only getByRole headings (h1 Library + both section headings — the old getByText(/template/i) passed on the un-renamed page and proved nothing); new '@smoke templates path redirects to library'; stale nav comment fixed (Health/Ops merged in #1109) - browser-tab-titles.spec.js: nav click asserts 'Trinity — Library'; redirect test also covers /templates -> /library title resolution - tests/test_templates.py: remove TestEnvTemplate + TestTemplateRefresh — GET /api/templates/env-template and POST /api/templates/refresh no longer exist (router has exactly 2 GET routes; live-stack probe returns 404); test_get_template_by_id now exercises the REAL detail endpoint instead of the dead env-template detour that always skipped. 5 remaining tests pass against the live stack. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: Library page — requirements, architecture, feature flow, stale-endpoint rot sweep (ent#263) - requirements/core-agent.md: new §4.5 Library Page — unified /library surface (agent templates + fleet skills browse), query+hash-preserving /templates redirect, stacked sections, per-kind empty states, the AC#4 page-identity naming rule; fleet assignment visibility named as Not Built - requirements/skills.md (surgical — §21.3/§22.2/new §22.3 only, avoiding PR #1901's §21.1/§21.5 hunks): §21.3 stale 'Skills tab is hidden' note corrected (visible since ent#235/PR #1877); §22.2 rewritten as visible/rebuilt; new §22.3 Library Page fleet skills browse — browse-only over the existing /api/skills/library reads, own skillsLibrary store + the KeepAlive rationale, admin-only URL/Sync, #1901 forward-compat, assignment read = Not Built - architecture.md: 'Top-nav IA — Library (ent#263)' paragraph beside the #1109 Operations one; stale 'Templates (4 endpoints)' table corrected to the 2 real routes (POST /refresh AND GET /env-template both verified absent) - feature-flows: templates-page.md git-mv'd to library-page.md + full rewrite (the old file was deeply stale — AgentSubNav, dead endpoints); index row + platform-settings.md Related-Flows link repointed - template-processing.md + CREDENTIAL_MANAGEMENT.md: dead env-template endpoint references removed/replaced (same rot class as the architecture table); Templates.vue references repointed at Library.vue - user docs (creating-agents.md, faq/agents.md): Templates page → Library (+ redirect note) Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): TGRAM-PROGRESS — Telegram in-progress status indicator (ent#264) New §15.1h: reaction ack + elapsed-time placeholder + channel-agnostic start/progress/resolve seam, group gating (mention/reply OR all-mode; observe stays silent), degradation ladder, default-ON per-binding toggle, GET /telegram access hardening. §15.1c/§15.1e touch-ups. Requirements-first per Rules of Engagement #1. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(channels): in-flight progress indicator seam + Telegram reaction ack and elapsed-time placeholder (ent#264) Channel-agnostic start/progress/resolve seam (Invariant #9): - base.py: default-no-op indicate_progress hook + progress_threshold_seconds/ progress_interval_seconds capability attrs (None => the router never arms a driver, so Slack/WhatsApp/VoIP behave byte-identically). - message_router.py: router-owned per-turn driver — _arm_progress_driver after step 8 (call + arm wrapped so a raising hook can never abort the turn), _progress_loop (elapsed origin captured BEFORE the threshold sleep; per-tick try/except), _resolve_indicator at all three terminals (cancels AND awaits the driver dead, settles the shielded in-flight placeholder send, THEN indicate_done — closes the tick-after-resolve and resolve-vs-first-send races by construction; carries success for the adapter's neutral fallback line), and an idempotent try/finally _cancel_progress_driver backstop. - telegram_adapter.py: indicate_processing upgraded (single binding read, per-turn cfg stash, typing preserved verbatim, 👀 reaction ack — gated on the default-ON per-binding toggle and ack-eligibility; whole body never raises); NEW indicate_progress (placeholder send-then-edit, message_id recorded INSIDE the shielded helper, disable_notification, explicit HTML, 2-consecutive-failure degraded flag over sends/edits/timeouts alike) and indicate_done (clear reaction at every terminal — no success-👍 swap; delete placeholder, neutral edit-to-done fallback); fail-soft primitives _set_message_reaction/_edit_message_text/_delete_message/ _send_placeholder_message mirroring _send_message's shape (429 retry_after capped 30s; never log the token-bearing URL). - parse_message stashes progress_ack_eligible: DMs, @mention/reply group turns, and `all`-trigger-mode groups; observe mode stays typing-only. - All per-turn state on NormalizedMessage.metadata (the adapter is a shared singleton); decrypt_telegram_bot_token facade passthrough so the hook decrypts from the row already in hand. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(telegram): per-binding progress-indicator toggle — dual-track migration, API, UI (ent#264) Default-ON toggle for the in-progress indicator, per-agent == per-binding: - Dual-track migration (Invariant #3 / Rule #9), all six touch points: SQLite `telegram_progress_indicator` in db/migrations.py + Alembic 0031_telegram_progress_indicator (down_revision 0030; renumber-at-rebase rule vs ent#265 applies to whichever PR merges second) + schema.py + tables.py DDL + _BINDING_COLUMNS + _row_to_binding. No backfill UPDATE: ADD COLUMN ... DEFAULT 1 populates existing rows (default ON is the AC). - Read predicate evaluated in Python, never SQL (`NULL != 0` is NULL): enabled ⇔ `v is None or v != 0` — only an explicit 0 disables. - db: set_progress_indicator_enabled + set_telegram_progress_indicator facade. - API: GET /api/agents/{name}/telegram surfaces progress_indicator_enabled (pinned in the hand-built response, #1809 lesson — configure PUT too) and is access-hardened get_current_user → AuthorizedAgentByName (the response carries webhook_url, which embeds the webhook secret — previously readable by ANY authenticated user; uniform-404 accessor, Invariant #8). New PUT /api/agents/{name}/telegram/progress-indicator — OwnedAgentByName + reject_agent_principal (behavior toggles are human-only, ent#223 lesson), 404 when no binding; dedicated route so toggling never re-sends the token. - models.py: TelegramProgressIndicatorRequest + response field (Invariant #14). - UI: TelegramChannelPanel.vue switch (SlackChannelPanel allow_proactive precedent), optimistic flip with revert-on-error, dark-mode aware. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(architecture): channel-adapter progress-indicator seam deltas (ent#264) base.py indicate_progress hook + capability attrs; message_router.py per-turn driver (arm/tick/resolve + backstop, inline-sync coupling named for #1081 pickers); telegram_adapter.py reaction ack + elapsed placeholder + default-ON per-binding toggle. Co-Authored-By: Claude Fable 5 <[email protected]> * test(telegram): progress-indicator unit suite — adapter, router driver, toggle (ent#264) 61 tests, no backend required. Highlights per the plan's scrutiny list: resolve-vs-first-send race (shielded id recording → delete finds it), cancel-and-await ordering at both terminal flavors, 429-backoff cancel promptness, [NO_REPLY]-still-resolves, step-8 wrap regression guard, singleton metadata isolation, degraded-quiesce after 2 consecutive failures, static-template-only egress pin (ent#224 class), live-select column test (4-file schema rule), real-DB facade round-trip (#1533 no-MagicMock), legacy-table SQLite migration + renumber-safe Alembic-twin existence, GET JSON field pinning (#1809) + AuthorizedAgentByName hardening pin, PUT reject_agent_principal 403. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(feature-flows): telegram in-progress status indicator section (ent#264) New section in telegram-integration.md: three fail-soft layers, the channel-agnostic start/progress/resolve seam, race closures (tick-after- resolve, resolve-vs-first-send, singleton concurrency), gating matrix (incl. `all`-mode groups; observe stays typing-only), toggle surface, degradation ladder / Bot API constraints, restart residual + the inline-sync coupling named for #1081/#1083 pickers, test inventory. Index unchanged (existing flow). Revision-history row added. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(telegram): access-harden the groups GET; document the bounded settle residual (ent#264) Review-stage fixes: - GET /api/agents/{name}/telegram/groups moves from bare get_current_user to the uniform-404 AuthorizedAgentByName accessor — the sibling read of the panel flow this PR already hardened. Group chat ids/titles/welcome text are tenant data; the only follow-up action (the group-message POST) was already OwnedAgentByName, so the read tier is strictly broader than every usable consumer and no flow narrows (incl. the MCP list_channel_groups path, whose paired send is owner-gated). - Route-dependency test pinning the groups-GET accessor (mirrors the binding-GET hardening pin). - Docs honesty: the resolve-path in-flight settle is bounded at 10s — a first placeholder send slower than that (429 retry_after >= 10s) is abandoned and can strand a self-dating placeholder. Named in the feature flow Residuals + requirements Known residuals instead of implying the race is closed unconditionally. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(db): source_channel_agent + telegram allow_proactive columns (ent#265) Dual-track migration (Invariant #3 / #1183): SQLite entry channel_report_back_columns + Alembic 0031_channel_report_back (single linear head off 0030), plus db/schema.py + db/tables.py so fresh builds stay correct. - schedule_executions.source_channel_agent (nullable TEXT): the agent whose channel binding owns the execution's INHERITED context (D1 Option A). Written only at the /task row-creation point; NULL for direct rows (reporter falls back to the executing agent). - telegram_group_configs.allow_proactive INTEGER DEFAULT 1: per-group completion-report consent, default ALLOW for existing AND new groups (opt-out mute; no backfill UPDATE needed). - create_task_execution accepts + inserts source_channel_agent; row mapper + ScheduleExecution model surface it. - AgentRef(schedule_executions.source_channel_agent, KEEP) so cascade_rename re-keys the binding agent (D1a); parity-test locks consciously updated (_AGENT_ID_COLUMNS + KEEP set). - Telegram group-config ops carry the flag (columns tuple, row mapper default-allow on NULL, update_group_config arm, explicit insert); database.py facade adds get_telegram_chat_link and converts the group-config passthrough to keyword args (eng M3). - TelegramGroupConfigResponse/UpdateRequest carry allow_proactive (Invariant #14; the response model IS the GET field allowlist). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(chat): persist inherited channel context at /task row creation (ent#265 D0) The ent#224 inheritance wire was severed: run_async_task threaded _inherited_channel_context's values into execute_task(source_channel=...), but execute_task writes channel columns ONLY in its no-execution_id creation branch — and the /task path always pre-creates the row in create_task_execution_and_activities. Every delegated row carried NULL channel context at terminal time, so the shipped Slack delegated report-back was latent dead code on its flagship path. - Resolve inheritance at the single row-creation point both the async and sync /task branches route through (the fork to _dispatch_async/_dispatch_sync happens AFTER creation), and persist all four fields on the row itself via db.create_task_execution. - _inherited_channel_context returns a 4-tuple: + source_channel_agent (D1 Option A — parent's own binding agent, else the parent's agent name; transitive across A→B→C; all-None when the parent lacks source_channel, so a channel-less child never carries a dangling agent pointer). - Provenance guard (security): db.get_execution(parent_id) is a global lookup; the inherited identity now also resolves a bot token. Agent caller (x_source_agent, already past the SELF-EXEC-001 spoof guard in derive_source_and_trigger) must BE the parent's executing agent; human caller must have access to the parent's agent. Failure → no inheritance, info log — fail-open to no-context, never to someone else's chat. - Remove the dead source_channel* threading from run_async_task (execute_task keeps its channel params — message_router uses them for direct turns). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(channels): Telegram completion report-back + failure-applier hook (ent#265) Telegram edition of the ent#224 Slack report-back: a Telegram-triggered long/delegated task posts its terminal back to the originating chat, threaded to the triggering message. channel_completion_report.py rework: - D10 resolver dispatch map (_CHANNEL_RESOLVERS: slack + telegram); SUPPORTED_CHANNELS derives from the map keys, so WhatsApp is additive. - D1 binding-agent resolution for BOTH channels: consent + bot token evaluate against binding_agent = row.source_channel_agent or row.agent_name — the bot the user actually addressed delivers (on Telegram no other bot even CAN deliver the DM). NULL column = legacy fallback, byte-identical pre-#265 behavior. Also fixes Slack's delegated case (previously suppressed whenever worker B wasn't bound to the originating channel); narrowing direction (channel consented to B but not to originating A → now suppressed) is intentional. - D2 Telegram consent: known group → is_active AND allow_proactive (default allow, opt-out mute); known DM chat link → consent-by-construction (the user cold-started the bot; a block is a 403 the send handles gracefully); unknown destination → suppress+log. - D5 rendering: pre-escape &/</> before _markdown_to_html (unescaped `<class 'ValueError'>` trips "can't parse entities" and the strip-HTML fallback deletes the substring), then post-conversion re-cap to 4096 ("message too long" is a 400 the parse-fallback does not catch). - D6 threading: reply_to_message_id when thread is numeric, DMs too; allow_sending_without_reply makes a deleted original safe. - D1c attribution: Telegram has no per-message sender name — when binding_agent != executing agent the head line names the worker. Slack keeps username=executing agent (unchanged). - D9 pin: effect_guard keeps agent_name = the EXECUTING agent (row.agent_name), never binding_agent — resolve_and_validate_execution fail-opens on mismatch, silently disarming dedup for exactly the delegated rows this feature exists for. - D4: failed send returns False INSIDE the guard (claim completes) — at-most-once bias, never blind-retry an ambiguous send. task_execution_service.py (D3, channel-agnostic — fixes Slack AC#2 too): the failure applier's CAS-won block emitted the #1578 event but never the channel report — the path agent-reported failure envelopes take. Sibling spawn added; CANCELLED envelopes report too (uniform with _write_terminal_and_gate). routers/telegram.py: PUT group-config passes allow_proactive through; the allow_proactive arm ONLY is human-only (reject_agent_principal — an agent-scoped key resolves to the owner and could self-grant consent, ent#223's own post-ship pitfall). TelegramChannelPanel.vue: per-group "Completion reports" opt-out checkbox in the panel's house idiom (updateGroup passthrough). Co-Authored-By: Claude Fable 5 <[email protected]> * test(channels): ent#265 suite + facade passthrough fix caught by it New tests/unit/test_265_telegram_completion_report.py (41 tests): - Wired-mock layer: Telegram delivery/consent/rendering decisions — delegated group report + threading, DM consent-by-construction, muted/inactive/unknown-destination suppression, graceful bot-cannot-post, inline-trigger no-double-post, D5 escape+cap, D1c attribution, D1 binding-agent resolution (telegram + slack) incl. the intentional Slack consent-narrowing pin (D1b). - Chokepoint layer: apply_result failure branch spawns the report on CAS-win only (D3), success-branch pin, CANCELLED-envelope report. - Real-DB layer (db_harness): D0 row READ-BACK inheritance tests (a SimpleNamespace mock row cannot see a severed write path — the exact reason ent#224 shipped broken), both provenance-guard arms, channel-less parent all-NULL, two-hop transitive root binding agent; REAL effect_guard replay with source_channel_agent != agent_name (D9/M1 — a binding_agent passthrough fail-opens resolution and posts twice → red); fan-out one-report-per-child (G3); live column SELECTs through db/tables.py metadata; group-config default-allow + kwargs round-trip (eng M3); router PUT round-trip incl. agent-principal 403 and the surgical-gate proof that trigger_mode stays agent-callable. Conscious test_224 edits: non-slack scope test → whatsapp-only (telegram grew a leg); consent fixture keyed on the binding agent. The read-back tests immediately caught a REAL gap: database.py's create_task_execution facade passthrough was missing source_channel_agent (the ops layer had it) — every /task dispatch would have raised TypeError. Fixed here; the exact severed-wire class D0 exists to kill. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): Dashboard type-to-filter — new §9.10, §9.9 seam note updated (ent#261) Trinity Rule #1: requirements before implementation. §9.10 specifies the / hotkey filter across Timeline/Grid/List — store-seam predicate, pre-query node invariant, pill honesty, Esc layering, chassis query-empty overlay, kbd hint, list-mode composition, and the deliberate timeline owner-filter behavior change. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(dashboard): / type-to-filter across timeline, grid, and list (ent#261) Store seam (network.js): non-persisted filterQuery + setFilterQuery; the visibleAgents seam splits into ownerFilteredAgents (tag ∘ owner, pre-query) and the query-aware visibleAgents (slug + display label via agentDisplayName, #1642). ALL THREE convertAgentsToNodes call sites now read the pre-query ownerFilteredAgents — incl. the 30s poll that previously rebuilt from the RAW list (nodes must never be query-filtered: timeline row enrichment would degrade after Esc). Dashboard chassis: document / keydown with guards (defaultPrevented/repeat, chords, IME, editable targets, open modals) + Firefox quick-find preventDefault; floating filter pill (open OR active — an applied-but-hidden filter is the dishonest state) with live 'X of Y match', Esc hint, x button; input-scoped Esc + gated document Esc backstop (tag-dropdown layered dismissal, native select skip); Enter blurs and keeps the filter; header kbd / toggle button (mouse/touch parity); ONE chassis query-empty overlay with panes MOUNTED underneath; true-empty onboarding CTA branches guarded && !filterActive; timeline :agents switched to the visibleAgents seam (owner filter now applies to timeline rows too — deliberate, release-noted); query cleared on unmount. AgentListPanel: N/M badge suppressed while the chassis query is active (two disagreeing denominators never render simultaneously). ReplayTimeline: data-agent test hook on row labels (no logic change). Co-Authored-By: Claude Fable 5 <[email protected]> * test(e2e): dashboard type-to-filter spec — 8 tests across all three modes (ent#261) Covers: grid live-filter + query-empty with the pane MOUNTED + Esc restore (@smoke); timeline row hiding via the :agents seam; list query-empty preceding the onboarding CTA + pill-x clear; editable-target guard + literal '/' inside the pill; kbd-hint toggle; non-persistence across reload; cross-mode filter survival + the document-Esc backstop after focus wanders; Enter blur-and-keep. Spec rules per plan: focus-wait before keyboard.type (nextTick focus race); regex count assertions (/^1 of \d+ match$/ — X is the claim, Y is environment). Full run defers to CI via the ui label. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): type-to-filter folded into the three dashboard flows + architecture note (ent#261) architecture.md: Grid-view block gains the type-to-filter seam sentence; the List-view block's seam description now covers all three panes. Flow deltas: grid — filter rides the absence-as-filtering layout path (pane stays mounted under the query-empty overlay); timeline — FILTER-001 gains a deliberately NOT-persisted row + a new ':agents = visibleAgents seam' section naming the owner-filter behavior change and the pre-query node invariant; list — D8 seam updated to landed state + the chassis-query ∘ panel-filter composition rules (badge suppression, overlay precedence). feature-flows.md changelog entry (no standalone flow doc, per plan D11). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(dashboard): review fixes — modal z-order, dual empty-state CTA, Esc scope, structural e2e backstop (ent#261) Four review findings on the type-to-filter, fixed in place: - CreateAgentModal was fixed z-10 — UNDER the new z-30 filter pill and z-20 query-empty overlay, so chassis chrome floated above the open modal. Raised to z-50, the house modal tier (SystemViewEditor / OnboardingWizard). Safe in all three mounts (wizard renders it v-if-exclusive with its own z-50 chrome). - AgentListPanel's filtered-empty card assumed the panel never mounts with a zero-agent prop — no longer true under a chassis query zero-match, so it rendered a second contradicting CTA under the query-empty overlay. Gated on a non-empty prop; the chassis overlay owns query-zero messaging (the behavior the list-view flow doc already described). e2e test 3 now pins it. - Document-Esc backstop generalized from the select-only guard to all editable targets: Esc inside the list panel's search box (or any other input/textarea/contenteditable) belongs to that control — it must not clear the chassis filter. Pill input unaffected (own handler stops). §9.10 wording updated to match. - e2e test 7's coordinate click (400,250) on the timeline pane could land on an agent row/toggle on seeded fleets — replaced with a structural pillInput.blur(). npm run build green; spec collects 8 tests. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): overlay-chrome z-order re-pricing + mount-invariant comments (ent#261 review) Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): sibling-route access-hardening class from the ent#264 review Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): sync pass — seam note in skill-assignment, Recent Updates row, dead skills-management link purge (ent#263) /sync-feature-flows verification pass over the branch diff: - skill-assignment.md: note that SkillsPanel's package-fact chips now render via the shared components/skills/ contract seam (extracted in ent#263) - feature-flows.md: Recent Updates row for ent#263; removed the stale 'Skills Management UI' index row — skills-management.md was split/archived long ago (the archive table records it) and the live row pointed at a missing file - library-page.md: repointed its two skills-management.md links (propagated from the stale index row) at skill-assignment.md Co-Authored-By: Claude Fable 5 <[email protected]> * fix(library): harden stripUserinfo against silent-no-op and non-parseable URL shapes; share it with SkillsPanel (ent#263 review) Adversarial testing of the display-layer credential scrubber proved five leak shapes. Two families: the regex fallback under-matched what new URL() rejects (git+ssh:// schemes, protocol-relative //user:token@host, leading whitespace), and — worse — schemeless/scp user:token@host shapes PARSE as a WHATWG URL with an opaque hostless path where .username/.password assignment is a silent no-op, so the credential sailed through the success lane untouched. - move stripUserinfo to the shared components/skills/contract.js seam - trust the parsed lane only when host is present AND the strip verifiably took (post-assignment username/password empty); otherwise fall through to a widened textual scrub (scheme charset [A-Za-z][\w+.-]*, protocol- relative, schemeless colon-user, trim) - variant analysis: SkillsPanel's library_empty state rendered the RAW stored URL to any agent accessor — now scrubbed through the same helper - verified by an executed 26-case suite (23 adversarial leak shapes ALL PASS + 3 must-survive-unmangled regressions: plain https, scp git@host:path, path-@ preserved) - durable class captured in docs/memory/learnings.md Co-Authored-By: Claude Fable 5 <[email protected]> * docs: purge the second dead skills-management link; cso --diff report (ent#263 review) - feature-flows.md Archived Flows table pointed at archive/skills-management.md, which does not exist (the archive/ dir never received it) — same dead-link class d23005af purged from the skills index; row now says 'document not preserved' and names the dedicated flows it split into - add the /cso --diff report for the ent#263 review: zero backend surface delta; one MEDIUM display-layer scrubber finding (proven, remediated in 820895bf with variant coverage); secrets/enterprise- disclosure/XSS/supply-chain/CI categories clean Co-Authored-By: Claude Fable 5 <[email protected]> * docs(channels): channel report-back flow + requirements — pays the ent#224 debt (ent#265) - requirements/public-access.md: NEW §15.1h "Channel Completion Report-Back (CHANNEL-REPORT — ent#224 Slack, ent#265 Telegram)" — generic mechanism (inherited-context-only, D0 row-creation persistence + provenance guard, binding-agent resolution, chokepoints incl. D3, effect-guard at-most-once, sanitize-before-truncate), per-channel consent units, the two-DM-consent- regimes rationale (F6), known v1 limits, the deliberate ungated proactive-send scope cut. (§15.1f was already taken by WHATSAPP-001 — plan's placement kept, id shifted to h.) - feature-flows/channel-completion-report.md: NEW flow doc — entry points, D0/D3 fixes, chokepoint coverage table with the v1 boundaries (lease-reaper, bulk sweeps, pull sink, operator-terminate, restart mid-inline-turn, FAILED→SUCCESS resurrection, fan-out per-child, pre-migration NULL rows), destination/consent resolution per channel, D1 identity design with every rejected alternative, failure modes, Testing. Pays the #1763 flow-doc debt (ent#224 shipped undocumented). - feature-flows.md: Recent Updates row + Collaboration-table entry. - telegram-integration.md: ent#265 section (column + toggle + pointer) + revision row. - task-completion-events.md: sibling-spawn paragraph (report rides beside the #1578 emit at the same CAS-won chokepoints incl. the failure applier). - architecture.md: services-catalog entry for channel_completion_report.py, schedule_executions DDL line for source_channel_agent, telegram DB-module line mentions allow_proactive. - learnings.md: the D0 class — a threaded parameter only one callee branch consumes is a severed wire; mock-row suites are blind to it AND to its facade-passthrough sibling (caught pre-merge by the row-read-back tests). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(channels): key the inheritance provenance guard on the principal, not the header (ent#265) The D0 provenance guard selected its arm from the raw `X-Source-Agent` header. The SELF-EXEC-001 spoof guard in `derive_source_and_trigger` only fires when `current_user.agent_name` is set, so for a human caller that header is unvalidated client input (routers/chat.py documents the identical trap for the resume-session IDOR). Setting it to the parent execution's own agent name — a value the row itself discloses — satisfied the agent arm trivially and skipped the human arm entirely: any user with access to ANY agent could POST /task with someone else's `parent_execution_id` and have that task's terminal reported into the parent agent's Telegram DM or Slack thread, delivered by a bot binding they do not own. Second, narrower issue in the same guard: the human arm used `can_user_access_agent`, which admits share recipients. Posting into a channel chat is a proactive-send capability and every other proactive surface is owner-gated (`OwnedAgentByName` for group sends) or per-recipient-consented (#321); a share recipient can already read the owner's execution ids (`GET /api/executions` is accessor-scoped), so an accessor arm let them push a report into the owner's chat. Fix: arms are selected by the authenticated principal — - agent-scoped key must BE the parent's executing agent, - human must OWN the parent agent (`can_user_share_agent`) or be admin, - connector key (consumption-only, ent#46) never inherits, - no principal at all refuses. `x_source_agent` is still passed, now for logging only. Three regression tests, each verified red against the pre-fix guard. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): header-selected auth-guard arms collapse to the weakest arm (ent#265) Second instance of a class the codebase already warned about: routers/chat.py documents the same X-Source-Agent trap for the resume-session IDOR, and the ent#265 provenance guard reproduced it a few hundred lines away. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design-system): system of record, builder contract, reference page + raw-color scanner & ratchet baseline Stands up the frontend design system's written layer per #1430: - docs/memory/design-system.md — system of record: token taxonomy, both-theme rules incl. the dark ink ladder, type/spacing/radius scales, 10-primitive catalog with exact token recipes, the data-loading motion standard (scanline beam + wipe reveal; first load animates, background refresh is invisible), and 28 UI Construction Principles - docs/memory/design-system-contract.md — condensed binding contract to load before any src/frontend change - docs/memory/design-system-reference.html — approved visual spec (self- contained; both themes; live motion demo) - src/frontend/scripts/scan-raw-colors.mjs — raw-color scanner aligned with check-design-tokens.mjs token families - src/frontend/raw-color-baseline.json — ratchet seed at dev@5b28999: 753 raw non-gray / 383 hardcoded colors; counts may only shrink - CLAUDE.md — Rule of Engagement #10 + Memory Files row making the design system the mandatory reference for frontend work Refs #1430 Co-Authored-By: Claude Fable 5 <[email protected]> * fix: fleet restart adopts rebuilt base images through the canonical lifecycle path (#1860) (#1912) * fix: route fleet restart through the canonical lifecycle path so agents adopt rebuilt base images (#1860) POST /api/ops/fleet/restart stopped/started agents with raw Docker calls, bypassing start_agent_internal — no config-drift predicate ran and a rebuilt trinity-agent-base was never adopted on "Restart All" (#1809's cold-start gate never fired). - lifecycle.restart_agent_internal(): the canonical stop→cold-start helper (explicit stop is load-bearing for the #1809 image predicate; future home of #1817's per-agent start lock) - restart_fleet routes through it; per-agent recreated/recreate_reason surfaced via explicit allowlist copy, summary.recreated count - skips ephemeral ghosts (config predicates aren't ephemeral-gated — a recreate would destroy a volume-less ghost workspace, ent#69) - reject_agent_principal beside assert_admin (the endpoint now replaces containers — Invariant #8 escalation rule, #1816 precedent) - single-flight Redis SETNX lock ops:fleet_restart (409 on contention, own-lease refresh, compare-and-delete release, fail-open) — guards the client-timeout→retry overlap (#799/#1817 wedge class) - partial-safe fleet_restart audit entry with a per-agent recreate map (restores the entry dropped in 0ec3a7fc); sync cleanup ordered before the awaited audit so a shutdown CancelledError can't leave the lock held - actionable containerless-recovery errors (#1559), context-stats cache invalidation, 16 mocked unit tests, flow/architecture docs, learnings, CSO diff report (PASS) Fixes #1860 Co-Authored-By: Claude Fable 5 <[email protected]> * fix: never flow a raw exception message into fleet-restart results (CodeQL py/stack-trace-exposure) Per-agent failure rows now carry HTTPException .detail (platform-authored) or the exception class name only; the full message + traceback go to the backend log (exc_info). The #1559 containerless recovery hint is preserved. Tests strengthened into leak regression guards (raw message asserted absent); flow-doc line refs re-verified. Refs #1860 Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> * feat(auth): bulk portal-session revocation primitive + operator client panel (#1902) * feat(auth): bulk portal-session revocation primitive + operator client panel The OSS half of an operator kill switch for signed-in portal clients. A client who signs in through sharing holds a 12-hour portal session with no way to end it short of a backend restart, which logs out everyone. `revoke_portal_sessions_for_email(email)` is the edition-agnostic primitive: OSS owns the mint, the decode and this bulk revoke; the entitled module that mints portal sessions decides WHEN to call it (the same split as the delegated mint). Mechanism is a per-email CUTOFF, not a jti list. `jti` is random per token and nothing indexes email -> issued jtis, so answering "which tokens does this address hold?" would need a write-side index maintained at every mint. One timestamp per email is O(1) to write and read, self-expiring at the max session lifetime (same bounded-growth property as the #187 blacklist, no sweep), and — the property that matters — covers every mint path by construction, since they all go through `create_portal_session_token`. That is the failure mode a hand-maintained index has and this does not. `create_portal_session_token` now stamps an explicit `iat` so tokens can be dated against the cutoff; set there rather than in `create_access_token` so no other token type's claim set changes. `decode_portal_session` rejects `iat <= cutoff`. Rounding toward revoking is deliberate: for a kill switch, a token minted in the same second as the revoke must die. A token with NO `iat` is treated as revoked — fail closed. Only sessions minted before this shipped lack one (all expired within PORTAL_SESSION_EXPIRE_HOURS of the upgrade), and only for an email an operator actively revoked; letting an undatable token survive an explicit kill switch is the worse failure. The Redis read stays fail-OPEN, matching #187 and the platform posture. That is why revocation is not the whole feature: the durable half lives in the entitled module and keeps working with Redis down. `revoke_...` returns a bool so a caller can report honestly instead of claiming a success the operator would act on. Frontend: `PortalClientsPanel.vue` on the Sharing tab — per-client log out / block / unblock with current state. Entitlement-gated (`client_portal`), so an OSS build renders nothing. Block is hidden for non-admins rather than offered and 403'd, and the panel reports a failed revoke as a failure rather than "signed out". It deliberately shows no live-session count: portal sessions are stateless JWTs with no server-side store, so any number would be a guess. Related to trinity-enterprise#281 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(ui): use the real status-danger design token in the portal clients panel `status-error-*` does not exist — the token family is success/warning/danger/info/urgent (tailwind.config.js), and `npm run check:tokens` caught every reference. No visual change intended: danger is the red alias the invented name was reaching for. Related to trinity-enterprise#281 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> * feat(skills): library lifecycle automation — auto-sync, fleet re-inject, removal-on-unassign (abilityai/trinity-enterprise#236) (#1883) * feat(skills): library lifecycle automation — auto-sync, fleet re-inject, removal-on-unassign Closes the three "Not Built" gaps in the skills lifecycle (requirements §21.1/§21.4). All three default OFF/no-op, so a zero-config install is unchanged. Removal-on-unassign - `compute_removal` is `compute_prune` against an empty new manifest, so path confinement, `..` rejection, and the cap live in one place and cannot drift. - `remove_skills` takes the SAME per-agent lock as injection (both mutate ~/.claude/skills and read-modify-write CLAUDE.md). Only manifest paths are deleted, so agent-authored files and runtime artifacts survive; a directory the removal empties is reaped via os.rmdir, which refuses a non-empty dir. - Wired into BOTH the single DELETE and the bulk PUT — the bulk PUT is the primary UI/MCP path and drops skills far more often. - The DB unassign is authoritative and always succeeds; a stopped agent, busy lock, or dead transport degrades to a named `removal_deferred:*`. - A partially-failed removal keeps the meta AND the .gitignore line: dropping the meta strands survivors as unmanaged orphans, and dropping the ignore line lets the 15-min auto-sync commit leftover injected files (#1595/#1596 class). Start-path reconciliation - The assignment row is gone by the time a stopped agent starts, so removal is reconciled, not replayed: the agent's platform-managed skill dirs are diffed against the assignment set. No tombstone table, no migration, and every removal route converges. Runs after injection and also at zero assigned skills — that is exactly the "unassigned the last skill" case. - Blast-radius guard: >10 removals for one agent refuses wholesale and alarms. A wiped agent_skills table is indistinguishable from a mass-unassign, and keeping files is the recoverable direction (#1638/#1644). Scheduled auto-sync + fleet re-inject - New leader-locked backend service (skills:sync:leader). Backend-hosted because the sweep must reach agent containers and the scheduler is platform-network-only. - Sweeps only when the library commit actually changed; running non-ghost agents; force=False so the ent#183 tree-SHA skip makes unchanged skills free; bounded concurrency; inject-lock contention is skip-and-report. - Honest aggregate report in Settings + operator alarm only when an agent failed. - Config re-read each cycle, so an interval change needs no restart. Durable sync status - `_last_sync`/`_last_commit_sha` were per-process; under `--workers 2` the worker answering /status was usually not the one that synced, so the panel showed a stale timestamp and could never show an error at all. Now mirrored to system_settings on both the success and failure branches, and the commit-changed comparison reads the durable row (the in-memory field would make every restart look like a change). Hardening found by /review and /cso on this branch - The persisted sync error is PAT-scrubbed: sync_library's outer handler passed a raw str(e), and the authenticated remote URL is an argument in the subprocess command list, so an OSError could carry a token into system_settings and the admin panel. - Cross-worker lock around the shared clone: scheduled + manual sync both run `git fetch` + `git reset --hard` on /data/skills-library. Contention returns 409 and writes no status row, so a contended click cannot paint "Last sync failed". - remove_skills re-reads assignments inside the lock and refuses a still-assigned skill, closing the bulk-PUT check-then-act race (#1445 pattern). - PUT /api/settings/skills-library is human-only (reject_agent_principal): it is the on-switch for an unattended fleet-wide write of SKILL.md files, which Claude executes as instructions. assert_admin answers "what role", never "is this a human" — third occurrence of the trinity-ops-agent#232 class. The remaining half of that chain (skills_library_url writable by an agent key via the generic settings PUT) is pre-existing and filed as abilityai/trinity-enterprise#293. Dedicated range-validated GET/PUT /api/settings/skills-library; the three keys are blocked on the unvalidated generic PUT. 58 new tests. Fixes abilityai/trinity-enterprise#236 * fix(skills): wire ent#236 tuning vars into both compose files + .env.example `SKILLS_RECONCILE_MAX_REMOVALS` and `SKILLS_FLEET_INJECT_CONCURRENCY` were read via os.getenv() but never reached the container — the #1056 / trinity-enterprise#31 packaging class. The reconcile-refusal alarm names the first var in its own remediation text ("raise SKILLS_RECONCILE_MAX_REMOVALS"), so on a deployed stack the operator was told to turn a lever that does not exist, leaving a legitimate mass-unassign permanently blocked at the default cap of 10. Found by /validate-pr on PR #1883. * fix(ui): agent tab panel polish — card borders, section spacing, and an honest Sync-now affordance Three cosmetic fixes plus one UX gap on the agent detail tabs. - SkillsPanel had no card wrapper, so its content sat flush against the tab bar unlike every sibling tab. Wrapped in the same card the other panels use. - FoldersPanel and InfoPanel each had a `v-else` content wrapper with no spacing class, so the root `space-y-6` never reached the cards inside and they rendered touching. Same bug in both files. - SkillsPanel: saving assignments writes the DB rows, but the files only reach the container on a sync or the next agent start. That was stated in muted text above the button, which is easy to miss — an operator can save, message the agent, and be told the skill doesn't exist, because it isn't there yet. "Sync now" now goes prominent while that gap is open, and only while the agent is running (shouting at a disabled control helps nobody). A failed or 409-busy sync keeps it lit, since the gap is still open. * fix(ui): inset the Settings and Skills tab content like every other tab 8 of the agent-detail tab wrappers use p-6 (overview, info, brain, dashboard, schedules, playbooks, git, folders). Settings and Skills had none, so their cards ran flush into the enclosing panel's left and right edges instead of sitting inset like the rest. * fix(skills): re-clone a library path that is not a repository, and make the panel's failures actionable Three fixes found while testing this PR on a live instance. All pre-existing on dev, but each is sharpened by putting sync on an unattended timer. 1. sync_library() chose pull-vs-clone on `library_path.exists()` — directory existence, not repo-ness. A path holding no `.git` (clone interrupted by a full disk, a stray mkdir, a restored backup) failed `git pull` with "not a git repository" on every attempt, with nothing able to re-clone: permanent, and recoverable only by shell access. Now tests for `.git` and re-clones. Detecting it is only half a fix, since `git clone` refuses a non-empty destination — so a non-repo directory is moved aside first. Renamed, never deleted: the platform owns the path exclusively so removal would probably be safe, but "probably safe" is not the standard for an unattended timer deleting a directory derived from an operator-supplied setting (#1638/#1644). One quarantine is kept, so a recurring fault cannot grow without bound. 2. syncSkillsLibrary() saves settings first (setting showSuccess), then syncs; the catch set `error` without clearing it, so a failed sync showed "Settings saved successfully!" and "Clone failed" together. Both true, which is precisely what makes the pair untrustworthy. 3. The panel never said a private library needs a GitHub PAT — it is in two internal docs only, and what an operator hits is raw git ("could not read Username"), which names no remedy and does not hint that the PAT field is one section above. Added that line. The error-string mapping is deliberately NOT done: matching git stderr is brittle across versions and locales, and the raw error is at least surfaced rather than swallowed. Tests: 5 new (4 fail without the fix). Also fixes 7 existing tests that created the library path without `.git` — under the corrected predicate they took the clone path and reached for the network; the suite drops 5.01s -> 0.62s. * fix: ownership-checked fleet-restart lease with loss detection + acquire inside try/finally (#1919) (#1928) The per-iteration refresh was a bare EXPIRE gated on a local flag — after a TTL lapse it extended a concurrent caller's lease while both loops ran. The refresh is now a pre-action ownership gate (GET-compare via the shared redis_breaker_util.lock_token_matches): a foreign token stops the run with honest partial accounting (summary/audit gain processed + stopped_early), an absent token is re-acquired via SETNX so an unraced run completes instead of aborting, EXPIRE→0 routes to the absent path, and refresh Redis errors stay fail-open with one throttled warning per run. list_all_agents_fast() moved inside the try/finally so nothing can ever leak the lock between acquire and release; an abnormal exit audits as stopped_early="error" + exception class name only. TTL 900→2100, sized above the slowest single agent (skill injection alone is bounded at 1800s) so a mid-agent lapse is no longer arithmetically guaranteed. Release stays compare-and-delete, attempted even after detected loss (foreign-safe by construction). +11 unit tests (27 total in the file); live-validated on the local stack (foreign takeover mid-run, absent re-acquire to completion, 409 concurrency, TTL 2098 observed, release verified). Sibling hand-rolled lock sites and the system_seed_service unconditional release → #1920. Fixes #1919 Co-authored-by: Claude Fable 5 <[email protected]> * fix(templates): contain local: template ids and stop deriving credential paths from name: (#1900) (#1935) * fix(templates): contain local: template id resolution on the read path (#1900) `GET /api/templates/{template_id:path}` handed `local:<name>` straight to `get_local_template`, which joined `<name>` onto the templates root with no validation. The `:path` converter permits `/`, so `local:../<x>`, `local:/<abs>/<x>` and a root-escaping symlink each read `<escaped-dir>/template.yaml` and echoed its contents in an authenticated 200. Reachable by any authenticated principal of any role — including an agent-scoped MCP key, so a prompt-injected agent qualifies. In a container the reachable set includes `/data/deployed-templates/<victim>`, where every user's uploaded template archive lands: a cross-tenant read. Two corrections to the issue's framing, both verified here: * it is NOT arbitrary file read — the filename is fixed (`template.yaml`), it must parse as a YAML mapping, and only a fixed key set is echoed. But those keys' VALUES are arbitrary YAML subtrees, not just strings. * `local:..` alone is not an existence oracle: a directory with no `template.yaml` returns the same 404 as an unknown id. Fix: `contained_template_dir(name, root)` — the two-step barrier the CREATE path has had since #950 (`crud._safe_local_template_path`), brought to the read path. A name allowlist runs BEFORE any path math (this is also what CodeQL recognises as a `py/path-injection` barrier; resolve-only was flagged high-severity twice on this codebase), then `resolve()` on BOTH sides plus `is_relative_to`. `str.startswith` is not equivalent — it passes the sibling escape `<root>-evil`. An escaping id returns `None`, so the router's 404 stays byte-identical to an unknown template: no error code, no path, no root name. A distinct error would be a NEW enumeration oracle, which is what #1759's single-sentence 404 exists to close. Rejections log at DEBUG, sanitized — the endpoint has no rate limit, so a per-rejection WARNING would be an authenticated log-flood primitive. The helper is public: the remote-template-registry work (trinity-enterprise#14) edits this same resolver family in this same module and should import it rather than copy it. Tests: every rejection test PLANTS a real `template.yaml` at the escaped location, because unpatched code returns `None` for any id whose target simply does not exist — a rejection test with nothing planted is green before and after and proves nothing. Each is labelled REPRO (verified red pre-fix) or HYGIENE (cannot be made red; contract only). The router guard lives in `tests/unit/` because no gating CI job collects `tests/test_templates.py`. `test_1900_containment_survives_a_symlinked_root` is the landmine guard for resolving both sides: a half-resolved variant passes all 130 pre-existing tests and only that test catches it. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(templates): stage .mcp.json from the validated template dir, not template name: (#1900) The second traversal sink, found by this issue's own AC #4 audit ("audit the by-name create path for the same join"). It is NOT the create path's `local:` id resolution — that has been contained since #950/#1759 via `crud._safe_local_template_path`, applied at both seams #1759 named. It is the create path's CREDENTIAL STAGING, which threw that validated path away and re-derived a directory from scratch: template_name = template_data.get("name", "") # untrusted mcp_template_path = templates_dir / template_name / ".mcp.json" `name:` comes from an uploaded template.yaml, so any `creator` reaches it via `deploy_local_agent`. `name: ../../data/deployed-templates/<victim>` read another tenant's `.mcp.json` — a credential-bearing file type under Invariant #12 — into the attacker's OWN agent, where they read it at leisure. A victim who hardcoded a token rather than a `${VAR}` placeholder leaks it. Assessed on its own axes, NOT inherited from the read sink: different trigger (`creator` role + an upload + an agent create, vs a bare authenticated GET) and a higher impact ceiling (credential values, not template metadata). Also P2, for different reasons. The derivation was also simply wrong. `name:` is not a directory name — 5 shipped templates declare a display string there ("Test Echo Agent"), so `local:test-echo` resolved to `<curated>/Test Echo Agent/.mcp.json`, which does not exist. That kills the "validate the name" framing: the value should not resolve paths at all. Fix is root-cause, not another guard: `_stage_config_files` already calls `_safe_local_template_path` itself for the `/template` bind decision, so the validated directory is available in the same function. Extract the two-root ladder as `_resolve_local_template_dir` and pass its result as `template_base_path`. The untrusted join is gone from the live path, and the #1759 "seams must agree" property becomes structural across all THREE seams (resolver, bind decision, credential stager) instead of two. Deliberately NOT threaded through `_TemplateResolution` or the return tuple: `_resolve_local_template` returns a 2-tuple that three existing tests depend on, two as monkeypatched `lambda config: ({}, None)` doubles — widening it breaks the test doubles, not just the callers. Its signature, its return arity, `_safe_local_template_path`, `_LOCAL_TEMPLATE_ROOTS`, and everything inside the CodeQL-sensitive `if template_yaml.exists():` block are untouched (#1793 had to revert exactly that reshape). The residual `template_base_path is None` arm is kept and made fail-closed: it is a public function with a `template_base_path=None` default, so a future caller can still reach it. It now contains through the same barrier as the id, which also absorbs a non-string `name:` — `Path(root) / 123` raised TypeError, i.e. an uncaught HTTP 500 during agent creation (the ent#128 bug class, one seam over). One disclosed behaviour change: a deploy-local template that BOTH declares `credentials.mcp_servers` AND ships a `.mcp.json` now gets `${VAR}` substitution, where the old curated-root lookup always missed. Verified no collision with `deploy._prepopulate_workspace_from_template`, which writes the archive's raw copy into the workspace volume: `startup.sh` copies `/generated-creds/.mcp.json` unconditionally (gated only on the directory existing) and AFTER the template-copy block (gated on `.trinity-initialized`), so the substituted file deterministically wins — which is the intended behaviour, the raw copy still carrying unsubstituted placeholders. Not one of the 26 shipped curated templates contains a `.mcp.json`, so the curated rows are provably unchanged. The crud seam tests are mandatory, not decorative: every service-level test calls `generate_credential_files` directly, so an "extracted but never wired" mistake leaves all of them green while deploy-local resolution silently regresses into the fallback arm. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: record the #1900 containment contracts for template id + credential staging Rule #1 (requirements before implementation) — `core-agent.md`: * §4.1 gains the **read-path resolution contract** as a sibling to the existing create-time contract: `GET /api/templates/{id}` resolves `local:<name>` through the same two-step barrier the create path has had since #950, and a failing name returns a 404 byte-identical to an unknown template (the #1759 non-disclosure rule). Records the deliberate, known asymmetry that `get_local_templates()` still enumerates by `iterdir()` and so could LIST a root-escaping symlink that detail and create both refuse — the listing is the outlier, and planting one needs local filesystem write access, not a request. * §4.3 records that the `credentials.mcp_servers` template lookup now resolves from the validated path rather than the template's own untrusted `name:` field, including the one disclosed behaviour change (deploy-local templates now get `${VAR}` substitution) and why the substituted file wins over the archive's raw copy. `architecture.md` gets one clause on the `templates.py` router catalog entry (the catalog rule caps entries at 2 lines, and no Cross-Cutting Subsystems block is warranted). A bug fix would normally be commit-message-only under the tiered-docs rule; the exception is that this ships a public, importable containment primitive in the exact module and resolver family the remote template registry (trinity-enterprise#14) will edit, and one catalog clause is the cheapest way that author finds it instead of copying the flaw. Not updated, deliberately: no feature-flow doc (no new vertical slice), no user docs (no user-visible change for honest callers), no schema/migration (no DB change, so the dual-track SQLite/Alembic rule does not apply). Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(feature-flows): sync template-processing + local-agent-deploy for #1900 `/sync-feature-flows` was NOT a no-op here — three concrete staleness points in `template-processing.md`, which owns the `local:` resolution surface: * The inlined two-root ladder is now `_resolve_local_template_dir`; the code block showed the pre-extraction form. * "**Two** seams read `_LOCAL_TEMPLATE_ROOTS` and must stay in agreement" was the #1759 claim and is now wrong in the direction that matters: there was always a third seam (the credential-file stager) which did NOT agree — it re-derived the directory from the template's untrusted `name:`. Corrected to three, with the extraction as the structural guarantee. * `generate_credential_files` was cited by stale line range (`:228-299`) and documented none of where the `.mcp.json` template is actually located. Replaced the fragile line-range citation with a symbol reference and added the provenance, the residual fail-closed arm, and the disclosed deploy-local substitution delta. Also documents the read-path containment (`get_local_template` → `contained_template_dir`) beside the existing #1513 catalog-curation note, including the deliberate list-vs-detail asymmetry for a planted symlink. `local-agent-deploy.md` gets one line at the credential-merge step: a deploy-local template's `.mcp.json` now resolves from the deploy-local directory, so a hostile `name:` cannot read another tenant's file and `${VAR}` substitution finally applies to that template. `credential-injection.md` was checked and NOT touched — its `.mcp.json` references are unrelated (credential inject/export/import), and the template lookup live…
…t (ent#435, CWE-312) (#2330) * fix(security): encrypt credential-bearing system_settings rows at rest (ent#435, CWE-312) Six `system_settings` rows held LIVE third-party credentials in cleartext — `anthropic_api_key`, `github_pat`, `google_api_key`, `slack_app_token`, `slack_client_secret`, `slack_signing_secret` — while Architectural Invariant #12's own table read as though everything was covered. Every DB dump, backup, replica and snapshot therefore carried usable tokens (backups being exactly the artifact most likely to travel), and any read path to the database yielded working credentials WITHOUT needing CREDENTIAL_ENCRYPTION_KEY. `platform-settings.md` was worse than silent about it: security consideration #5 advertised the defect as a control ("stored in SQLite ... encrypted at rest if filesystem supports it"), which protects a powered-off disk and nothing that moves. That bullet is rewritten to say what was actually true and why. The key NAME moves, not just the value. Each secret becomes an AES-256-GCM envelope under `<key>_encrypted` and the cleartext row is DELETED. Leaving an encrypted value under the original name would keep "is this install encrypted?" unanswerable by inspection — which IS the reported defect, not a cosmetic detail. With the rename, the reporter's own verification query returning nothing is the proof, and the sink guard keeps it true. The read path lazily migrates. A one-shot migration converts disk once, but a restored pre-fix backup, a rollback-then-roll-forward, or a direct DB write can put cleartext back and only the reader would notice. `_resolve_secret_setting` resolves encrypted -> legacy-encrypted-and-deleted-on-sight -> env -> "", so cleartext is transient by construction rather than merely absent right now. Steady state is unchanged: while the encrypted row exists the legacy key is never read (pinned by a byte-equality test — a rewrite would change the nonce). Fail directions are deliberately opposite. Read fails OPEN to env (an unreadable envelope must not 500 the agent-start path) but never down to a stale legacy row, which would resurrect a credential the operator had replaced. Write fails CLOSED: no encryption key means refuse, never silently store cleartext. The guard is at the SINK, not only on the routes. `db.set_setting` raises `SecretSettingWriteError` (mapped to 422) for a registered secret key or any merely credential-shaped key (`*_api_key`/`*_token`/`*_secret`/`*_pat`/ `*_password`/`*_credentials`). Two reasons it cannot live on the routes alone: `system_settings` has four writers, and the generic `PUT /api/settings/{key}` catch-all can address ANY key — the same door #506, #1609, ent#12, #1644, ent#14 and ent#346 each found standing open. The explicit set gives a precise refusal with a pointer; the shape heuristic catches the NEXT secret nobody registers. Writing a `*_encrypted` key raw is refused too, since a hand-pasted string would land as a row every reader then fails to decrypt (the #736 rationale). `slack_client_id` is a reasoned exemption, not an omission: an OAuth client_id is a public identifier that `slack_service.get_oauth_url` puts verbatim into the browser-visible authorize URL (the `whatsapp_bindings.account_sid` "(public)" precedent). Recorded with its reason in `PUBLIC_CREDENTIAL_SHAPED_KEYS` so a later reader can tell reviewed from overlooked, and pinned by a test. Dual-track per Invariant #9: `secret_settings_encryption` (SQLite) and Alembic `0041_secret_settings_encryption` (PostgreSQL — the backend the defect was reported on, so not the afterthought). Both call ONE `plan_migration`: the two drivers cannot share SQL, but they must not disagree on policy. Hard-fails on a missing encryption key only when there is something to encrypt, so a fresh install still boots (the #453 choice, refined). `downgrade()` is a deliberate no-op — the honest inverse is "write these live credentials back in cleartext". Found in passing and fixed with it: `rotate-credential-key.py` sweeps COLUMNS, so `elevenlabs_api_key_encrypted` (ent#117) and `a2a_outbound_endpoints_encrypted` (#736) — envelope-in-a-ROW — were invisible to every key rotation, leaving them readable only via the secondary key and dead the moment it was removed. It gains a row-keyed `system_settings` pass whose membership derives from the policy module, so a newly-registered credential setting joins rotation automatically. Encryption protects the database going forward only. Historical backups still hold the plaintext, so the runbook's headline instruction is ROTATE: docs/migrations/SECRET_SETTINGS_ENCRYPTION_2026-08.md. Guards: tests/unit/test_ent435_settings_sink_guard.py (AST — every `system_settings` writer is gated or listed with the reason it cannot carry a credential; OSS tree only, the private submodule owns its twin per #1677). Related to Abilityai/trinity-enterprise#435 * fix(settings): a blank credential write unsets rather than storing an empty envelope (ent#435) Found while testing the ent#435 encryption change: `set_secret_setting(key, "")` stored an AES-256-GCM envelope OF an empty string. Resolution was unaffected — the decrypted `""` is falsy, so every reader fell through to the env var exactly as before — but the row's mere existence made `has_secret_setting` true, so the `source: settings|env` field on the admin status endpoints reported "settings" for a credential that actually resolves from the environment. Pre-ent#435 a blank write stored `''`, which readers treated as falsy and fell through the same way, and `bool(db.get_setting_value(...))` on `''` was False — so "settings" was never reported. Clearing instead of storing preserves the original resolution AND the original source reporting, which makes this a divergence introduced by ent#435 rather than a pre-existing behaviour. Related to Abilityai/trinity-enterprise#435 * fix(settings): name the upgrade in the fail-closed encryption-key error (ent#435) The ent#435 migration refuses to boot when `CREDENTIAL_ENCRYPTION_KEY` is unset AND there are cleartext credentials to encrypt. That refusal is correct — the alternative is booting with the credentials still readable in every dump — but it surfaced as the generic `CredentialEncryptionService` message, which says what to set and nothing about why it suddenly matters. Almost no install can hit this: `start.sh` has auto-generated the key via `ensure_hex32_secret` since v0.6.0 (2026-06-01), three weeks BEFORE it started generating `AGENT_AUTH_SECRET`, so any install with a working agent fleet provably has one. The gap is an install provisioned by a bare `docker compose up` — compose defaults the variable to empty and `.env.example` ships it blank — that ALSO configured credentials through the UI. For that operator the platform has always worked, so a bare "encryption key not configured" gives no clue that an upgrade is what changed. `MissingEncryptionKeyError` now names ent#435, states why refusing to start is deliberate, gives the one-line fix, and points at the runbook. It subclasses ValueError, so the migration runner's failure path and any `except ValueError` caller are unchanged; the failing credential's VALUE never appears in the message (asserted). Verified at container level: exit 1, full message in the log, cleartext row preserved. Runbook gains the same provenance so the rare case is diagnosable from the docs as well as the log. Related to Abilityai/trinity-enterprise#435 * test: stub the three ent#435 settings helpers for the standalone settings.py load CI's regression-diff caught this: the 4 `test_telegram_webhook_backfill` tests passed on base and failed on head. That test loads `routers/settings.py` as a standalone module against a hand-built `services.settings_service` stub whose attributes are enumerated explicitly — the stub is extended per-issue by convention (#1310, #1129, #506, #1609, ent#236). ent#435 added `set_secret_setting` / `clear_secret_setting` / `has_secret_setting` to that router's module-level import, so the load raised `ImportError: cannot import name 'set_secret_setting'`. Proven both directions under CI's ordering (a prior test must seed `services.telemetry_sharing_service` into sys.modules for this file to load at all — a pre-existing order-dependency, unrelated): without the stub entries 4 fail with that ImportError, with them 14 pass. Worth recording why this was not caught locally: in a Python 3.12 venv these 4 fail on BOTH base and head for an unrelated reason (`cannot import name 'telemetry_sharing_service'`), so a local base-vs-head comparison showed "identical, pre-existing" and hid a genuine head-only regression. The 3.13 image that matches CI is the environment that distinguishes them. Related to Abilityai/trinity-enterprise#435 * docs(migrations): the ent#435 sweep is one transaction, not a commit per row Found on re-review: both migration docstrings claimed "write-then-delete per row, so a crash mid-sweep leaves cleartext intact". The safety conclusion was right but the mechanism described was not — the SQLite sweep issues a single `conn.commit()` after the loop, and the Alembic revision runs inside Alembic's own migration transaction. Both are all-or-nothing across every row. That distinction matters more than a wording nit: single-transaction is the STRONGER property (a crash rolls back rather than leaving three of six credentials converted, and the runner never records the migration as applied), so a future reader trusting the old docstring could "fix" the loop into a per-row commit and quietly trade atomicity for a partially-converted state whose only recovery is the read-path lazy migration. Docstrings now describe what the code does and say explicitly not to make that change. `test_sqlite_sweep_is_atomic_across_rows` pins it: failing the DELETE of the second row leaves all three cleartext rows intact and zero encrypted rows, and a clean re-run converges completely — so the property is asserted rather than asserted-in-prose. The per-row, two-transaction description on the SERVICE path (`_migrate_legacy_secret_setting`) is accurate and unchanged — that one really is two separate db calls, deliberately, because it runs on a read path. Related to Abilityai/trinity-enterprise#435
…ce key adopts the credential-less fleet (Abilityai#2572) (Abilityai#2741) * feat(subscriptions): credential-less agents can adopt an available subscription SUB-003 only ever moves an agent that ALREADY has a subscription (its precondition 2), and registering a subscription assigned nobody. So on an instance with no ANTHROPIC_API_KEY every pre-existing agent sat in api_key mode with nothing behind it. Neither feature is wrong; nothing covered the gap. `subscription_service.adopt_for_credentialless_agents` is that cover: one predicate, one loop, two exclusions. Phase A decides and persists inside the request (every blocking call in asyncio.to_thread), so the panel's immediate `GET /api/subscriptions` refetch is already correct; Phase B applies to containers in the background under the Abilityai#799 per-agent lock, re-verifying the assignment before each restart because Phase A itself creates SUB-003 eligibility. Three things are load-bearing and easy to undo by accident: - Condition 1 resolves through get_anthropic_api_key() — encrypted row, legacy row, then os.getenv. Never has_secret_setting(), which is DB-only and presence-only and would adopt a whole fleet off a working env key. - The runtime gate is LABEL-STRICT. `agent_container_runtimes` defaults a missing label to "claude-code" and `is_claude_runtime(None)` is True, so the new `agent_container_runtime_labels` sibling preserves absence: a container with no runtime label (trinity-system has none) is not evidence of a Claude runtime. An unreadable Docker adopts nobody — the opposite resolution to ent#403's documented fail-open, because that call site decides a UI affordance and this one writes a credential assignment. - Phase B skips the system agent (_restart_agent stops first, so Abilityai#1816's "never recreate a running trinity-system" guard is bypassed by construction), and ephemeral ghosts are skipped by the sweep entirely — the AUTH recreate predicate carries no ghost exemption, so restarting an adopted ghost destroys its workspace mid-budget. Auth-MODE change, so the apply is _restart_agent; _hot_reload_subscription_token keeps its producer invariant. SUB-003's preconditions are unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB * fix(subscriptions): registering a subscription adopts the credential-less fleet Trigger A1. The hook sits beside the Abilityai#1089 key-rollover fan-out and copies its swallow-everything contract: the sweep must never fail a registration whose credential is already stored. Only Phase A is awaited, so the Settings panel's refetch on the next line already lists the adopted agents. The body parameter is renamed `request` -> `payload` because the handler now also takes the injected Request. Two things called `request` in one handler is how a log line inside an `except` raises AttributeError, which would escape to the outer handler and return 500 with the credential stored. All six body-param sites move, including the two inside logger calls, and the three positional calls in the existing hot-reload suite are updated. Also adds the two manual-assignment audit rows. AC5 asks for adoption to be recorded "alongside manual assignment", which is only literally true if the manual move is recorded too — Abilityai#2421 found this router carried no platform_audit_service call at all, so "how did agent X get onto this subscription?" answered with a false negative for every manual move. This takes `subscription_assign` / `subscription_clear` only; Abilityai#2421's register / delete / settings actions stay unclaimed. Subscription id and name in details, never a token (Invariant Abilityai#12). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB * fix(settings): deleting the instance API key adopts the credential-less fleet Trigger A2. The canonical migration off a metered key is *register the subscription, then delete the key*. In that order Trigger A1 does nothing — the key still resolves, so the sweep short-circuits — and the deletion then strands the whole fleet in exactly the reported state with no trigger left. Both reachable clear paths are hooked. The dedicated DELETE /api/settings/api-keys/anthropic is the one the UI uses; the generic DELETE /api/settings/{key} reaches the same rows through db.delete_setting, which — unlike db.set_setting — carries no ent#435 sink guard, so it is a real second door rather than a theoretical one. Both are gated on the route's existing `deleted` truthiness, so a no-op DELETE stays inert, and both are already assert_admin-gated, so the hook inherits an identical human-only boundary and adds no reachable principal. The hook deliberately sits on the routes, not on clear_secret_setting: that leaf also serves github_pat and the Slack keys. A third clear path exists at set_secret_setting's blank-write branch and is unreachable for this key — update_anthropic_key 400s anything not starting `sk-ant-`, and the generic PUT is refused by ent#435's sink guard. Noted, not fixed here: db.delete_setting has no delete-side twin of that sink guard. Closing it would change DELETE of any credential-shaped key from 200 to 422 — ent#435's scope, not this bug's. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB * test(subscriptions): pin credential-less adoption at the service and router boundary Every test executes the path against a real schema (db_harness) rather than asserting on source text (Abilityai#2659). The only stubs are the two edges a unit test cannot have: the batch Docker runtime read and the container restart. The ones that earn their keep are the negatives. A working instance key adopts nobody and never even asks Docker; an agent already on a subscription and one opted out of the platform key are untouched; a codex agent, a container-less agent and a container with no runtime label are each skipped for a different reason, and an unreadable Docker adopts nobody at all. T16 drives register-then-delete end to end at both routers — the ordering the key-deletion trigger exists for — and T17 deletes the settings row while ANTHROPIC_API_KEY is still in the environment and asserts zero adoptions, which is the test that fails if condition 1 is ever "simplified" to has_secret_setting(). T11b/T11c pin the two destructive exclusions, T11d pins the under-lock re-verify, T12 drives the REAL headroom ranker rather than asserting a mock's return value, and T13 pins the already-shipped Abilityai#74 create path so that half of the decision survives by behaviour rather than by luck. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB * docs(subscriptions): record the credential-less adoption triggers and their guards Requirements (security.md): 20.3's workflow gains the automatic step; 20.3a is retitled to cover all three triggers and now carries the five-condition predicate, the two never-move guards, the phase split, the two Phase-B exclusions, the container-less known bound, the fail-closed Docker rule and the owner-blind decision; 20.5a's "Cut: Tier 4 bulk auto-assign" is amended rather than silently contradicted — the credential-less subset is delivered, bulk migration of agents with a working credential stays cut; SEC-001's CREDENTIALS category lists the four new event actions. Feature flows: subscription-management.md owns the delta (the Abilityai#74 section becomes the three-trigger section, Flow 1's overview / sequence diagram / endpoint block show the awaited decide phase and the backgrounded apply, both POST entry-point rows note the sweep, revision history row added). platform-settings.md gains the two Anthropic-key DELETE rows and a downstream pointer, because that flow owns Settings -> API Keys. subscription-auto-switch.md gets one cross-reference under "Not covered" so nothing there contradicts it — SUB-003 stays failure-driven and its precondition 2 is untouched. Architecture: backend.md's subscriptions / settings / subscription_service / subscription_auto_switch bullets; agent-lifecycle.md's Abilityai#1089 section gains the fourth producer, the one that deliberately takes the recreate branch. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB * test(subscriptions): a non-admin cannot reach the adoption sweep on either A2 route The sweep GRANTS a credential, so it stays human-admin-only by inheriting each delete route's existing assert_admin rather than adding a gate of its own. Asserted on BOTH routes, because "a guard applied to one of two sibling codepaths" is the repo's most recurrent escape class and this change has exactly that shape. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB * docs(workspace): note the label-strict sibling of the sparse runtime read The sparse-`attrs["Labels"]` trap this flow documents now has two call sites with opposite correct answers: the model control fails OPEN to "claude-code", and Abilityai#2572's credential-less subscription sweep must fail CLOSED because a missing label is not evidence of a Claude runtime (trinity-system carries none). Recorded here so a future change to the sparse shape moves both. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB * fix(subscriptions): an aborted adoption sweep is on the audit record too The sweep-summary row exists so that "adopted 0 of 40 because Docker was unreadable" is distinguishable in `audit_log` from "nothing to do" — that is its stated rationale in the plan and in the shipped test's own docstring. But the unreadable-Docker arm returned before writing one, so the single case the row was designed for left the trail saying nothing happened, with an ERROR log as the operator's only signal and `agent_count` staying 0 either way. Write the summary row on that abort, carrying a `skipped.docker_unreadable` count so the reason is in the record rather than only in the log. The other early returns stay silent on purpose: "no credential-less agents" and "no assignable subscription" are genuinely nothing-to-do, not a failed decision. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_017YoUiMQgPj3BeFMpyYpfkB --------- Co-authored-by: trinity-ability <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: sim <[email protected]>
…L, not one per sync (#2744) (#2777) * docs(skills): the terminal legacy-adoption refusal is bounded by class (#2744) Rule #1: the requirements delta lands before the code. §21.1.3 described adoption as "idempotent and fail-soft" and said nothing about the refusal's ALERTING. `_adopt_legacy_clone` runs as the first statement of every `sync_library()`, so on an install that is past migration but still carries a non-matching `skills_library_url` the terminal refusal files a fresh `priority: "high"`, `expires_at: None` operator-queue item on every sync — unattended under the ent#236 auto-sync loop (300s floor ⇒ 288 rows/day), never expiring, and un-dismissable because each row carries a new timestamped `request_id`. The rule this states: that refusal is the designed resting state of a migrated install, not a failure, so it is `low` + `logger.info` with a stable URL-derived id whose family prefix is reserved; the two genuine failure branches keep `high` and their repeat-visible ids by product decision. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_0176XEqK8PTCAK5K6yZURQLv * test(skills): pin the legacy-adoption alert's cadence, severity and echo (#2744) TDD — RED on this commit, green on the next. Proven red for the right reason, not merely red: test_n_syncs_..._exactly_one_item 5 distinct timestamped ids test_a_different_refused_url_... frozen clock ⇒ both URLs share one id test_the_terminal_refusal_is_not_high... priority "high", logger.error test_the_stable_id_is_reserved_... 'skills-legacy-adoption-<ts>' unreserved test_a_pat_bearing_url_is_never_echoed... the PAT is in context.url AND the log test_the_actionable_branches_keep_high... GREEN on base, by design (AC 4) The last one is the anti-regression half: it pins behaviour the fix must NOT change, and goes red only if the low/stable-id treatment is applied to all three call sites instead of the one the issue names. Harness notes, both load-bearing. `_record_adoption_failure` imports `utc_now_iso` INSIDE its body, so the patch target is `utils.helpers` — patching `services.skill_service.utc_now_iso` binds nothing and yields a vacuous test. And `validate_skills_library_url` does a live `socket.getaddrinfo`: on a sandboxed resolver a terminal-branch test would silently drive the validation-reject branch and fail as "5 distinct ids" / "priority is high", reading exactly like the fix regressing — so DNS is stubbed to the `gaierror` that function already tolerates, and every terminal-branch test additionally pins which branch produced its item. New file rather than an append to test_ent346_skills_source_injection.py: Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_0176XEqK8PTCAK5K6yZURQLv * fix(skills): the legacy-adoption refusal files one row per URL, not one per sync (#2744) `_adopt_legacy_clone()` is the first statement of every `sync_library()`. On an install that is past migration but still carries a `skills_library_url` matching no configured source, the terminal "already has sources" branch called `_record_adoption_failure`, which minted a TIMESTAMPED `request_id` at `priority: "high"` with `expires_at: None`. One permanent, high-priority, operator-unclearable row per sync, forever — 17 of them (~17% of everything pending) on the reporting install, and 288/day at the ent#236 auto-sync floor. Two behaviour changes, on ONE branch: * a STABLE, URL-keyed id (`skills-legacy-adoption-refused-{sha256(url)[:12]}`) so `create_item`'s `(agent_name, request_id)` ON CONFLICT DO NOTHING collapses N syncs to exactly one row — and, since that conflict target ignores `status`, an operator's dismissal finally sticks; * `priority: "low"` + `logger.info`, because this is the designed resting state of a migrated install, not a failure. Shaped as a keyword-only `steady_state` flag on the existing emitter rather than a second method: one #1677 `_ALLOWED_CALLERS` key, and a `False` default that leaves the two actionable call sites LITERALLY UNCHANGED lines — the strongest available proof of AC 4. The emitter keeps its name despite now serving a non-failure; renaming costs the allowlist key and churns a file two people are editing this week. The hash is over the RAW `url.strip()`, and is computed INSIDE the try: a non-str setting value must degrade to a warning and no alarm, not turn a decorative alarm into a raiser. Normalising the input instead would re-enter `validate_skills_library_url`, which does a live `socket.getaddrinfo` and can raise — a network call and a raise path inside a fail-soft alarm. Two things the stable id makes mandatory, both included: * `skills-legacy-adoption-` joins `_RESERVED_ID_PREFIXES`. An id derived from an admin-visible URL is guessable, so an agent could pre-create it and silence the alarm through the sink's ON CONFLICT (the #1632 C2 class); and `is_platform_minted` reads the same tuple to gate the ent#499 responded write-back and the ent#329 respond→resume dispatch, which this change makes an expected operator action. The FAMILY prefix, so all three call sites and the 17 historical rows classify correctly. * the URL echo is `strip_url_credentials`-scrubbed. The emitter's docstring claimed the credential case was handled, and that was true of `message` and of nothing else: `EmbeddedCredentialError` is a `ValueError` subclass, so the validation-reject branch is exactly the one a PAT-bearing URL reaches, and the raw value landed at ERROR in the Vector-captured log and durably in `operator_queue.context` — SQLite, every backup, rendered in the Operating Room (Invariant #12, Rule #5). The hash still keys on the raw value; scrubbing first would collide two different tokens on one repo. The #1677 justification is corrected in the same commit: "admin-driven sync cadence" is false (ent#236's loop is unattended), and the real bound — the only input is a setting blocked on the generic settings PUT — is co-located as a comment at the emitter, where it is likelier to stay true. Unchanged and deliberately so: the `count_skill_sources() > 0` guard itself, both validators, the grant branch, `expires_at: None`, the `title`/`question` copy, and `context["alert_type"]`. No schema change — `request_id` and its unique index shipped in #1631 — so Invariant #9 is not triggered: no `db/migrations.py` entry and no Alembic revision. Clearing the lingering `skills_library_url` key stays out of scope pending a separate investigation. Tests: tests/unit/test_2744_skills_adoption_alert_idempotency.py Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_0176XEqK8PTCAK5K6yZURQLv * docs(operator-queue): record the reserved prefix and the alarm's real bound (#2744) The reservation of `skills-legacy-adoption-` is enumerated in three live places and all three now carry it: `requirements/security.md` §26.7's reserved-id guard, and `operating-room.md`'s two enumerations (the ingestion-guard list and the #1632 ingestion-caps paragraph). `operating-room.md`'s "Platform exemption & emitter budget (#1677)" bundled the skills alarm into a disjunction that includes "operator-driven". That was the same false claim the `_ALLOWED_CALLERS` justification made — ent#236's auto-sync drives `sync_library()` unattended on a 300s-86400s timer, so nothing admin- or operator-driven bounds it. The paragraph now names this emitter's actual bound, per branch: the terminal refusal is idempotent by a URL-keyed id (≤1 row per refused URL) and what makes it platform-only is that its only input is a setting blocked on the generic settings PUT. Plus the two dated rows (`operating-room.md` Revision History, the `feature-flows.md` change log) and the Operating Room catalog row. All three enumerations were ALREADY stale — each omits prefixes the live tuple carries. Ours is added; their pre-existing drift is deliberately not swept here (Rule #2) and is named as a follow-up instead. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_0176XEqK8PTCAK5K6yZURQLv * test(skills): pin the steady-state discriminator and sweep the whole item for the PAT (#2744) Two gaps the review found in the new file, both in tests only. `context["reason"] = "already_migrated"` is the discriminator the emitter grew because one `alert_type` and one title now span both `low` (the benign resting state) and `high` (a URL that failed validation — the signature of an attempted injection). Nothing asserted it, so the field the fix added to be read by a machine could be dropped by a later edit in silence. The credential test asserted the PAT is absent from `context["url"]` and from the captured log, but not from `question`. `question` is credential-free only because neither ent#346 validator echoes the URL in its `ValueError` (`validate_skills_library_url` names the hostname or the resolved IP; `reject_embedded_credentials` names neither) — the scrub does not reach it. A validator message that starts echoing the URL would reopen the leak durably in `operator_queue.question` with no guard. Sweeping the serialized item covers every field the emitter writes, not the two that were remembered. Both were verified to bite: dropping the `reason` key fails the first, and reverting `strip_url_credentials` to the raw url fails the second. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_0176XEqK8PTCAK5K6yZURQLv * fix(skills): drop the already_migrated context key the owner declined (#2744) `QueueItemDetail.vue` renders every `context` key, so the discriminator the emitter grew would have surfaced to operators as a `reason | already_migrated` row. Put to the product owner as keep / drop / rename; the answer was drop — nothing reads the key today, so removing it is non-breaking. The steady-state branch is now discriminated by `priority: low` plus the `logger.info` level alone. The assertion added in 69274de7 to pin the key goes with it; it lived inside an existing test, so no test is removed. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_0176XEqK8PTCAK5K6yZURQLv --------- Co-authored-by: trinity-ability <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>
#12 list (ent#966) R3: format_env_line and models._nevermined_secret refuse any value that str.splitlines() — the agent .env reader's splitter — would break, anywhere in the value (a trailing \x85 or U+2028 leaves splitlines() length 1 but still pushes the closing quote onto its own line). Same error messages. Red with the old \n/\r-only check: 16 cases of test_every_splitlines_boundary_is_rejected and TestOrganization::test_unicode_line_separator_in_secret_is_rejected. R2: tests/registry.json lists unit/test_ent966_agent_env_patch.py. R5: Invariant #12 names nevermined_organization.encrypted_credentials. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dget session, delegation bind/revoke, MCP tools (Abilityai/trinity-enterprise#966) (#3914) * feat(nevermined): organization config + delegation schema (ent#966 A) Checkpoint A of Abilityai/trinity-enterprise#966 — the buyer side of Nevermined, beside the provider-side paywall. Nevermined holds the card and the mandate; Trinity stores the organization config and, later, the delegation id bound to an agent. - Alembic 0102_nevermined_delegations (after 0101_held_gate_turns, single head) + SQLite `nevermined_delegations`, one shared DDL constant: `nevermined_organization` (singleton, both secrets in one AES-256-GCM envelope) and `agent_delegations` (no `replaced_at` — a second bind is refused per the orchestrator ruling; partial unique index on the active row, `revoked_at IS NULL AND agent_deleted_at IS NULL`). - AgentRef KEEP for agent_delegations; cascade_delete stamps `agent_deleted_at` so a kept row never blocks the org or a reused name. KEEP-set pin in test_agent_cleanup_parity.py updated with its discipline. - Admin GET/PUT/DELETE /api/nevermined/organization (require_admin): configured:false 200, write-only secrets, secret_required, environment_mismatch, delegations_active on env change / key rotation / delete; audit rows name rotated secrets, never values. - Requirements public-access.md §23.8. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(nevermined): widget-session route (ent#966 B) Checkpoint B of Abilityai/trinity-enterprise#966. POST /api/nevermined/agents/{agent_name}/widget-session (nested path per ruling T2, superseding ent#966's `?agent=` spelling): require_person + the uniform-404 owner dependency. Mints a Nevermined widget session for the signed-in person's email server-to-server (POST {api_base}/api/v1/widgets/ session, api_base from the fixed sandbox/live map) and returns it with Cache-Control: no-store. Nevermined holds the card; Trinity forwards only the session. - Own `delegation_slot()` gate (NEVERMINED_DELEGATION_MAX_INFLIGHT=4), never a facilitator slot; 10 s upstream timeout. - Rate limit nvm-session:{user}:{agent} 10/min, before any upstream call. - Error map: 409 nevermined_not_configured, 422 email_required, 503 nevermined_busy (+Retry-After: 5), 503 nevermined_unreachable, 502 nevermined_rejected with upstream_status only (never the body). - Logs carry org, environment, agent, actor and upstream status only — never the widget secret, the session token or an upstream body. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(nevermined): .env patch helper + delegation read route (ent#966 C1) services/agent_env_patch.py — set_keys / remove_keys over the whole agent .env text with the #2023 quoting rule (parity-pinned against the PAT writer and the real agent reader), newline refusal, duplicate collapse, every other byte preserved. PAT service untouched (plan T4, D3 folds it later). GET /api/nevermined/agents/{agent_name}/delegation — uniform-404 read tier (get_authorized_agent_by_name), agent keys self-only with the same 404, nvm-read 30/min, one upstream GET /delegation/{id}/transactions per id in flight (single-flight, no cache). Every number in `live` is copied from a named Nevermined field or null; upstream failure → source "unavailable", status "unknown", error code, nothing derived. Delegation ids are validated against ^[A-Za-z0-9_-]{8,128}$ before any URL is built. Census: AGENT_CALLABLE row for the read (#2996). Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(nevermined): bind and revoke an agent's card delegation (ent#966 C2) POST /api/nevermined/agents/{agent_name}/delegation (require_person + owner): org configured → nvm-bind 10/min → an active row refuses with 409 delegation_active (no upstream call, no env read or write; ruling P7) → agent running → ONE upstream verify under delegation_slot() whose payload is the response `live` → .env read → row insert (api_key_injected = NVM_API_KEY absent OR the most recent prior row's flag, H1) → re-read + whole-file inject through the curated-path endpoint → on inject failure delete only the inserted row, 503 agent_unreachable. A concurrent bind that trips the partial unique index is 409 bind_in_progress. Upstream 404 → 422 delegation_not_found; an explicit non-active status → 422 delegation_inactive; an absent status does not block (F5). Response adds effective: next_execution. DELETE …/delegation: upstream DELETE first (2xx or 404 = revoked; anything else 503/502 and nothing local changes), then revoked_at/by, then a best-effort removal of NVM_DELEGATION_ID (+ NVM_API_KEY, NVM_ENVIRONMENT only when bind introduced them); agent down → 200 env_removed:false with env_note. Audits nevermined_delegation_bind / _revoke, credential report cache invalidated. Mutation checks (run, not committed): rate limit after the verify → test_rate_limit_fires_before_upstream red; a second upstream call in bind → test_happy_path_one_upstream_call_then_env_write red; compensation dropped → both inject-failure tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(mcp): get_agent_spending + revoke_agent_delegation tools (ent#966 D) Two MCP tools over the delegation routes from C: - get_agent_spending: GET /api/nevermined/agents/{agent_name}/delegation, body passed through in every 200 state; the uniform 404 becomes {error: "agent_not_found_or_no_access"} (not the configured:false idiom). - revoke_agent_delegation: DELETE the same path; a 403 comes back as a readable refusal stamped denied; hidden from agent sessions by a {user, system} canAccess allow-list (M6), row added to the #3435 visibility test. access.ts rows enforce agent_name on both. Descriptions name Nevermined and fit the #3234 2,048-character cap. npm test: 974/974 pass; npm run build clean. Mutation: removing the revoke canAccess turns nevermined-delegation.test.ts and tool-visibility.test.ts (#3435 block) red. Refs Abilityai/trinity-enterprise#966 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs+tests(nevermined): fund an agent with a card — docs, wording scan, §8 gaps (ent#966 E) Docs: - feature-flows/nevermined-payments.md: "Flow: Fund an agent with a card", files/tables/endpoints/MCP rows, change-history line. - user-docs/integrations/nevermined-payments.md: "Fund an agent with a card" (Nevermined holds cards and mandates; least-privilege org agent_api_key; NVM_ENVIRONMENT). One pre-existing provider-side line ("Trinity settles the transaction with Nevermined") reworded — the ent#932 scan below flags it. - architecture/backend.md + api-endpoints.md catalog lines. - requirements/public-access.md §23.8 reconciled to the routes as built (nested path, 409 delegation_active / bind_in_progress, agent_name in every GET shape, MCP tools). Tests: - test_ent966_facilitator_wording.py scans tools/nevermined.ts and both docs pages for the ent#932 phrasings. - test_ent966_delegation_gate.py: eight concurrent spending reads fill the delegation gate; every paid-chat facilitator slot stays free. - test_ent966_delegation_schema.py::TestCompensation:: test_compensation_tolerates_active_row: by-id compensation leaves a concurrent bind's active row in place. Mutations (scratch copies, restored, cmp byte-identical): revoke without the api_key_injected check -> test_hand_configured_key_survives_revoke; inject-first bind -> test_direct_db_race_is_bind_in_progress; remaining = limit - spent -> test_remaining_is_null_when_absent_never_limit_minus_spent; no-store removed -> TestWidgetSession::test_mints_for_the_signed_in_person + test_unreachable; read taking a facilitator slot -> test_paid_verify_slot_free_under_eight_gets; compensation by agent -> test_compensation_tolerates_active_row. pytest -k ent966: 154 passed, 2 skipped; test_2996_human_only_routes: 66 passed. Refs Abilityai/trinity-enterprise#966 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(nevermined): pin agent-key self-only GET, idempotent concurrent revoke (ent#966) R1: an agent key with an agent_permissions edge to a sibling passes the access gate (ent#629 "may call") but still gets the uniform 404 on the sibling's delegation, with zero Nevermined calls. Red with the router's self-only check deleted: TestReadDelegation:: test_agent_key_with_reach_to_a_sibling_still_gets_the_uniform_404. R4: revoke reads db.revoke_agent_delegation's return; None (a concurrent revoke stamped the row first) skips the env pass and the audit row and answers 200 with a Nevermined-naming env_note. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(nevermined): env newline boundary parity, registry entry, invariant #12 list (ent#966) R3: format_env_line and models._nevermined_secret refuse any value that str.splitlines() — the agent .env reader's splitter — would break, anywhere in the value (a trailing \x85 or U+2028 leaves splitlines() length 1 but still pushes the closing quote onto its own line). Same error messages. Red with the old \n/\r-only check: 16 cases of test_every_splitlines_boundary_is_rejected and TestOrganization::test_unicode_line_separator_in_secret_is_rejected. R2: tests/registry.json lists unit/test_ent966_agent_env_patch.py. R5: Invariant #12 names nevermined_organization.encrypted_credentials. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(nevermined): bind log takes literal flags, never env-derived values (ent#966, CodeQL) The bind and revoke success logs now print a yes/no literal chosen by the boolean (agent_key_written / agent_key_removed) instead of the api_key_injected value, which CodeQL's py/clear-text-logging-sensitive-data traced to the agent's .env text. Same information, no secret logged before or after. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(nevermined): bind refuses a hand-set NVM_API_KEY instead of overwriting it (ent#966, validate C1) R9 (plan premise 6): after the `.env` read and before the row insert, every value the agent's `.env` sets for NVM_API_KEY is compared constant-time with the organization's agent key; one that differs is a key Trinity did not write and the bind is refused with 409 `agent_key_present` — no row, no write, the one read-only verify already spent. The organization's own key left behind by a revoke while the agent was down (H1) still proceeds. `api_key_injected` is therefore always True on a real bind; the column, response field, audit detail and revoke's False branch stay as the record of older or synthetic rows, and the prior-row lookup (`latest_prior_agent_delegation_api_key_injected` and its db leaf) goes away with its only call. `agent_env_patch.values_of` reads a key the way the agent's own reader (`execution_env.parse_env_file` / `unquote_env_value`) does — stripped line, first `=`, one-scan unquote of a double-quoted value, single quotes verbatim — so the compared value is what the agent would send to Nevermined; `has_key` had no consumer left and is removed. Mutations: deleting the refusal turned test_hand_set_api_key_refuses_the_bind_and_writes_nothing and test_a_second_line_with_a_different_key_is_refused_too red; comparing the raw env line instead of the parsed value turned test_trinitys_own_left_behind_key_binds_and_is_removed_on_revoke and test_rebind_carries_api_key_injected_after_a_revoke_with_the_agent_down red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(nevermined): revoke notes and docs name the left-behind org key, wire DELEGATION_MAX_INFLIGHT, pin router registration (ent#966, validate W1-W3) R10 (W3): nothing calls a left-behind NVM_API_KEY "inert" any more — the delegation id is inert, the key is the organization's live agent key until the next bind rewrites it or a person removes it. `REVOKE_NOTE_AGENT_DOWN` and the new `REVOKE_NOTE_AGENT_UNREACHABLE` say exactly that behind their panel-keyed prefixes; the user doc's Revoke paragraph, the feature flow's bind ladder (409 agent_key_present after the .env read; api_key_injected always true since R9) and requirements §23.8 carry the R9 rule and the same code. R11 (W1): NEVERMINED_DELEGATION_MAX_INFLIGHT is forwarded like NEVERMINED_MAX_INFLIGHT — docker-compose.yml, docker-compose.prod.yml and .env.example (default 4) — and the user doc's Operator settings table gains its row; the .env knob was dead without the compose forward (#1056 class). R12 (W2): tests/unit/test_ent966_delegation_gate.py pins `app.include_router(nevermined_delegation_router)` by an AST walk of main.py, asserting exactly one registration of the imported router (the test_3325 mechanism). Mutation: deleting the main.py line turned test_main_registers_the_delegation_router_once red (and the existing TestProductionWiring::test_main_registers_the_router in the routes test). Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix(nevermined): hosted compose mirrors DELEGATION_MAX_INFLIGHT (ent#966, compose parity #2280) Co-Authored-By: Claude Opus 5.5 <[email protected]> * merge-train: one KEY= matcher for values_of/set_keys/remove_keys (ent#966 D12) — mechanical, per the merge-train note on the PR `values_of` stripped whitespace around `=` (mirroring the agent reader) while `set_keys`/`remove_keys` required a bare `KEY=` prefix, so a hand-spaced `NVM_API_KEY = <org key>` line passed the R9 bind check, `set_keys` appended a second line, and revoke removed only that one while reporting `env_removed: true`. `_LINE_KEY_RE` now tolerates `[ \t]*` before `=` and is the single matcher all three functions use. Test: `TestOneLineMatcher` in `tests/unit/test_ent966_agent_env_patch.py` — a spaced line is seen by `values_of`, replaced in place by `set_keys` and removed by `remove_keys`, cross-checked against the real agent reader; red on the old code (4 failed), green after. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: trinity-ability <[email protected]>
…y-enterprise#926) PR #3778 review: a route with no census row that names no agent was open in a restricted turn. POST /api/agents is gated only by require_role("creator"), and the agent key carries the owner's role, so a shared person's turn could create agents owned by the owner, cloned with the owner's GitHub PAT (resolved at creation, Invariant #12). route_tier_service.OWNER_TIER_UNNAMED refuses POST /api/agents, /api/agents/deploy-local, /api/systems/deploy and /api/systems/{system_name}/restart in a restricted turn. A census test scans every creator-gated route that names no agent and fails one that is neither in that set nor declared open with a reason (the two manifest reads), and fails a stale entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>


Summary
npm ciwithnpm installfor better handling of optional dependencies@rollup/rollup-linux-arm64-muslfor ARM64 Alpine LinuxTest plan
Made with Cursor
Note
Low Risk
Build-only change to the frontend Docker image; risk is limited to potential dependency drift from using
npm installinstead ofnpm ci.Overview
Updates the frontend
docker/frontend/Dockerfileto usenpm install(instead ofnpm ci) to better tolerate optional dependencies during container builds.Adds an ARM64 Alpine workaround by conditionally installing
@rollup/rollup-linux-arm64-muslwhen the image is built onaarch64.Written by Cursor Bugbot for commit 7196432. Configure here.