Repository navigation
feat(nevermined): fund an agent with a card — organization config, widget session, delegation bind/revoke, MCP tools (abilityai/trinity-enterprise#966) - #3914
Conversation
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
…6 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 <noreply@anthropic.com>
…n, §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 <noreply@anthropic.com>
…evoke (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 <noreply@anthropic.com>
#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 <noreply@anthropic.com>
…es (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 <noreply@anthropic.com>
trinity-ability
left a comment
There was a problem hiding this comment.
PR Validation Report — #3914 (run chain-ent965-966-validate)
Branch: feature/ent966-nevermined-delegation-backend → dev · Tip: 89d1eb6afd2f · Files: 31 (+4017/−5) · Lane: B +schema (no Lane-C path. The secret-bearing org config and money paths were read at Lane-C depth anyway.)
Summary
| Category | Status | Notes |
|---|---|---|
| Commit messages / base / size | ✅ | conventional; base dev f049d67 (unmoved); 31 files |
| Issue link / auto-promotion | ✅ / |
Fixes abilityai/trinity-enterprise#966 resolves. Cross-tracker, so set status-in-dev by hand after merge |
| Requirements / architecture / flows | ✅ | public-access.md §23.8, api-endpoints.md, backend.md, Invariant #12 list, feature flow + user doc |
| Enterprise-docs disclosure (§3.5) | ✅ | guard pattern: 0 hits on added lines |
| Security greps §4.1–4.6, §4.10 | ✅ | §4.5 hits are synthetic test fixtures under tests/; no symlinks, mode flips or host paths |
| Build packaging (§4.8) | ✅ | no new top-level backend directory |
| Config packaging (§4.9) | W1 | |
+schema addendum |
✅ | SQLite _migrate_nevermined_delegations + Alembic 0102 (down_revision 0101_held_gate_turns). check_alembic_heads.py → 1 head, PASS |
| Structural review | ✅ | /review MERGEABLE (6 INFO, fixed) + /cso --diff posted on the branch |
| Merge gate Tier 1 | ✅ | every check on the tip green or skipped. dev-ci = success; no open dev-ci red issue |
| Test adequacy / execution coverage | C1 is not covered by a real-sequence test; W2 |
Execution coverage (§5.4)
| changed symbol / test file | executed by | live consumer | verdict |
|---|---|---|---|
nevermined_delegation_service.bind/revoke_delegation |
test_ent966_delegation_routes.py (103 passed here, real router + tmp SQLite + real AES-GCM) |
routers/nevermined_delegation.py |
✅ (gap: C1) |
agent_env_patch.set_keys/remove_keys/format_env_line |
test_ent966_agent_env_patch.py (52 passed) |
the service, via _inject_agent_env |
✅ |
| schema / gate / wording | _schema 10, _gate 1, _facilitator_wording 8 passed |
migrations runner; the wording test is a guard | ✅ |
main.py app.include_router(nevermined_delegation_router) |
— | main.py:1417 |
test_2996_human_only_routes (66), test_186_enumeration_uniformity (29) and the routes file green. The routes tests build their own FastAPI(). Restored, cmp identical |
Issues found
Critical (block merge)
C1. A hand-configured NVM_API_KEY is destroyed at bind, and revoke then leaves the organization's agent API key in the agent. bind_delegation sets api_key_injected = False when the agent already has an NVM_API_KEY. But agent_env_patch.set_keys still overwrites that line with org["agent_api_key"]. On revoke, api_key_injected=False means only NVM_DELEGATION_ID is removed.
Shown by execution: a scratch test in the PR worktree (since removed) seeded NVM_API_KEY=hand-pasted-personal-key, then ran bind (201) and revoke (200, env_removed: true). The agent's .env ended up holding NVM_API_KEY, which is now the org key (org_key_retained=True, personal_restored=False), plus NVM_ENVIRONMENT.
- This contradicts the user doc (
integrations/nevermined-payments.md: "removes the keys from the agent … AnNVM_API_KEYyou set by hand is never removed"). The personal key is gone at bind, and what remains after revoke is the instance-wide org secret. - It misses the plan's own T6 / Decision 14 goal ("never deletes a hand-configured key"). It also produces exactly the outcome the plan gave for rejecting T6's "Never" option: "the org key lingers and the agent can still
delegation create". test_hand_configured_key_survives_revokeseedsNVM_API_KEY=personalafter bind, which the real sequence cannot produce, so it passes over the defect.test_pre_existing_api_key_is_not_claimedasserts the overwrite ("Premise 6") but not what revoke leaves behind.- Needs a ruling plus a test of the real sequence. Possible shapes: refuse bind (409) while a hand-set
NVM_API_KEYdiffers from the org key; or treat an overwritten key as injected, so revoke removes it, and say in the docs that bind replaces it. Either way, the user doc andenv_notemust match what actually happens.
Warnings
- W1.
NEVERMINED_DELEGATION_MAX_INFLIGHT(nevermined_delegation_service.py:52, default 4) is not wired intodocker-compose.yml,docker-compose.prod.ymlor.env.example, so it cannot be changed on a deployed install. The feature still works at the default. Precedent is split:NEVERMINED_MAX_INFLIGHTis wired everywhere, while #3215'sNEVERMINED_PLAN_LOOKUP_MAX_INFLIGHTis not. Graded⚠️ rather than the playbook's ❌ because the feature itself is reachable. - W2. The router's registration in
main.pyis not pinned by any test (mutation above). - W3.
REVOKE_NOTE_AGENT_DOWN/ the agent-unreachable note and the user doc call the leftover key "inert". OnlyNVM_DELEGATION_IDis inert. A leftover bind-introducedNVM_API_KEYis the live org key, which by the plan's own T6 analysis can stilldelegation create. Reword (e.g. "the delegation id is inert; the agent still holds the organization key until the next bind or a restart-time cleanup").
Suggestions
- The PR body says the widget session is limited to "30/min per agent"; the code allows 10/min per (user, agent). The 30/min figure is the read limit. The body also names the table
nevermined_agent_delegations; the DDL createsagent_delegations. revoke_agent_delegationis advertised tosystemscope, butrequire_person(PERSON_SCOPES = {None, "user"}) always refuses it there. That was ruled in R6; noting it only so the deferred tightening stays tracked.
Recommendation
REQUEST CHANGES. One blocker, C1. Everything else holds: auth boundaries, the upstream-first money-path order, compensation by row id, secrets kept out of responses and logs, one Alembic head, Tier 1 green.
This PR requires the following changes before merge:
- C1: make bind and revoke over a hand-configured
NVM_API_KEYmatch the documented guarantee (ruling + a real-sequence test: seed key → bind → revoke → assert.env) - W3: fix the "inert" wording, if the C1 fix keeps any path where the org key stays behind
status-needs-fix label not set: label changes are excluded by this run's constraints.
🤖 Generated with Claude Code
…riting 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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
…966, compose parity #2280) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
trinity-ability
left a comment
There was a problem hiding this comment.
PR Validation Report — round 2 (/validate-pr, run chain-ent965-966-validate-2)
PR: #3914 · Head: 3de77a0df8ff · Base: dev (f049d67312aa) · Lane: C+schema (compose files; schema was validated in round 1)
Scope this round: were C1 and W1–W3 from round 1 closed as ruled (R9–R13), and did the fixes introduce anything new? Everything else got a spot-check only.
Round-1 items
| Item | Ruling | Verdict | Evidence |
|---|---|---|---|
C1a: bind overwrote a hand-set NVM_API_KEY |
R9 | ✅ closed | _refuse_foreign_agent_key runs before the row insert and the inject. It compares every value values_of returns using hmac.compare_digest. values_of mirrors execution_env.parse_env_file line for line (strip, skip #/blank/no-=, partition('='), unquote). An export KEY= line is ignored by both, and startup.sh does not source .env. Real-sequence test test_hand_set_api_key_refuses_the_bind_and_writes_nothing: 409 agent_key_present, one verify only, no inject, .env byte-identical, no audit row, empty history, key not echoed. Mutation (drop the refusal call) → that test and the duplicate-line test go red. |
| C1b: revoke left the org key | R9 + R10 | ✅ closed | api_key_injected is now always true on a new bind, so a revoke with the agent up removes the key (test_trinitys_own_left_behind_key_binds_and_is_removed_on_revoke). With the agent down, the org key is left behind and the next bind passes and rewrites it. The dead latest_prior_* helper is gone from both db/ and database.py. |
| W1: "inert" wording | R10 | ✅ | Both revoke notes (agent_not_running / agent_unreachable) now say the org key stays until the next bind or until someone removes it. The remaining uses of "inert" refer only to the delegation id (service, user doc :127, feature flow :143). |
W2: NEVERMINED_DELEGATION_MAX_INFLIGHT |
R11 + R13 | ✅ | Present in docker-compose.yml, .prod.yml and .hosted.yml, in .env.example, and in the user-doc Operator settings row. test_2280_hosted_compose_parity: 8 passed. |
| W3: router registration unpinned | R12 | ✅ | test_main_registers_the_delegation_router_once (AST walk over main.py). Mutation (delete app.include_router(nevermined_delegation_router)) → red. |
Local runs: test_ent966_delegation_routes.py, test_ent966_agent_env_patch.py and test_ent966_delegation_gate.py all passed (73 + 104). Every mutation was run on a scratch copy and restored; cmp confirmed each file byte-identical afterwards.
New observations (non-blocking)
⚠️ W4: two line matchers disagree, so a spaced org key survives revoke.values_ofmatches the reader's lines (KEY = vcounts).set_keys/remove_keysmatch_LINE_KEY_RE(^\s*KEY=), which does not. Probe:.env=NVM_API_KEY = <org key>→ the bind passes (correct, it is the org key) →set_keysappendsNVM_API_KEY="<org key>"→remove_keyson revoke removes only the appended line →values_ofstill returns[<org key>]. Meanwhile revoke reportsenv_removed=trueand logsagent_key_removed=yes. To reach this, a person has to hand-write the org key with a space around=. The fail direction is "org key not removed", which is the same state the documented agent-down path already leaves. Suggested follow-up: haveset_keys/remove_keysmatch the reader's line shape, or treat a non-canonical org-key line asagent_key_present.⚠️ W5: the duplicate-line test pins only one ordering. Mutating the loop to check only the last value (values_of(...)[-1:]) survives, because the test seeds org-then-foreign. A first-only mutation ([:1]) is caught. Behaviourally, last-only would still refuse whenever the agent would send a foreign key. Butset_keysrewrites the first line in place and drops later duplicates, so in the foreign-then-org case it would destroy the hand-set line. That case is what the all-values rule protects, and no test pins it. A one-line seed swap closes it.
Spot-checks
- Tier 1 on the tip: every check is pass or skipping, none fail, including
regression diff,pytest (head),schema-parity,pg-migrations,gitleaks,journey-smoke,prod-image-smokeand CodeQL.dev-ciondevissuccess. - §4.1–4.3 / §4.10: all six token-pattern hits are identifiers (
github_pat_propagation_service, …). No real emails, public IPs or host paths in added lines. - Closing keyword
Fixes abilityai/trinity-enterprise#966is present. It is cross-tracker, sostatus-in-devhas to be set by hand after merge. - The before-merge items already listed in the PR body (§23.8 flip, real Docker
_agent_running, sandbox click-through, the documented false refusal after an org-key rotation, D2–D11) were not re-raised.
Recommendation
APPROVE. C1 and W1–W3 are closed as ruled, and each is pinned by an executing test that a mutation turns red. W4 and W5 are edge-shape follow-ups and do not block.
…#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 <noreply@anthropic.com>
|
merge-train (2026-10-23): pushed to your branch — Fix (D12, mechanical): Test added: Tier: the owner ruled the feature OSS-core at Gate 1 (recorded on abilityai/trinity-enterprise#966), so the open "confirm the tier before merge" item in the PR body is closed — nothing is gated. Not approving, labelling or merging from here. |
trinity-ability
left a comment
There was a problem hiding this comment.
merge-train: batch validated on train/20261023-2211 (#3930, all checks green)
… re-chain onto 0102_nevermined_delegations - Resolve the MIGRATIONS tail conflict by keeping both entries (nevermined_delegations, then a2a_caller_identity). - Rename the Alembic revision to 0103_a2a_caller_identity and re-parent it onto 0102_nevermined_delegations (#3914), so dev keeps a single head. - Add a2a_caller_identity to db_models.ScheduleExecution and map it in _row_to_execution. Before this, GET .../executions/{id} always returned null because the column was written but never read back. - Read-back test: create_task_execution -> get_execution -> ExecutionResponse. - test_ent966: assert nevermined_delegations is registered, not that it is the last runner entry, since any later migration would break that. Refs abilityai/trinity-enterprise#862 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts: - tests/registry.json: both sides appended at the tail; kept both (text edit, every entry three-way checked). - tests/unit/_route_census.py: dev (#3914) added routers/nevermined_delegation.py::get_agent_delegation to AGENT_CALLABLE, which this branch splits; it is now an AGENT_CALLABLE_SELF entry. Semantic, from #3914 (merged cleanly, would fail the census): - routers/nevermined_delegation.py: the read's hand-copied agent-key check is now assert_own_agent(..., refusal=...) as its first statement, building the access dependency's uniform 404, so a sibling inside the caller's reach still answers exactly like a missing agent; the unused agent_principal_name import is gone. - tests/unit/test_ent966_delegation_routes.py: reads AGENT_CALLABLE_SELF and asserts the recognised gate carries refusal=. - tests/unit/test_ent840_agent_self_gate.py: pins the route's message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… Payments tab, organization settings form (Abilityai/trinity-enterprise#967) (#3917) Fixes Abilityai/trinity-enterprise#967 — second of two in the ent#965 card-delegation epic (the one-component spending panel; the backend / API / MCP landed as ent#966). **Stacked on #3914** — base is `feature/ent966-nevermined-delegation-backend`; the stack merges together in order on the operator's call (retarget this PR to `dev` after #3914 merges). **Draft until the chain is in.** ## What - **Spending panel** — `components/NeverminedSpendingPanel.vue`, mounted on the agent Payments tab (`views/AgentDetail.vue`). Reads `GET /api/nevermined/agents/{agent}/delegation` and renders every state: not configured (admin link to the organization form), unfunded (Enroll), pending (Retry bind / Discard), funded (live numbers, every one nullable, `status:"unknown"` when Nevermined is unreachable), plus a collapsed "Past mandates (N)" table from `history[]`. Every string names Nevermined as the holder of the card and the mandate (ent#932 wording; `COPY` + `ACTIONS` constants, FORBIDDEN-regex tested). - **Enroll flow** — mints a widget session server-side (`POST …/widget-session`), then runs Nevermined's `setupCard` (one combined iframe, `@nevermined-io/ui-widgets` 1.80.0, dynamic `import()` + `optimizeDeps.include`) inline when the slot is ≥ 440 px, as the SDK's fullscreen overlay below that. The `{paymentMethodId, delegationId}` result is persisted as a pending record (memory + `sessionStorage`) before the bind `POST`, so a lost reply is recoverable with **Retry bind** (same ids, no second mandate). Bind `201` → funded from the response; `409 agent_not_running` / `409 agent_key_present` → the backend message + Retry bind; `429`/`503` → Retry bind held for `Retry-After` seconds; `422` → start again. Esc, tab-leave and unmount destroy the SDK instance; `beforeunload` is armed while the form is up. - **Redirect fallback** — a frame that never boots (8 s) or is CSP-blocked offers "Continue on Nevermined": a fresh session is minted and the hosted page opens with a per-tab nonce as `state`; the return deep-links to the Payments tab (`AgentDetail.applyDeepLinkRouting`), the nonce must match, the three query keys are stripped, and the bind runs from the returned ids (`paymentMethodId` optional, pattern-checked when present — R-I1). - **Revoke** — `ConfirmDialog`, then `DELETE`; the panel renders the backend's `env_note` sentence verbatim (never its own paraphrase). - **Organization form** (admin-only) — `components/settings/NeverminedOrganizationPanel.vue` on Settings › Integrations (`views/Settings.vue`): organization id, environment (sandbox / live, change confirmed), widget secret and agent API key write-only ("paste to rotate"; a blank secret is omitted from the `PUT`); `409 delegations_active` and `422` `detail.message` surfaced. - **Rules module** — `utils/neverminedSpending.js` (`unwrapSession` tolerant of bare / `.session` / `.data`, `unwrapSuccess`, `redirectReturn`, `newNonce` with `randomUUID` → `getRandomValues` → `Math.random` tiers, `recoveryFor`, `RETURN_MISMATCH`, `FALLBACK_CAUSES`); `apiErrorCode` in `utils/apiError.js`. - **CSP, both copies** — `frame-src https://embed.nevermined.app` and `connect-src` + `api.sandbox.nevermined.app` + `api.live.nevermined.app` in `vite.config.js` and `security-headers.conf` (the SDK refreshes its session from the browser); `cspMirrors.spec.js` pins the two copies equal, forbids `nevermined.dev`, and pins the existing `'unsafe-*'` set per copy. `Permissions-Policy: payment=()` is kept (TD-6). - **Docs** — `docs/user-docs/integrations/nevermined-payments.md` (panel, organization form, the hosted-page fallback's one-time session in the address bar, the `/login` bounce), feature flow `nevermined-payments.md`, `public-access.md` §23.8 FR-5, `architecture/frontend.md`; the wording guard `test_ent966_facilitator_wording.py` now scans the panel, the form and the rules module. - **Specs** — `neverminedSpending.spec.js` (59), `neverminedSpendingPanel.mount.spec.js` (50, real memory router), `neverminedOrganizationPanel.mount.spec.js` (13), `cspMirrors.spec.js` (6). ## Rulings carried (orchestrator, on the operator's behalf — plan file) - TD-1 the admin organization form ships **in this issue** on Settings › Integrations (the issue body's own rule: a second form on the Payments tab only if no admin settings home exists) · TD-2 `setupCard` as one combined iframe — the issue's two-step wording is superseded · TD-3 dynamic `import()` + `optimizeDeps.include` · TD-4 SDK fullscreen overlay under 440 px; redirect only for a browser-blocked frame · TD-5 render the past-mandates table from `history[]` · TD-6 keep `Permissions-Policy: payment=()` in both header copies · TD-7 tolerant `unwrapSession` in the panel, no backend delta · TD-8 defer `NeverminedPanel.vue`'s native `confirm()` to #1924 (commented there) · TD-9 accept and document the `/login` bounce on redirect return (no router stash) · TD-10 inline where the slot fits, overlay otherwise. - Deviations from the issue text, accepted: specs under `tests/unit/`; the hard-coded Nevermined-only `connect-src` addition in both CSP copies; `onSuccess` delivers `{result, handle}`; `returnUrl` carries no query and the deep link maps the return to the Payments tab; every added text surface carries "Nevermined holds the card". - Addenda: 409 `agent_key_present` (from ent#966 R9) handled like `agent_not_running` → Retry bind; `env_note` rendered verbatim, no "inert" paraphrase (R10); `notify` prop (`showNotification` seam, as the A2A panel); `loadSdk` prop for the rejects test; `ACTIONS` outside `COPY`; slot measured while visible; Retry-After hold covers bind retries only; Retry bind as its own button; 8 s never-booted timer offers the redirect; the CSP mirror spec forbids `nevermined.dev`, not every `.dev`. - Fix rulings after review (`83bfedd4b23f`, each proved red first): **R-I1** `redirectReturn` follows the `unwrapSuccess` rule — a return without `paymentMethodId` binds (the backend's field is optional, Trinity records only the delegation id, and a strict refusal on the redirect path wrote no pending record, orphaning a mandate Nevermined already created) · **R-I2** dead `COPY.closeForm` removed · **R-I3** a funded read clears a stale pending record with the same delegation id (the mid-POST agent-change leftover), a different id is kept · **R-I4** no fix: the hold resetting on `teardown()` is reachable only by tab-switch/unmount and costs one extra 429/503 against the backend's own `nvm-bind` limiter · **R-I5** `newNonce` second tier is `crypto.getRandomValues`. ## Review + security `/review` (Fable, report-only, `89d1eb6afd2f..941deca`): **MERGEABLE** — 0 CRITICAL / 0 HIGH / 7 INFO. Rider checks (a)–(m) hold: the session token goes only into `initialize` and the fresh-mint redirect URL, nothing logged or stored beyond ids + nonce; nonce + `state` + id-pattern + three-key strip on the return; no open redirect (fixed Nevermined host); CSP both copies; organization secrets write-only and never echoed; auth boundaries UX-only (the backend enforces); ent#932 wording; flow invariants; Retry-After hold; merged state against the live base `3de77a0df8ff`; `.claude` and the enterprise submodule untouched in the range. `/cso --diff`: 2 supported INFO, both accepted as the plan records — the SDK's own iframe `sandbox`/`allow` flags are not tightenable without a fork, and the session token in the top-level URL on the hosted-page fallback (TD-4: reachable only from the never-booted/CSP-blocked offer, fresh mint, `no-store`, Nevermined-side expiry; disclosed in the user doc). Evidence sweep (Opus, merged tree): branch specs + guards 9 files / 184 passed; mutations M1–M8 red (state mismatch, CSP mirror, secret omission, redirect-return strip, Retry-After hold, SDK destroy on teardown, agent-change guard, COPY wording). Fix-step mutations: m1 (re-add the `paymentMethodId` refusal) and m2 (drop `clearPending` in `load()`) each red on exactly the new case. `/validate-pr` (Opus, PR worktree at `83bfedd4b23f`, judged against the stacked base `3de77a0df8ff`, not `dev`): **APPROVE** — review 5624392780, 05:44Z. `npm ci` exit 0; 109 + 19 + 28 + 11 spec passes, wording pytest 11. Mutations M1–M6 and M8 red; **M7 survives** — no case fires the SDK `onClose` during `binding` (W1, Handoffs). W2 = the `applyDeepLinkRouting` one-liner (Before merge). W3 = cross-tracker `Fixes` does not auto-promote (Before merge). ## Tests - Targeted (fix tip, from `src/frontend`): 9 spec files / 173 passed — `neverminedSpending` 59, `neverminedSpendingPanel.mount` 50, `neverminedOrganizationPanel.mount` 13, `cspMirrors` 6, `optimizeDepsIncludeGuard` 11, `rawColorRatchet` 14, `loadingGateRatchet` 6, `sourceTextRatchet` 8, `agentDetailDeepLink` 6. `npm run build` exit 0; `check:tokens` exit 0; wording guard `test_ent966_facilitator_wording.py` 11 passed. Raw-colour scan: both new components `raw_nongray: 0`, `hardcoded_colors: 0`. - Full frontend island (`npm run test:unit`, alone, merged tree): 399/400 files, 6367/6369 tests — `mobileAdminQueueWalk3302.spec.js` 2 × 5 s timeouts in the full run, 4/4 alone on tip and merged, imports nothing in range: load-sensitive / pre-existing; CI's run is the tiebreak. - Not run here: the real Nevermined sandbox (Before merge); `AgentDetail.applyDeepLinkRouting`'s one-liner has no harness. ## Before merge - **Stack:** base is `feature/ent966-nevermined-delegation-backend` (#3914, approved). A stacked PR runs a reduced check set (`backend-unit-test` does not run here) — the first full run comes when this PR retargets to `dev` after #3914 merges. - **Lockfile:** `package-lock.json` was hand-trimmed to the two new entries (npm 10.8.2 rewrote unrelated rollup lines; the committed lockfile was already out of step with `package.json` on the base). `npm ci` exit 0 in the review and both sweep trees; the frontend CI `npm ci` is the proof. - **Sibling PRs — conflicts this branch adds** (test-merged 05:2xZ; operator's merge-order call, siblings not commented): #3913 (ent862 AAuth) — `src/frontend/src/views/Settings.vue`, both add a Settings › Integrations panel row; #3858 and #3860 (dependabot, frontend) — `package-lock.json`, whichever lands second regenerates the lockfile. Twelve other open PRs share files with this range with no added conflict. - **Live-only AC (operator's sandbox click-through):** inline form at ≥ 440 px and the overlay below it (375 px), bind → funded; the hosted-page fallback and its deep-link return (including the `/login` bounce, TD-9); Retry bind after a refused bind; revoke; the `AgentDetail` mount line; `Permissions-Policy: payment=()`'s effect on any wallet button inside the frame (TD-6); light and dark themes. If Nevermined wraps the widget-session body, the one-line unwrap in `mint_widget_session` goes on the ent#966 branch (D1). - **Tier:** built OSS core per the ent#965 default; the operator's tier call and the widget-gap questions (ask `ent965-widget-gaps`) are open. - §23.8 FR-5 "Status: 🚧 In Progress" flips to shipped at merge. - **Cross-tracker label (validate W3):** `Fixes Abilityai/trinity-enterprise#967` does not auto-promote — set `status-in-dev` on ent#967 by hand after merge (same for ent#966 on #3914). ## Handoffs - #1924 — `NeverminedPanel.vue` still uses the native `confirm()`; recorded there (TD-8). - ent#889 (Settings section rows) — the panel's `can_share` / deep-link dependency is recorded in the plan §1.1; the mover re-reads it (D4). - Not built, revisit only if the click-through hits it: a router stash for the redirect return across a `/login` bounce (D3, TD-9); a retained hold deadline across `teardown()` (R-I4). - Follow-up test (validate W1, mutation M7): one mount case that fires the SDK `onClose` while `phase === 'binding'` — the guard in `NeverminedSpendingPanel.vue` keeps `closeForm()` from dropping the phase mid-bind (Enroll re-enabled, `beforeunload` hold removed); the `bound` half of the guard is redundant with the `mine !== flow` check. Recorded on ent#967. - ent#966's per-agent spend key, pre-flight `bindable` hint, and the wider ent#932 wording sweep remain on that PR's handoff list. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Fixes abilityai/trinity-enterprise#966 — first of two in the ent#965 card-delegation epic (backend / API / MCP; the one-component spending panel follows as ent#967, stacked on this branch). Base is
dev; the stack merges together in order on the operator's call. Draft until the chain is in.What
0102_nevermined_delegations(one Alembic head after0101_held_gate_turns): a singletonnevermined_organizationrow (org id, environment, encrypted widget secret + agent API key) andagent_delegations(one active row per agent,WHERE revoked_at IS NULL AND agent_deleted_at IS NULL; KEEP rows on agent delete).db/nevermined_delegation.py,db/schema.py,db/tables.py,db/migrations.pymirrors,agent_cleanup.pyparity.GET/PUT /api/nevermined/organization; secrets are write-only, envelope-encrypted (Invariant fix: Add ARM64 Alpine compatibility for frontend Docker build #12 list updated); rotating the agent key while delegations are active answers409 delegations_active.POST /api/nevermined/agents/{agent_name}/widget-session(owner tier) mints a short-lived Nevermined widget session server-side ({session, environment, org_id},Cache-Control: no-store), 10/min per user and agent (nvm-session); the delegation read is 30/min (nvm-read).GET(configured/funded/delegation/live/history; every live number nullable,status:"unknown"when Nevermined is unreachable),POSTbind ({delegationId, paymentMethodId, provider}→ 201, upstream verify first, then the.envpatch, with compensation by row id;409 delegation_activewhile one is active,409 agent_not_runningon a stopped agent,409 agent_key_presentwhen the agent already holds anNVM_API_KEYTrinity did not write — bind never overwrites a hand-set key; 10/min per user and agent (nvm-bind)),DELETErevoke (upstream first, then env removal; idempotent under a concurrent revoke). Agent keys read their own agent only — anything else is the uniform 404.routers/nevermined_delegation.py,services/nevermined_delegation_service.py..envpatch helper —services/agent_env_patch.py: byte-for-byte preservation of untouched lines, bug(credentials): .env quote-escaping is write-only — a credential containing a double quote round-trips corrupted #2023 quoting parity with the agent reader, union semantics over the whole-file inject,str.splitlines()boundary set rejected in values.get_agent_spendingandrevoke_agent_delegation(src/mcp-server/src/tools/nevermined.ts, visibility rows, descriptions inside the 2,048-char budget).nevermined-payments.md, user docintegrations/nevermined-payments.md,public-access.md§23.8,api-endpoints.md,backend.md. Every user-facing string names Nevermined as the holder of cards and mandates; nothing reads as Trinity holding a card or settling money (test_ent966_facilitator_wording.py, scan over code, MCP and docs).Rulings carried (orchestrator, on the operator's behalf — plan file)
/api/nevermined/agents/{agent_name}/…(supersedes the?agent=spelling in the issue) · T3 no cache, per-id single-flight, 30/min · T4 newagent_env_patchservice, PAT service untouched · T5 KEEP rows on delete · T6 removeNVM_API_KEYon revoke only if bind introduced it · T7 no admin MCP tool for the organization secrets · T8 rotation with active bindings →409 delegations_active· T9 org key only (per-agent spend key deferred) · T10 bind on a stopped agent →409 agent_not_running.409 delegation_active; revoke is the only way out, so no untracked live mandate can exist.replaced_atdropped.agent_deleted_at(a deleted agent's KEEP row must not block the name); direct POST to the agent inject endpoint mirroring the PAT service; compensation by row id;agent_namein every GET shape.splitlines()boundary parity (builder tightened the check tovalue.splitlines() not in ([], [value])— a trailing separator is also rejected) · R4 idempotent concurrent revoke (env_removed:false,env_notenaming Nevermined; upstream-first order unchanged) · R5 Invariant fix: Add ARM64 Alpine compatibility for frontend Docker build #12 list · R6 revoke MCP tool stays advertised touser+systemscopes, matching the refactor: hide the three credential-migration MCP tools from agent sessions that can never call them, and say who may #3435CREDENTIAL_TOOLSprecedent (tighten both together — deferred) · R7 §23.8 status flips at merge.yes|noflags, never a value traceable to the agent's.env(89d1eb6afd2f)./validate-pr(REQUEST CHANGES, one blocker): R9 rules plan premise 6 — bind never overwrites a key Trinity did not write: while the agent's.envholds anNVM_API_KEYwhose value differs from the organization's agent key (constant-time compare on the parsed value, never logged), bind answers409 agent_key_presentafter the one upstream verify and writes nothing; a key equal to the org key (left by a revoke while the agent was down) proceeds;api_key_injectedis therefore true on every new bind (column kept as the record; the dead prior-row helper deleted). Known safe false refusal after an org key rotation, documented. R10 no note or doc calls a left-behind key "inert" — the delegation id is inert, the org key stays until the next bind rewrites it or someone removes it. R11NEVERMINED_DELEGATION_MAX_INFLIGHTwired indocker-compose.yml,docker-compose.prod.yml,.env.exampleand the user doc; R13 (after CI'sregression diffcaughttest_2280_hosted_compose_parity) mirrors it intodocker-compose.hosted.yml, the pull-only twin of prod —3de77a0df8ff, parity file 8 passed. R12 the router registration pinned by a gate test (test_main_registers_the_delegation_router_once). Landed as0ff44709fcdc(R9) anda409e924b88a(R10–R12), mutations m1–m3 red first.Review + security
/review(Fable, report-only,5be717b30c11): MERGEABLE — 0 CRITICAL / 0 HIGH / 6 INFO. Rider checks hold: money-path order (verify → write, rate limit before upstream, compensation on write failure) by code and by test; secrets never in a response body or log;require_admin/require_person/ uniform-404 boundaries;.envbyte-for-byte; one Alembic head on a merge-tree against livedev; MCP visibility rows + description budget; ent#932 wording; §23.8 parity;.claudeand the enterprise submodule untouched./cso --diff: 0 supported findings (one hypothesis — the shared org key can spend any agent's mandate — deferred as a per-agent spend key).Evidence sweep (Opus): 37 test files green, neighbour run 503 passed, mutations M1–M6 red, M7 fixed by R1.
/validate-pr(Opus, on89d1eb6afd2f): REQUEST CHANGES — C1 (hand-setNVM_API_KEYoverwritten at bind, org key left after revoke) + W1–W3; all fixed by R9–R12 above; re-validated on the current tip: round 2 (3de77a0df8ff, review 5623653104) APPROVE — C1 and W1–W3 closed as ruled, each pinned by a test a mutation turns red; two non-blocking edge shapes recorded as handoffs D12/D13 below. All six INFO items fixed in2cbaa431484a(R1 + R4) and6bd397e9f0c0(R2 + R3 + R5), each proved red first (R1:test_agent_key_with_reach_to_a_sibling_still_gets_the_uniform_404; R3: 17 boundary cases).Tests
test_ent966_*files +test_2023_env_quote_round_trip+test_186_enumeration_uniformity+test_2996_human_only_routes+test_agent_cleanup_parity+test_2306_architecture_split→ 368 passed after F4 (364 before).-k ent966154 passed / 2 skipped (enterprise unmounted, no PostgreSQL).npm testinsrc/mcp-server974/974 +tscclean.check_alembic_heads1 head.test_2280_hosted_compose_parity8 passed after F5 (red in CI ona409e924b88a, the oneregression difffailure of that tip)._agent_runningpath and the live Nevermined sandbox (Before merge).test_ent236_skills_lifecycle::test_real_repo_still_pulls(red ondevf049d67 too).Before merge
0102_nevermined_delegationsfollows0101_held_gate_turns. PR feat(a2a): AAuth identity badge + execution attribution (ent#862 PR2+PR3) #3913 adds a0099_…revision that already collides with dev's0099; it renumbers behind this chain (notified).devafter this merges. This PR is dev-based and runs the full check set._agent_runningseam is unit-guarded only); the sandbox widget click-through is the operator's.Handoffs
effective:"next_execution", revoke 200{revoked, delegation_id, env_removed, env_note}, error bodies{detail: {code, message}}).NVM_API_KEYis discovered only at bind, after Nevermined created the mandate — abindablehint on the GET would cost an agent.envread per GET; D11); revoke the mandate at Nevermined on agent delete; fold the PAT.envwriters ontoagent_env_patchand lock the agent-side read-modify-write; key rotation propagation; per-agent spend key at bind; lifecycle hook for bind-on-stopped; wider ent#932 wording sweep over the other Nevermined docs; tighten thesystem-scope allow-lists ofrevoke_agent_delegationandCREDENTIAL_TOOLStogether. Thenevermined-catalogskill's hardcoded live API base (must readNVM_ENVIRONMENT) is atrinity-skillslibrary task.values_ofacceptsKEY = v(spaces) whileset_keys/remove_keysmatch^\s*KEY=only, so an org key hand-written with spaces around=survives a revoke that reportsenv_removed=true; align the two matchers or treat a non-canonical org-key line asagent_key_present. D13 — the duplicate-line test seeds org-then-foreign only; a last-value-only mutation survives — add the foreign-then-org seed.🤖 Generated with Claude Code