Skip to content

fix(security): admin gates reject agent-scoped keys - #1890

Merged
vybe merged 3 commits into
devfrom
fix/293-admin-gate-rejects-agent-keys
Aug 8, 2026
Merged

vybe merged 3 commits into
devfrom
fix/293-admin-gate-rejects-agent-keys

Conversation

@dolho

@dolho dolho commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes a privilege-escalation class reported privately. P1.

The bug

An agent-scoped MCP key resolves to its owner carrying the owner's role, so on a default admin-owned install every agent's injected TRINITY_MCP_API_KEY satisfied every assert_admin / require_admin gate.

The chain that makes it P1: a prompt-injected agent repoints the platform skills library at an attacker-controlled repo through the generic settings setter; the scheduled sync pulls it; the fleet sweep writes attacker-authored SKILL.md files into every running agent. A SKILL.md is instructions Claude executes, persisted on the durable home volume. One compromised agent becomes all of them.

Fixed at the gate, not the endpoint

This is the third occurrence of the class — trinity-ops-agent#232, #1644 (retention acknowledge), #1816 (system-agent restart) — each previously closed by bolting reject_agent_principal onto one more endpoint. Three occurrences means the gate is wrong, not the endpoints.

So assert_admin and require_admin now reject agent principals. The class closes at once, and a settings key or endpoint added tomorrow inherits the protection without anyone remembering to ask for it.

Why this is safe — verified, not assumed

Concern Finding
Do agent flows need an admin gate? No. Heartbeat, structured reports and the #1083 result callback authorize on current_user.agent_name self-checks.
Does trinity-system break? No. User.agent_name is set only for scope == "agent", so system-scoped keys never trip the guard.
Do MCP tools hit admin endpoints? Yes — six do. The original audit was wrong (it only checked the skills tools against /skills/library/sync). Corrected below.
Do agents lose legitimate capability? No. require_role is deliberately unchanged — MCP deploy_system uses require_role("creator").

That last row is the grant-vs-use line from learnings.md landing where it should: the endpoint that uses a capability may be agent-callable; the endpoint that grants one is human-only. Admin is the granting tier.

Tests — 9, and no MagicMock anywhere

Deliberately: a bare MagicMock auto-creates a truthy .agent_name, so it reads as an agent key and passes for the wrong reason — the trap #1816 recorded and this issue's AC called out. Every principal is an explicit dataclass with every field stated.

Both gates reject an agent principal carrying role="admin"; the exploit is driven through the real update_setting handler; non-regression for a human admin, a system-scoped key, a connector key and a non-admin. Verified 3 fail with the gate fix reverted.

Test-double churn, and why it's honest

The change broke 6 pre-existing tests. All six were incomplete principal doubles that set connector_agent = None — churn from when #1310 added the connector guard — but omitted agent_name: either absent (raising AttributeError) or a truthy MagicMock reading as an agent key.

I checked each rather than assuming, because 6 failures could equally have meant a real flow broke. They didn't; the doubles were simply one guard out of date. Same convention applied.

815 passed across the auth/admin/settings/ops/subscription/retention suites, at failure parity with base (3 pre-existing bcrypt environmental failures before and after).

Closes the privately-tracked issue.


Correction: MCP surface fallout (review of this PR)

The claim above was inaccurate. Six MCP tools call admin-gated routes. Re-audited, split by whether the call is a grant or a use:

Four intended 403s — deliberate, no change

The grant-vs-use line working as designed. Each hands out or revokes a platform credential, which is exactly what an agent-scoped key must not be able to do:

Tool Route Why it stays closed
get_credential_encryption_key GET /api/agents/{name}/credentials/encryption-key Pulls the platform master key
get_agent_ssh_access POST /api/agents/{name}/ssh-access Already self-documents as admin-only
register_subscription POST /api/subscriptions Grants a platform credential
delete_subscription DELETE /api/subscriptions/{id} Revokes one

An agent needing any of these is asking a human to perform a privileged act, and a 403 is the correct answer.

Two fixed — reads, not grants

These left a half-working workflow, which is worse than a cleanly closed door:

trigger_health_check (POST /api/monitoring/agents/{name}/check) — an ops agent could READ health (GET /status, GET /agents/{name}, both non-admin) but not REFRESH it. The require_admin was redundant regardless: AuthorizedAgentByName already restricts the endpoint to callers who own or are shared the agent. Now get_current_user + the unchanged per-agent gate.

list_subscriptions (GET /api/subscriptions) — assign_subscription / clear_agent_subscription / get_agent_auth all kept working under owner gates, so an agent could ASSIGN a subscription it could no longer ENUMERATE.

Note this one is scoped, not un-gated. Un-gating was the first attempt and it traded one disclosure for another: the payload carries owner_email and the full agent-name list of every subscription, so an ungated read hands any role=user account a fleet-wide owner-email + agent-name enumeration oracle — the disclosure class Invariant #8 exists to prevent, reintroduced by a fix for a different disclosure. Resolution: admin keeps the fleet view, everyone else gets owner_id-scoped through a filter already in the accessor's contract. An agent key is excluded from the fleet view by the agent_name term even though it carries the owner's admin role — which is the whole point of ent#293.

Also corrected a stale "Admin-only" docstring on get_subscription_usage, whose gate has always been get_current_user.

Pinned

tests/unit/test_293_admin_gate_rejects_agent_keys.py now covers all three resolutions plus the four intended 403s, so the next change to the gate cannot silently re-break them.

One note on how that test is written, since it bit during this fix: the access-gate assertion reads the source annotation, not the resolved Depends. Sibling monitoring tests override that dependency with a lambda, so a runtime check passes standalone and fails in a full run purely on collection order — caught by running the wider selection rather than the file alone.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validated via /validate-pr. The security reasoning here is right and the fix is the correct shape — three occurrences of one class means the gate was wrong, not the endpoints, and moving the rejection into require_admin/assert_admin closes it at the root. I verified the two load-bearing safety claims independently and both hold:

  • System-scoped keys are unaffected — dependencies.py:360 sets User.agent_name only when scope == "agent", so trinity-system still passes both gates.
  • Agent-originated flows don't touch an admin gate. I enumerated all 116 admin-gated routes across all 63 routers and cross-checked every agent-authored path: heartbeat (agents.py:1182), the #1083 result callback (agents.py:1252), reports (reports.py:56), notifications, emit_event/subscribe_to_event, reminders, write_user_memory, share_file, and all of routers/internal.py. Every one authorizes via a current_user.agent_name self-check. None regresses.

Tests pass locally at 7cdc127b — 113 passed across the new file plus the four touched suites and both test_1310_auth_* wiring/consolidation suites. The no-MagicMock discipline in the new test file is the right call (a bare MagicMock auto-creates a truthy .agent_name and would pass for the wrong reason — the #1816 trap).

One blocking correction: the claim "Do MCP tools hit admin endpoints? No." is not accurate.

Six MCP tools call admin-gated backend routes. The audit only covered the skills tools, which is why this was missed. The MCP layer's only visibility gate is connectorDenied (src/mcp-server/src/server.ts:244,279-281), which filters scope === "connector" — not scope === "agent" — and none of the six has its own scope check. So on a default admin-owned install all six previously succeeded for an agent-scoped key and newly 403:

MCP tool Backend route Gate
get_credential_encryption_key (agents.ts:649) GET /api/credentials/encryption-key require_admin — credentials.py:451
get_agent_ssh_access (agents.ts:669) POST /api/agents/{name}/ssh-access require_admin — agent_ssh.py:19
trigger_health_check (monitoring.ts:164) POST /api/monitoring/agents/{name}/check require_admin — monitoring.py:379
register_subscription (subscriptions.ts:43) POST /api/subscriptions assert_admin — subscriptions.py:60
list_subscriptions (subscriptions.ts:91) GET /api/subscriptions assert_admin — subscriptions.py:122
delete_subscription (subscriptions.ts:227) DELETE /api/subscriptions/{id} assert_admin — subscriptions.py:198

Four of these I read as intended consequences that fit the grant-vs-use line squarely, and I'd keep them: a hosted agent pulling the platform master key is an exfiltration surface; get_agent_ssh_access already says "Admin only" in its own description; register_subscription/delete_subscription are human admin grants. Worth stating explicitly in the PR body rather than leaving them as undocumented fallout.

Two are the actual problem, because they are reads, not grants:

  • trigger_health_check — an admin-owned ops/monitoring agent running fleet-health routines newly 403s. Its siblings get_fleet_health (GET /api/monitoring/status) and get_agent_health (GET /api/monitoring/agents/{name}) are not admin-gated and keep working, so the result is an incoherent surface: an agent may read health but not refresh it.
  • list_subscriptions — assign_subscription, clear_agent_subscription and get_agent_auth all stay working (owner/access gates at subscriptions.py:251,344,396), so the write step of the subscription workflow survives while the read step that discovers subscription names breaks. An agent can assign a subscription it can no longer enumerate.

Neither is a grant, so neither is justified by this PR's own rationale — and both leave a half-working workflow, which is worse than a cleanly closed door.

What I'd like before merge

  1. Give trigger_health_check and list_subscriptions a path that keeps working for an agent-scoped key — either an MCP-layer scope gate that fails cleanly with a comprehensible message, or a non-admin backend path consistent with their already-non-admin siblings. Your call which; the coherence of the surface is the requirement, not the mechanism.
  2. Correct the "no MCP tools hit admin endpoints" line in the PR body, and record the four intended 403s as deliberate.
  3. A test pinning whichever resolution you pick, so the next gate change doesn't silently re-break it.

To be clear about priority: I'm not disputing the fix or asking you to weaken the gate. The P1 is real and this is the right place to close it. Ship the same change with those two tools coherent and I'll merge it immediately.

dolho added a commit that referenced this pull request Jul 30, 2026
…hange (ent#293)

Review of #1890 found the PR body's "no MCP tools hit admin endpoints" claim
inaccurate: six do. Four of those 403s are the grant-vs-use line working as
intended and stay — get_credential_encryption_key, get_agent_ssh_access,
register_subscription, delete_subscription all hand out or revoke a platform
credential.

Two were reads, not grants, and left a half-working workflow, which is worse
than a cleanly closed door:

- trigger_health_check: an ops agent could READ health (GET /status,
  GET /agents/{name}, both non-admin) but not REFRESH it. The require_admin was
  redundant anyway — AuthorizedAgentByName already restricts the endpoint to
  callers who own or are shared the agent. Probing an agent you can already see
  is a use of a capability, not a grant of one.

- list_subscriptions: assign_subscription / clear_agent_subscription /
  get_agent_auth all kept working under owner gates, so an agent could ASSIGN a
  subscription it could no longer ENUMERATE.

list_subscriptions is SCOPED rather than un-gated. Un-gating was the first
attempt and it was wrong: the payload carries owner_email and the full agent
list of every subscription, so an ungated read hands any role=user account a
fleet-wide owner-email and agent-name enumeration oracle — the disclosure class
Invariant #8 exists to prevent, reintroduced by a fix for a different
disclosure. Admin keeps the fleet view; everyone else gets owner_id-scoped, via
a filter already in the accessor's contract. An agent key is excluded from the
fleet view by the agent_name term even though it carries the owner's admin
role, which is the whole point of ent#293.

Also corrects a stale "Admin-only" docstring on get_subscription_usage, whose
gate has always been get_current_user.

Tests pin all three resolutions plus the four intended 403s, so the next change
to the gate cannot silently re-break them. The access-gate assertion reads the
SOURCE annotation rather than the resolved dependency: sibling monitoring tests
override that dependency with a lambda, so a runtime check passes standalone and
fails in a full run purely on collection order.

Related to Abilityai/trinity-enterprise#293

Co-Authored-By: Claude Opus 5 <[email protected]>
@dolho

dolho commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Review addressed — all three items.

(1) The two half-working workflows. Fixed in ebd5c16.

trigger_health_check → get_current_user, keeping AuthorizedAgentByName. The require_admin was redundant anyway; the per-agent gate was already doing the work.

list_subscriptions → scoped, not un-gated. I un-gated it first and that was wrong: the payload carries owner_email and the full agent-name list of every subscription, so an ungated read hands any role=user account a fleet-wide owner-email + agent-name enumeration oracle. That's the Invariant #8 disclosure class, reintroduced by a fix for a different disclosure. Admin keeps the fleet view; everyone else is owner_id-scoped via a filter already in the accessor's contract. An agent key stays out of the fleet view on the agent_name term despite carrying the owner's admin role — which is the point of the issue.

(2) + (3) PR body. Corrected. The "no MCP tools hit admin endpoints" line now says six do and links to a new section recording the four intended 403s (get_credential_encryption_key, get_agent_ssh_access, register_subscription, delete_subscription) as deliberate, with the grant-vs-use rationale per tool.

Pinning. Four new tests cover all three resolutions plus the four intended 403s.

One thing worth flagging from writing them, since it's the kind of thing that silently rots: my first version asserted the access gate by reading the resolved Depends. Sibling monitoring tests override that dependency with a lambda, so it passed standalone and failed in a full run purely on collection order (assert 'get_authorized_agent_by_name' in {'<lambda>'}). It now reads the source annotation via AST instead. Caught by running the wider selection rather than the file alone — noting it because a structural guard that depends on collection order isn't a guard.

485 passed across the monitoring / subscriptions / credentials / ssh / auth-invariant (#1310, #186) selection.

@dolho

dolho commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

/review Report — #1890 + #1893 (the ent#297 pair)

Branches: fix/293-admin-gate-rejects-agent-keys → dev (MB 04d11cf2) · fix/297-retention-settings-hardening → dev (MB 39f29c64)
Files Changed: 8 (+448/−15) · 5 (+559/−9)
Scope: CLEAN both
Plan Completion (ent#297 ACs): 6 done / 1 partial / 0 not done / 1 changed / 0 unverifiable

Self-review, so weighted toward finding problems — my self-review of #1885 earlier this week missed that I'd reintroduced the exact duplication that issue forbade. Four findings, all fixed.


Critical

[C1] Auth boundary: a THIRD admin-gate spelling left open (Confidence: 10/10) — FIXED bf23a2d7

File: src/backend/routers/agents.py:808

@router.post("/{agent_name}/circuit-breaker/reset")
async def reset_circuit_breaker_endpoint(
    agent_name: AuthorizedAgentByName,
    current_user: User = Depends(require_role("admin")),   # <- not require_admin

and the reason it stayed open (dependencies.py:590):

def _require_role(current_user: User = Depends(get_current_user)) -> User:
    _reject_connector_principal(current_user)      # connector, yes
    # reject_agent_principal — absent

Issue. #1890 closes require_admin and assert_admin. There are three spellings of an admin gate; require_role("admin") is the third, and after the other two were closed it was the only one left accepting an admin-owned agent's own key. Its single call site is POST /api/agents/{name}/circuit-breaker/reset — a route ent#297 names in its own blast-radius list ("circuit-breaker resets"). An agent that can re-close its own dispatch breaker on demand defeats the control built to contain it.

The naive fix is wrong, which is why this needed checking rather than patching: adding reject_agent_principal to require_role would break require_role("creator") on POST /api/agents, and agent-spawned agent creation is a supported feature (ent#69 Part 2 — spawned_by_agent provenance, auto-granted parent→child edge, enforce_agent_spawn_scope). It would kill ghost spawning.

Fix applied: swap the one call site to require_admin — equivalent for the admin case (ROLE_HIERARCHY = [..., "admin"], so >= admin is == admin) and it rejects agent principals. require_role's docstring now records why it stays permissive, so nobody "fixes" it later and breaks spawning.

Pinned by an AST scan over routers/. AST, not a regex — the comment on the fixed call site necessarily contains the offending string, and my first version flagged its own documentation. That is the second time this session I wrote a source-scanning guard that matched its own explanatory text; it is now the reason _calls_in_body exists in this file. Meta-tested by planting a violation in monitoring.py and confirming it fires.


Informational

[I1] #1893 invented a bound instead of adopting the existing one (Confidence: 9/10) — FIXED 825afbfd

config.py had _DAYS_MAX = 36500 (100y). The enterprise retention module validates the same windows at le=3650:

execution_row_retention_days: Optional[int] = Field(None, ge=0, le=_MAX_DAYS)   # _MAX_DAYS = 3650

Two validated write paths, two different contracts for one value: an admin could store a window via the OSS route that the managed panel then refuses to edit — surfaced by its own GET, rejected by its own PUT. Aligned to 3650 with a test pinning it, since the enterprise constant can't be imported (private submodule; OSS must build without it). This is the duplicated-policy-constant drift class from learnings.md, committed inside a fix whose theme is "one path".

[I2] Two false claims in #1893's own prose (Confidence: 10/10) — FIXED 825afbfd

[I3] #1890's gate docstrings undercounted the class (Confidence: 8/10) — FIXED bf23a2d7

Both said "three consecutive incidents". ent#297 traced five (ops-agent#232, #1644, #1816, ent#236, ent#293), against 18 bolt-ons and 114 admin-gated call sites. In a security docstring the count is the argument for why the gate moved, so an undercount weakens the reasoning a future reader inherits.

[I4] Enterprise panel can't set one of the eight windows (Confidence: 8/10) — NOT FIXED, enterprise-side

RetentionConfigUpdate covers 7 of 8; agent_reminders_retention_days (#1296) is absent. So the managed retention panel cannot set it, and an entitled operator has no UI for that window. Pre-existing, in the private repo, out of scope for these PRs — flagging for a follow-up.


Clean (verified, cited)

  • AC fix: add missing logging_config.py to backend Dockerfile #4 blocklist is not a bypass. DELETE /api/settings/{key} is untouched, but deleting a retention row reverts to OPS_SETTINGS_DEFAULTS, which are the wide values (30/90/7/180/30/90/90/90 — read at runtime, not assumed). Deleting fails safe; it is not a way around the 422.
  • No legitimate caller broken. Checked before blocking: the Settings UI writes retention only through the enterprise endpoint (Settings.vue:2524), and the sole UI use of /ops/config is the ssh_access_enabled toggle (Settings.vue:3799), which the bool validator accepts. Driven end-to-end via TestClient: the PoC call 422s, a normal key still 200s, the SSH toggle still 200s.
  • All-or-nothing is real, not aspirational — validation runs in its own loop before any db.set_setting, and a behavioural test asserts the good key in a mixed request never lands.
  • assert_admin/require_admin parity — both reject agent + connector, both keep human admins and trinity-system (agent_name is set only for scope == "agent").
  • Enum/value completeness — OPS_SETTINGS_VALIDATION has parity tests against both RETENTION_OPS_KEYS and OPS_SETTINGS_DEFAULTS, so a new window or ops setting can't ship unvalidated.
  • Credential exposure — the new audit details carries ops config values; none of the 16 OPS_SETTINGS_DEFAULTS keys is a secret (thresholds, day counts, one bool), and answering "who shortened retention, to what, when" is the point.
  • Migrations / SQL / concurrency — no schema, no SQL, no shared mutable state in either diff.

Summary

  • Critical: 1 — found and fixed (bf23a2d7)
  • Informational: 4 — three fixed, one (I4) is enterprise-side and reported
  • Scope: clean

The one that mattered was C1, and it is worth naming why it survived the first pass: I audited the gates I changed rather than enumerating every way an admin gate can be spelled. Same shape as the #1871 lesson in learnings.md — a guard for a "more than one call site" class has to start by enumerating the API surface, not the call name you just fixed.

@github-actions

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

@dolho

dolho commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

@vybe all three requested changes are in (ebd5c16a, bf23a2d7), plus one extra the review surfaced.

1 — the two non-grant reads now keep working, coherently:

  • trigger_health_check → dropped to AuthorizedAgentByName + get_current_user, matching its already-non-admin siblings get_fleet_status/get_agent_health. Triggering a probe on an agent you can already see is a use, not a grant.
  • list_subscriptions → owner-scoped, not un-gated. Dropping the gate entirely was the first attempt and it was wrong: the payload carries owner_email + the full agent-name list of every subscription, so an ungated read is a fleet-wide enumeration oracle for any role=user. It now filters by owner_id (admin still sees the fleet), which restores exactly the read the workflow needs — an agent key resolves to its owner and sees the subscriptions it can already assign.

2 — PR body corrected: the "no MCP tools hit admin endpoints" line is replaced with "Yes — six do", and the four intended 403s (get_credential_encryption_key, get_agent_ssh_access, register_subscription, delete_subscription) are documented as deliberate grant-side denials.

3 — tests pin every resolution: test_triggering_a_health_check_is_not_admin_gated, test_listing_subscriptions_is_not_admin_gated, test_the_restored_read_is_scoped_not_ungated (asserts the owner filter, so a future re-ungate fails), and test_the_granting_endpoints_stay_admin_only.

Extra from the review pass — a third gate spelling: require_role("admin") was the one admin gate that still accepted agent keys (it rejects connector but not agent principals, deliberately, because agent-spawned creation runs through require_role("creator")). Its one admin-gated site was POST /api/agents/{name}/circuit-breaker/reset — an agent re-closing its own dispatch breaker defeats the control built to contain it. Fixed at the call site (not the shared helper, which has a legitimate permissive consumer), guarded by test_no_route_uses_require_role_admin_as_an_admin_gate. Recorded in learnings.md.

All green, pushed at bf23a2d7. Ready for re-review.

vybe pushed a commit that referenced this pull request Aug 3, 2026
…s (ent#297) (#1893)

* fix(settings): one validated, audited write path for retention windows (ent#297)

ent#297 is the root-cause issue for a class point-fixed five times: an
agent-scoped MCP key resolves to its owner CARRYING THE OWNER'S ROLE, so on a
default admin-owned install every agent's injected TRINITY_MCP_API_KEY passed
every admin gate. The root fix — reject_agent_principal inside require_admin and
assert_admin — is #1890 (AC 1/2/3/6). This is the other half: AC #4 and #5, the
retention windows the attack actually reached.

Those windows had TWO write paths and neither validated anything:

  PUT /api/settings/{key}    -> bare db.set_setting, no type/range check at all.
                                #1644 blocked the guard's ACK keys here but left
                                the WINDOWS falling through.
  PUT /api/settings/ops/config -> Dict[str, str] written straight through, and
                                  not audit-logged, unlike the generic PUT right
                                  above it.

Now: the catch-all 422s all 8 RETENTION_OPS_KEYS and points at ops/config (same
shape as the #506 ceiling, #1609 proactive caps and ent#12 telemetry consent
redirects), and ops/config type/range-validates every value all-or-nothing plus
audit-logs `ops_settings_change` naming which windows moved.

What this does NOT do, stated plainly because the asymmetry is counter-intuitive
and it would be easy to oversell:

  * garbage always failed SAFE — unparseable coerces to 0, and 0 means "sweep
    disabled", i.e. retain forever;
  * a SMALL VALID INTEGER is the catastrophic input. "1" is well-typed, in
    range, and is exactly the issue's PoC. It is deliberately still ACCEPTED,
    because no range check can separate it from an operator who genuinely wants
    a one-day window.

So validation is not the control that stops the attack — the admin gate (#1890)
and the #1644 blast-radius guard are. What it buys is a loud boundary failure
instead of a silent coercion to a value nobody chose (#1525), and the removal of
the second, entirely unvalidated path. The audit half is its own small fix: the
one route that could shrink a retention window was also the one that left no
trace of having done it, which ent#297 lists in its blast radius.

The #1039 community floor is deliberately NOT clamped here — it is a
fresh-install seed plus an enterprise entitlement clamp, never an OSS hard limit
(#1638), and silently rewriting an admin's explicit 3 into a 5 is the same class
of invisible mutation #1638 was about.

Verification: 34 unit tests (structural + behavioural through the real handlers,
with an explicit non-MagicMock admin principal per the #1816 trap), plus HTTP-level
via TestClient against the real router —

  generic PUT retention window -> 422    (the PoC call, blocked)
  generic PUT normal key       -> 200    (no collateral damage)
  ops/config garbage           -> 422
  ops/config negative          -> 422
  ops/config valid             -> 200
  ops/config ssh toggle (UI)   -> 200    (the only live UI caller of this route)

352 passed across the settings/retention/ops/1638/1644/1709 selection.

Related to Abilityai/trinity-enterprise#297

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(settings): align the day bound with enterprise + correct two claims (ent#297)

Self-review findings on this PR:

1. The upper bound was invented, not adopted. `_DAYS_MAX = 36500` (100y) while
   the enterprise `retention` module validates the SAME windows at `le=3650`
   (10y). Two validated write paths with two different contracts for one value:
   an admin could store a window through the OSS route that the managed panel
   then refuses to edit — surfaced by its own GET, rejected by its own PUT.
   Aligned to 3650 and pinned by a test, since the enterprise constant can't be
   imported (private submodule; OSS must build without it).

2. "the seven retention windows" — there are EIGHT. `agent_reminders_retention_days`
   (#1296) joined RETENTION_OPS_KEYS and my prose didn't. Said in three places.

3. "this is the ONLY write path" — false. The enterprise
   `PUT /api/enterprise/retention/config` is a second one, and it was already
   typed and range-validated, so the security claim was never load-bearing on
   it. Reworded to what is actually true: this is the OSS write path.

Noted while checking (3), not fixed here because it is enterprise-side: that
endpoint's `RetentionConfigUpdate` covers 7 of the 8 windows —
`agent_reminders_retention_days` is absent, so the managed panel cannot set it.

Related to Abilityai/trinity-enterprise#297

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(learnings): enumerate gate SPELLINGS; AST-not-grep for source guards (ent#297)

The durable parts: a class-closing fix must enumerate every spelling of the
gate (a deliberately-permissive sibling helper is where the class survives, and
its permissiveness must be documented AT the helper); a source-scanning guard
must parse the AST because the comment explaining what not to write contains the
offending string; and a new validation bound should adopt the one another module
already applies to the same value, not invent a second contract.

---------

Co-authored-by: Claude Opus 5 <[email protected]>
dolho and others added 3 commits August 5, 2026 11:50
An agent-scoped MCP key resolves to its owner CARRYING THE OWNER'S ROLE, so on a
default admin-owned install every agent's injected `TRINITY_MCP_API_KEY`
satisfied every `assert_admin` / `require_admin` gate.

The chain that makes it P1: a prompt-injected agent repoints `skills_library_url`
at an attacker-controlled repo through the generic `PUT /api/settings/{key}` (the
SEC-179 guard constrains the HOST to github.com, not WHICH repo), the scheduled
sync pulls it, and the fleet sweep writes attacker-authored `SKILL.md` files into
every running agent. A SKILL.md is instructions Claude executes, persisted on the
durable home volume. One compromised agent becomes all of them.

**Fixed at the gate, not the endpoint.** This is the third occurrence of the
class — trinity-ops-agent#232, #1644 (retention acknowledge), #1816 (system-agent
restart) — each previously closed by bolting `reject_agent_principal` onto one
more endpoint. Three occurrences means the gate was wrong. `assert_admin` and
`require_admin` now reject agent principals, which closes the whole class at once
and means a settings key or endpoint added tomorrow inherits the protection
without anyone remembering to ask.

Safe by construction, verified rather than assumed:

* The agent-key flows that must keep working — heartbeat, structured reports,
  the #1083 result callback — authorize on `current_user.agent_name` self-checks
  and never touch an admin gate.
* System-scoped keys are unaffected: `User.agent_name` is populated only for
  `scope == "agent"`, so `trinity-system` still passes.
* `require_role` is deliberately NOT changed. Agents legitimately call
  `creator`-gated endpoints (MCP `deploy_system` → `require_role("creator")`).
  That is exactly the grant-vs-use line from `learnings.md`: the endpoint that
  USES a capability may be agent-callable; the endpoint that GRANTS one is
  human-only. Admin is the granting tier.
* Audited the reachable surface: no MCP tool calls an admin-gated endpoint —
  the skills tools do not touch the admin `/skills/library/sync`.

Tests (9, no MagicMock anywhere — a bare MagicMock has a truthy `.agent_name`
and would pass for the wrong reason, the trap #1816 recorded): both gates reject
an explicit agent-scoped principal carrying role="admin"; the exploit driven
through the real `update_setting` handler; and non-regression for a human admin,
a system-scoped key, a connector key and a non-admin. Verified 3 fail with the
gate fix reverted.

Also completes four pre-existing test doubles that set `connector_agent = None`
(churn from when #1310 added the connector guard) but omitted `agent_name` —
either absent, raising AttributeError, or a truthy MagicMock reading as an agent
key. Same convention, one guard later.

815 passed across the auth/admin/settings/ops/subscription/retention suites, at
failure parity with base (3 pre-existing `bcrypt` environmental failures before
and after).

Closes #293
…hange (ent#293)

Review of #1890 found the PR body's "no MCP tools hit admin endpoints" claim
inaccurate: six do. Four of those 403s are the grant-vs-use line working as
intended and stay — get_credential_encryption_key, get_agent_ssh_access,
register_subscription, delete_subscription all hand out or revoke a platform
credential.

Two were reads, not grants, and left a half-working workflow, which is worse
than a cleanly closed door:

- trigger_health_check: an ops agent could READ health (GET /status,
  GET /agents/{name}, both non-admin) but not REFRESH it. The require_admin was
  redundant anyway — AuthorizedAgentByName already restricts the endpoint to
  callers who own or are shared the agent. Probing an agent you can already see
  is a use of a capability, not a grant of one.

- list_subscriptions: assign_subscription / clear_agent_subscription /
  get_agent_auth all kept working under owner gates, so an agent could ASSIGN a
  subscription it could no longer ENUMERATE.

list_subscriptions is SCOPED rather than un-gated. Un-gating was the first
attempt and it was wrong: the payload carries owner_email and the full agent
list of every subscription, so an ungated read hands any role=user account a
fleet-wide owner-email and agent-name enumeration oracle — the disclosure class
Invariant #8 exists to prevent, reintroduced by a fix for a different
disclosure. Admin keeps the fleet view; everyone else gets owner_id-scoped, via
a filter already in the accessor's contract. An agent key is excluded from the
fleet view by the agent_name term even though it carries the owner's admin
role, which is the whole point of ent#293.

Also corrects a stale "Admin-only" docstring on get_subscription_usage, whose
gate has always been get_current_user.

Tests pin all three resolutions plus the four intended 403s, so the next change
to the gate cannot silently re-break them. The access-gate assertion reads the
SOURCE annotation rather than the resolved dependency: sibling monitoring tests
override that dependency with a lambda, so a runtime check passes standalone and
fails in a full run purely on collection order.

Related to Abilityai/trinity-enterprise#293

Co-Authored-By: Claude Opus 5 <[email protected]>
… (ent#297)

Self-review of this PR found the fix incomplete. There are THREE spellings of an
admin gate, and it closed two.

`require_role` runs `_reject_connector_principal` but NOT
`reject_agent_principal`, and that is deliberate: agent-spawned agent creation
goes through `require_role("creator")` (ent#69 Part 2), so a blanket rejection
there would break ghost spawning outright. The consequence is that after
`require_admin` and `assert_admin` were closed, `require_role("admin")` was
still wide open — and its one call site was
`POST /api/agents/{name}/circuit-breaker/reset`, a route ent#297 explicitly
names in its blast radius. An agent able to re-close its own dispatch breaker on
demand defeats the control that exists to contain it.

Fixed at the call site, not the helper: `require_admin` is equivalent for the
admin case (`admin` is last in ROLE_HIERARCHY, so ">= admin" is "== admin") and
additionally rejects agent principals. `require_role`'s docstring now records
why it stays permissive, so the next reader doesn't "fix" it and break spawning.

Guarded by an AST scan over routers/ so the spelling can't come back. AST, not a
regex: the comment on the fixed call site necessarily CONTAINS the offending
string, and the first version of the guard flagged its own documentation — the
same way this file's `_calls_in_body` helper came to exist. Meta-tested by
planting a violation and confirming it fires.

Also corrects both gate docstrings: they said "three consecutive incidents" —
ent#297 traced FIVE (ops-agent#232, #1644, #1816, ent#236, ent#293), against 18
bolt-ons and 114 admin-gated call sites.

252 passed across the 293/1310/186/circuit/subscription/monitoring selection.

Related to Abilityai/trinity-enterprise#297

Co-Authored-By: Claude Opus 5 <[email protected]>
@dolho

dolho commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@vybe all three asks were addressed in ebd5c16a + bf23a2d7, pushed shortly after your review — the review was never dismissed, so the PR has been sitting as blocked since. Recapping against your list, then what I've just done:

1. The two incoherent tools. Both fixed, and they needed different answers:

  • trigger_health_check → get_current_user + the unchanged AuthorizedAgentByName. The require_admin was redundant anyway: the per-agent gate already restricts the endpoint to callers who own or are shared the agent, so probing an agent you can already see is a use, not a grant. Coherent with its non-admin siblings now.
  • list_subscriptions → scoped, not un-gated. Un-gating was my first attempt and it was wrong: the payload carries owner_email and the full agent list per subscription, so an ungated read hands any role=user account a fleet-wide owner-email and agent-name enumeration oracle — reintroducing a disclosure class while fixing a different one. Admin keeps the fleet view; everyone else is owner_id-scoped through a filter already in the accessor's contract. An agent key is excluded from the fleet view by the agent_name term even while carrying its owner's admin role, which is exactly ent#293's point.

2. PR body corrected — the "no MCP tools hit admin endpoints" line is gone; the table now reads 'Yes — six do. The original audit was wrong (it only checked the skills tools).' The four intended 403s are recorded as deliberate with the grant-vs-use rationale.

3. Tests — test_293_admin_gate_rejects_agent_keys.py pins all three resolutions plus the four intended 403s. One implementation note: the access-gate assertion reads the source annotation rather than the resolved dependency, because sibling monitoring tests override that dependency with a lambda — a runtime check passes standalone and fails in a full run purely on collection order.

bf23a2d7 additionally closes a third spelling of the same gate, require_role("admin"), which the original audit missed.

Just now: rebased onto current dev (clean, no conflicts) so CI re-runs against today's base rather than the 30 Jul one — 279 passed locally across 293/297/admin/subscription/monitoring/1310. (Three test_admin_email_login failures in my local run are a passlib/bcrypt version mismatch in my venv; they reproduce on clean dev and pass in CI.)

Ready for re-review.

@dolho
dolho force-pushed the fix/293-admin-gate-rejects-agent-keys branch from bf23a2d to a1f6099 Compare August 5, 2026 08:53

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving — all three blocking items from my previous review are resolved, and verified against the diff rather than the PR body.

1. Surface coherence. trigger_health_check drops to get_current_user while keeping AuthorizedAgentByName (the admin gate was redundant with it all along), and list_subscriptions is scoped, not un-gated — the right call. Un-gating would have traded the agent-key disclosure for a fleet-wide owner_email + agent-name enumeration oracle readable by any role=user. owner_id scoping was already in the accessor's contract, and an agent key lands in the scoped branch despite carrying role="admin", which is the whole point.

2. PR body corrected, with the four intended 403s recorded as deliberate rather than left as undocumented fallout.

3. Pinned — test_293_admin_gate_rejects_agent_keys.py covers both gates, the exploit driven through the real update_setting handler, non-regression for human admin / system key / connector / non-admin, both restored reads, and the four grants.

The third spelling is a real find. require_role("admin") at POST /{name}/circuit-breaker/reset survived closing the other two gates, and an agent able to re-close its own dispatch breaker defeats the control built to contain it. Keeping require_role permissive (ghost spawning runs through require_role("creator"), ent#69 Part 2) and swapping the one call site is correct; the AST guard is the right shape, since the failure mode is a new route picking the wrong helper — which no behavioural test of existing routes can see. Good catch that both helper tests read the AST rather than grepping source: the comment documenting what not to write contains the offending string.

Verified locally at a1f60999: 118 passed across the new file, both test_1310_auth_* suites, and the four touched suites. All required checks green; pytest (head/base × 3 seeds) green.

One follow-up, not blocking this merge. docs/memory/architecture.md:1254 (Invariant #8) now contradicts the code:

Role ≠ human (#1644, #1816): assert_admin/require_admin answer what role, never is this a human … needs reject_agent_principal in addition to the role gate

That is precisely the bolt-it-on-per-endpoint pattern this PR eliminates, and it also still describes assert_admin as _reject_connector_principal + role only. Left as-is it will tell the next contributor to re-implement the thing that just got centralised. The new hard rule (never write require_role("admin")) is also documented only in a docstring and a test.

I'm reconciling this in one architecture.md pass across today's merge batch rather than pushing to this branch — eight PRs in flight touch that file, so batching avoids compounding the conflict. Tracking it explicitly; it will not be dropped.

Cross-tracker refs resolve: ent#293 (P1, status-in-progress) and ent#297 (P1, status-in-dev). GitHub auto-closes same-repo only, so I'll bump both manually after merge.

@vybe
vybe merged commit 106d454 into dev Aug 8, 2026
21 checks passed
vybe pushed a commit that referenced this pull request Aug 9, 2026
…1890, #1821) (#2062)

`#1890` moved the agent-principal rejection into `require_admin`/`assert_admin`
themselves, but Invariant #8 still described the pre-fix model — that the admin
gates answer "what role" and never "is this a human", and that an operator-scale
endpoint therefore needs `reject_agent_principal` bolted on *in addition to* the
role gate. That is precisely the per-endpoint pattern #1890 eliminated, so left
as-is the doc would tell the next contributor to re-implement the thing that was
just centralised, on a security invariant.

Rewrites that paragraph to describe the gate as the mechanism, records the two
admin-gated reads that were re-opened as *uses* rather than grants (and why
`GET /api/subscriptions` is owner-scoped rather than un-gated), and writes down
the new hard rule — never `require_role("admin")` — which until now lived only
in a docstring and an AST guard.

Also updates the `assert_admin` helper description in the same invariant, and
the `PUT /api/agents/{name}/label` row for #1821 (`label` is now
required-but-nullable with `extra="forbid"`; `{}` and unknown fields 422).

Docs only — no code, no schema, no behaviour change.

Co-authored-by: trinity-ability <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
AndriiPasternak31 added a commit that referenced this pull request Aug 9, 2026
Rebasing onto dev picked up two changes that landed under this branch and
moved what its own tests assert. Both are the other change being right.

- ent#15 (#2040) inserted an import-intent gate into `_resolve_template`
  ahead of the fork gate. Two `SimpleNamespace` config doubles predate the
  field, so `config.import_intent` raised AttributeError before reaching the
  assertion — a stub gap, not a production one. The fork/clone path and the
  S2 fail-closed gate are unchanged, and dev's `copy` intent carries its own
  `fork_to_own: required` refusal before its early return.

- #1890 made `require_admin` itself reject agent-scoped principals, closing
  the class at the gate rather than per-endpoint. This suite asserted an
  agent key could still READ the registry setting, on the reasoning that the
  human check belongs on the writes. That is now overruled, and correctly:
  the GET returns the registry URL plus a live status block, which for a
  private catalog is exactly the pointer an agent should not enumerate. The
  explicit `reject_agent_principal` on PUT/DELETE is kept as belt-and-braces
  — it states the intent locally and survives any relaxation of the gate.

Co-Authored-By: Claude Opus 5 <[email protected]>
vybe pushed a commit that referenced this pull request Aug 9, 2026
…ity-enterprise#14) (#2033)

* docs(requirements): TMPL-002 remote template registry (ent#14)

Rule of Engagement #1 — requirements land before implementation.

New §4.2.2 in core-agent.md, placed immediately after §4.2.1 because the
registry is a new *source* for the seam TMPL-001 documents: a reader who lands
on 4.2.1 must find it in the next paragraph, not in another file. §4.2.1's
"None = use defaults" sentence gets the one-line cross-reference that keeps it
true.

Two things the entry states plainly rather than comfortably:

- `repo` is a capability pointer. It is literally true that the four
  allowlisted fields only change which repos are listed and how they are
  labelled/ordered; as a security statement that is misleading. Choosing the
  repo chooses which template.yaml Trinity fetches and trusts, and that
  document declares mcp_servers, credentials, schedules, data_paths,
  persistent_state and fork_to_own. The allowlist bounds the direct blast
  radius, not the indirect one.

- The honest GitHub cost. A non-empty registry re-introduces the per-repo
  metadata fetches #1931 had driven to zero: workers x windows/hr x entries.
  On a PAT-less install that exceeds the 60/hr anonymous budget above ~5
  entries, which is exactly the precondition that makes the fork_to_own
  fail-open reachable.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(safe-yaml): distinguish the per-repo payload from the remote index

The TWO ALIAS POLICIES docstring says a "template catalog entry" may
legitimately anchor a repeated block, and that clause reads as an argument for
giving the remote registry a BUDGET policy. It is not one — the only shipped
BUDGET caller is load_template_yaml, a per-repo template.yaml, which really can
anchor a repeated block. The remote index cannot: it is a flat list of unique
entries carrying one pointer and three display scalars each.

Amend the clause so the next author cannot make the same misread, and add
load_template_registry_yaml() pinning REJECT + the 256 KiB cap at the utils
layer — the same reason load_template_yaml exists, so the decision is never
relitigated at a call site.

Duplicate-key rejection is load-bearing for this document specifically: a
registry with two `templates:` keys would silently last-wins, showing one
catalog to the human editing the file and serving another to Trinity.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(config): registry URL + hard kill switch, and its SSRF gate

TEMPLATE_REGISTRY_URL / TEMPLATE_REGISTRY_ENABLED on the OPERATOR_INTAKE_ENABLED
shape, plus validate_template_registry_url().

Two choices worth their comments:

The switch is deliberately NOT settings_service._resolve_bool_flag. That
helper's env leg is opt-in only ("true"/"1"/"yes" -> True, anything else falls
through to `default`), so with default=True it would silently swallow
TEMPLATE_REGISTRY_ENABLED=false and ship a kill switch that does nothing —
#1039's inert-by-obscurity class, caught before a line of it was written.

The validator is a sibling of validate_skills_library_url, not a reuse: that one
is github.com-only, which is right for a clone target and wrong for a registry
an operator may self-host. What carries over is the perimeter check; what is new
is refusing userinfo outright rather than stripping it (a stripped credential
gets persisted into a settings row and echoed through a status payload) and
refusing an unresolvable host rather than deferring, since unlike a later git
clone nothing downstream will fail loudly on our behalf.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(templates): remote template registry service (ent#14)

The fetch/parse/cache half. Never raises; every failure returns [].

Fail-open here is structural, not an except branch: get_all_templates() returns
local + github, local needs no network, github is empty by default, and this
module can only ADD to github. So unreachable / 5xx / timeout / malformed /
bombed / oversize / redirected / empty all reduce github toward [], which is the
already-shipping default state of the product. The except layers are a second
layer on top, because fail-open must not depend on this module being bug-free.

Decisions that are load-bearing and easy to undo by accident:

- The byte cap is enforced on bytes RECEIVED, not on Content-Length, which is
  absent on chunked responses and trivially lied about. resp.text on a 10 GB
  body OOMs the worker before any parse-time cap can act, so the transport
  ceiling is the gate and the parser's max_bytes is the belt.

- follow_redirects=False is a security control. A URL that passed the SSRF gate
  and then redirects is a bypass; a redirect is a fetch failure.

- TTL is 3600s + jitter, deliberately NOT aligned with the 600s per-repo cache.
  Aligning them is a correlated thundering herd, not a shared rhythm: one expiry
  fires the registry fetch and N per-repo GitHub fetches in the same instant,
  and --workers 2 drift into phase. It is also the cheapest lever on the
  anonymous GitHub budget, so it is doing security work, not tidiness.

- Serve-stale is capped at 7 days. Unbounded stale keeps a de-curated, renamed
  or compromised repo listed indefinitely while the operator sees a catalog that
  still renders — no signal at all.

- Invalidation is a generation counter read at cache-hit time, not a per-process
  clear. A per-process clear half-applies under --workers 2, and a
  nondeterministic setting is worse than a slow one. Coupled to the TTL raise;
  the two must not be split.

Found while smoke-testing the parser: `../evil` matches all four copies of the
owner/repo regex, because `.` is inside the character class. That breaks the one
invariant the catalog card rests on — the id would render "../evil" while both
the API and clone URLs normalize to a different repo. This gate now refuses dot
segments explicitly and is deliberately stricter than its three siblings, which
share the hole on paths reachable only by hand-typed ids.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(templates): resolve the registry in BOTH resolvers, fail the fork gate closed

Two changes that only make sense together.

get_all_templates() was never the only resolver. get_github_template() resolves
the same repo list for GET /api/templates/{id} and for agent creation
(crud._resolve_github_repo_and_pat), and its ladder ended in a dynamic
fallthrough calling _build_template with no override dict at all. Landing the
registry in one of them would have listed a template as "Cornelius - your second
brain" and resolved it by id as "cornelius" - and under a rate limit the detail
view degrades to the repo basename, so the hardening the registry buys would not
have reached the detail path. Both now share one ladder; a test pins list,
detail and create to it. learnings.md 2026-07-10, on schedule.

The second change is why the first one matters. An unreadable template.yaml and
an absent one were the same value: _fetch_template_yaml_result already
distinguishes them and the catalog wrapper threw the reason away one frame below
the code that computed it. So a 403 produced fork_to_own: None, `== "required"`
was False, and creation bound the agent to the shared upstream template repo
instead of a user-owned copy. Silent, and the thing in the wrong place is the
user's knowledge base.

That bug is pre-existing. This feature is what makes it expected rather than
theoretical: it re-introduces per-repo fetches on a default install, ships
default-on, and its own arithmetic puts a PAT-less install over GitHub's 60/hr
anonymous limit above ~5 listed repos - while the fleet the registry exists to
serve very likely includes the fork_to_own template.

The reason is now cached alongside the metadata and surfaced as
metadata_unavailable, and creation refuses (503, retryable) rather than
guessing. Scoped to the branch that is unsafe: a caller who IS forking gets a
user-owned repo whatever the template declares, so an outage does not block
them. A clean 404 stays "absent", so a repo that ships no template.yaml creates
as it always has.

Also here, because it is the same builder: priority becomes overridable, which
is the only dimension of "curate freely - feature, order, add, deprecate" that
had no mechanism.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(settings): GET/PUT/DELETE /api/settings/template-registry

Same shape as /api/settings/github-templates deliberately — the registry is a
new source for that seam, not a second settings idiom. Registered before the
/{key} catch-all (Invariant #4), verified by inspecting the router's own route
order rather than by reading it.

reject_agent_principal on both writes is not optional. assert_admin answers what
role, never whether this is a human: get_current_user resolves an agent-scoped
MCP key to its owner carrying the owner's role, so on a default admin-owned
install any agent's injected TRINITY_MCP_API_KEY passes a bare admin gate
(trinity-ops-agent#232). The consequence here is total — an agent could repoint
the platform's template registry at a URL it controls and every operator
browsing templates would see its catalog.

The catch-all blocks all four registry keys, on PUT *and* DELETE. PUT because
the generic route takes an unvalidated Dict[str, str], which would leave the
SSRF gate one request away from bypass. DELETE because — unlike the #1644
retention acks, where deleting an ack re-arms a guard and fails safe — deleting
template_registry_enabled reverts it to its default of ON, re-enabling egress an
operator deliberately switched off, and that route carries no human gate.
generation and lkg are blocked because they are the cache itself.

The status block on GET is part of the contract, not decoration: fail-open makes
every registry failure invisible in the catalog by design, so this is the only
place an operator can see that their registry 404s.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* feat(settings-ui): template registry panel; fix a stale MCP tool description

The panel is a new file specifically so Settings.vue's raw-color counts cannot
move — the ratchet only lets per-file counts shrink, and Settings.vue sits at 63
non-gray. It gains one import and one tag, neither carrying a class. Measured:
the new panel is 0 non-gray / 0 hex / 32 semantic tokens, and Settings.vue is
byte-identical to origin/dev at 63/832/1 (the gray drift vs the committed
baseline predates this branch).

The status block is the point of the panel, not decoration. Fail-open means a
broken registry looks exactly like a working empty one from the catalog, so this
is the only surface where an operator can see that their registry 404s. The
backend publishes a fixed lowercase code and never prose — a hostile server's
response text must not reach an admin's screen — so the explanations are ours,
keyed by code, and each one names the remedy.

Uses LoadFailed for a failed fetch and InlineError for a failed verb rather than
sharing one error line: "couldn't load the settings" and "couldn't save the URL"
point at different remedies, and principle 18 says a failed verb persists next
to the control rather than becoming a toast.

The MCP fix: create_agent's `template` description asserted that list_templates
"on a default install returns local templates only until an admin curates GitHub
repos in Settings". With a default-enabled registry that is false, and a wrong
tool description actively misleads a model. Description only — no parameter,
client method, type or behaviour change, so Invariant #13 stays satisfied
without touching the tool.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(ent14): the fail-open matrix, proven rather than asserted

309 tests across five files. Every failure mode is driven through the real
parser and a real httpx client over MockTransport, and every assertion is on the
CATALOG OUTPUT — not on whether an except branch ran. A test that asserts the
except branch ran would still pass if that branch returned garbage.

The matrix: unreachable, read timeout, 404/403/500/503, redirect, oversize body,
lying Content-Length, malformed YAML, level-6 alias bomb, duplicate keys, HTML
captive portal, binary body, top-level list, future schema version, non-list
templates, empty body, empty registry — each asserted twice, once for "the
catalog equals the bundled floor" and once through the router's own sort, which
is where a non-int priority used to 500 the endpoint. Plus a registry service
that simply raises, because fail-open must not depend on it being bug-free.

Two tests exist to stop the matrix being vacuous: one pins that the real bundled
floor is non-empty (otherwise every "degrades to the floor" assertion is
trivially true), and one re-probes the lying Content-Length through a second
client to prove the header really said 12 while the body was 100 KB — otherwise
a future refactor could start trusting Content-Length and these would still be
green.

The F2 regression test was verified to be red without its fix: neutralising the
guard fails 10 of its 24 assertions.

The parity test encodes a real divergence rather than papering over it. `.` is
inside the shared owner/repo character class, so `../evil` matches all three
older copies of the pattern; the registry gate refuses dot segments and the test
pins BOTH halves — the shared corpus where all four agree, and the containment
that everything the registry accepts, the others accept. If somebody later
tightens those copies, the test fails and points at deleting the assertion
rather than leaving a stale comment.

tests/unit/pytest.ini overrides pyproject.toml, so asyncio_mode = auto does not
apply here and a bare `async def test_*` is collected and silently never
awaited. Everything is sync; the one async call under test is driven through an
explicit asyncio.run.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ent14): architecture + feature flows for the remote template registry

architecture.md x3, in place — the registry is one source feeding one existing
service, not a cross-cutting subsystem: the template_service catalog entry gains
the ladder, template_registry_service gets its own <=2-line catalog entry, and
the Platform Settings table gets the three endpoint rows.

The flow doc is standalone rather than a section inside platform-settings.md.
The plan named that as an escape hatch if the section ran past ~60 lines; it ran
to 495, because the fail-open matrix, the cache semantics and the fork_to_own
fix each need their own argument. So platform-settings.md gets a short section
with the three things a reader of THAT file needs, and the index gets a catalog
row — a new doc always gets one.

library-page.md's `GET /api/templates` row said the GitHub half was the
admin-configured list or config.py defaults. That becomes wrong on merge, so it
now names the three-tier ladder. The page itself is unchanged, which is the
point: registry entries are source: "github" and land in the existing grid.

platform-settings.md already carried the sentence "trinity-enterprise#14 will
repoint this seam". This change is what makes it past tense.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(templates): the fork_to_own fail-open limitation is fixed, not restated

/sync-feature-flows found this and my own docs pass had missed it.
template-processing.md carried, as a Known Limitation:

  "fork_to_own: required enforcement is fail-open when the template.yaml
   metadata fetch fails (advisory gate; empty metadata -> flag unseen for that
   10-min cache window)"

That was an accurate description of a real defect, written down and left. It is
now false, and a stale limitation is worse than none — the next reader would
have designed around a gate that no longer behaves that way.

Replaced with what actually happens, keeping the old sentence quoted so the
history is legible: the fetch reason rides the metadata cache as
metadata_unavailable, the non-forking creation path refuses with a retryable
503, a clean 404 still means "declares nothing", and a caller who is forking is
never blocked. The trade-off is stated rather than buried — creation now depends
on GitHub API reachability where it previously depended only on git clone.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ent14): restore the vendored safe_yaml mirror and two stubbed seams

Three regressions the full unit run caught that the targeted runs could not.

1. safe_yaml.py is a BYTE-IDENTICAL vendored mirror into the agent server
   (Invariant #5, ent#314/#1965) and I edited only the canonical copy. The
   parity guard is exactly the CI mechanism that exists for this and it worked;
   re-copied. Worth noting the architecture doc's own warning applies here: a
   guard that walks only one tree is not a guard, and this one walks both.

2. get_all_templates() had moved onto a renamed bulk fetch
   (_fetch_all_metadata_results), which silently bypassed two existing test
   doubles — test_ent89's fence stub and test_1931's network stub — so both
   fell through to real code. _fetch_all_metadata keeps its name and its
   `repo -> metadata` return shape; the fetch reason rides _metadata_cache
   instead and is read back by _metadata_reason_from_cache. No caller pays a
   signature change, and routers/settings.py's direct call is untouched.

   The bulk path still submits the reason-preserving variant, deliberately: a
   cache entry written with reason=None for a repo whose fetch actually 403'd
   would tell the creation path "readable, declares nothing" for a full TTL —
   reopening the fork-gate bypass through the catalog's own cache.

3. Two test doubles updated where the seam genuinely moved rather than the code
   being wrong: test_ent89's _build_template stub was one parameter short (a
   short stub raises TypeError *inside* the fence that class exists to test, so
   the assertion failed for an unrelated reason), and test_1931's stub set now
   includes _fetch_template_yaml_logged — without it the counter-test silently
   stops counting, which is the failure mode that test was written to prevent.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(ent14): pin the settings stub by sys.modules key, not by module object

43 of my own tests passed in isolation and failed under the full run — the exact
trap test_ent89_template_schedules.py documents, walked into anyway.

Both consumers resolve the module lazily, at call time: template_service's
`from services.settings_service import get_github_templates` and the registry
service's `from services.settings_service import settings_service` each read
sys.modules by key. Patching an attribute on a separately-imported reference
works right up until an earlier file has swapped the module object, after which
the stub is silently ignored.

The resulting failure was worse than confusing, it was inverted: with the stub
bypassed the real accessor read the real tmp SQLite database, found the durable
last-known-good a previous ent14 test had legitimately persisted, and served it
— so a test asserting "a connect error degrades to the floor" reported a
fail-open bug that does not exist. A green isolated run and a red full run
disagreeing about a security property is the worst shape this could have taken.

Fixed with monkeypatch.setitem on the exact key, and the stub built from a copy
of the real module's namespace so SettingsService and the key constants still
resolve through it.

Full unit suite: 7781 passed, 16 skipped, 0 failed.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ent14): the hard kill switch was inert — wire both registry knobs into both composes

config.py read TEMPLATE_REGISTRY_ENABLED and TEMPLATE_REGISTRY_URL from the
environment, and neither compose file injected them. Prod compose launches
standalone — no base merge, no env_file: on any service — and it is what every
deploy path uses, so the explicit environment: list is the only route into the
container. Both levers were inert on every real instance while working fine on a
laptop, where the shell environment reaches the process directly.

TEMPLATE_REGISTRY_ENABLED is the feature's hard kill switch: the documented
air-gap answer that no system_settings row may override. An inert one is not a
missing convenience — it is a default-ON feature making outbound requests with no
way to stop it.

The irony is the reason this is pinned rather than just fixed. The comment block
directly above the os.getenv call argues at length, and correctly, against
routing the flag through settings_service._resolve_bool_flag, because that
helper's opt-in-only env leg would "silently swallow
TEMPLATE_REGISTRY_ENABLED=false and ship an inert kill switch (#1039 class)".
The flag then shipped inert anyway, by the other route, ~15 lines away. Avoiding
a known failure mode in the layer you are looking at does not avoid it in the
layer you are not.

Sixth recurrence of the #1039/#1056 packaging-gap class (#1056 VOIP_*, ent#31
LOG_*, #1039, #1871 AGENT_LOG_*, #411 CANARY_*), so it gets a guard shaped like
test_canary_env_prod_parity.py — the guard for the fifth.

What the guard asserts, and why presence is the wrong property:
  - injection in BOTH composes; drift between them IS the bug
  - the ${VAR:-true} form, not a hardcoded `- TEMPLATE_REGISTRY_ENABLED=true`,
    which satisfies a presence check while re-breaking the switch
  - the URL's full non-empty default; a bare `:-` arrives set-but-empty,
    os.getenv returns "" instead of falling back, and the registry points at
    nothing (#1076) — strictly worse than absent, because it looks wired
  - compose and config.py defaults are equal, since two spellings of one default
    drift invisibly (the container always wins, so the code default becomes
    decorative while still reading as authoritative)
  - a meta-test that goes red on pre-fix content AND on the hardcoded revert

Verified by rendering rather than grepping: `docker compose config` shows both
vars on backend for each file, and TEMPLATE_REGISTRY_ENABLED=false propagates
through to "false". The guard was additionally proven by deleting the real prod
line and watching it go red — the first attempt at that used
`grep -v 'VAR=${VAR'`, where $ is an end-of-line anchor, so nothing was removed
and the suite reported a false green against an unmodified tree.

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(ent14): CSO diff findings — wire-byte ceiling, creation-path fork gate, CGNAT

Three findings from the security review of this branch, each a case where the
control was present and correct one level above where the attack lands.

S1 — a byte ceiling on decoded bytes is not a byte ceiling.
_fetch_registry_text streamed under a 256 KiB running total, with a docstring
correctly explaining why Content-Length cannot be the gate and why resp.text on
a huge body OOMs the worker. Both true, both defeated one level down: a custom
headers= dict does not override httpx's default Accept-Encoding: gzip, deflate,
and iter_bytes() yields DECOMPRESSED chunks. A 199 KiB wire body — under the cap,
so the early abort passes it — inflated ~1030:1 before the running total was ever
consulted: 458 MB of transient allocation on the event-loop thread. The cap
bounded the decoded total, which is not the resource under attack; the peak is.
Now the ceiling counts wire bytes via iter_raw(), any Content-Encoding is refused
outright before the body is read (encoding_refused, named rather than folded into
bad_shape so gzip bytes hitting a UTF-8 decode don't report as a shape problem),
and Accept-Encoding: identity is sent as the polite half only — a request header
is a preference, never a control over a hostile server. Same body post-fix peaks
at 0.01 MB.

The harness hid it and then inflated it: httpx.Response(content=…) decodes and
buffers in the CONSTRUCTOR, so every fixture built a response the production
iter_raw() path cannot even read and that could only ever exercise iter_bytes().
The byte-ceiling tests were green against a shape incapable of expressing the
failure. Both transport fixtures now convert every mock to a real stream — a
transport test whose mock does not stream is not a transport test.

S2 — the fork_to_own gate read the catalog cache, not its own read.
The gate is correct in direction and was wrong in source: it consulted
gh_template["metadata_unavailable"], derived from the global platform PAT, off
the default branch, through a 600 s cache — while crud.py had already read the
same template.yaml one line earlier with the caller's resolved PAT and parsed
ref, cache-bypassed, for ent#89's schedules. ent#89's own docstring had written
the warning: "the exact silent-ignore class this feature exists to close,
reintroduced one layer up."

Both error directions followed. FALSE PASS: GitHub answers 404, not 403, for a
repo a token cannot see, so a private fork_to_own: required template readable
only by the creator's own PAT was classified absent, the gate passed, and the
agent bound to the shared upstream — the precise outcome the gate exists to
prevent, with no attacker involved. FALSE REFUSE: a poisoned shared cache entry
503'd a creator whose own PAT read the file fine, for a full TTL.

Fixing only the availability half would NOT have closed the false pass — for a
private template the catalog's fork_to_own VALUE is None for the same reason its
verdict is wrong, so the gate would sail past a `required` it still could not
see. Both inputs now come from _read_source_template, and `required` from EITHER
read enforces: a union, so this can only remove a false pass, never add one.
Costs zero extra GitHub calls, and the read that DECIDES is now made with the
same credentials as the clone that follows.

S3 — RFC 6598 shared address space (100.64.0.0/10) was admitted.
Python's ipaddress reports CGNAT as neither is_private nor is_reserved, so the
standard predicate stack passed it. Not reachable in Trinity's own topology
(both Docker networks are 172.28/16 and 172.29/16, which are is_private), but
several cloud providers address internal endpoints out of that range, so a
Trinity deployed there had a hole the same shape as 10.0.0.0/8. Both /10
boundaries are held public so a legitimate registry is not blackholed, and one
CGNAT record among public ones is enough to refuse.

Docs: requirements TMPL-002, architecture, template-registry + scheduling flows,
and three learnings entries for the transferable classes: a decoded-byte
ceiling; a gate reading the catalog's cached metadata instead of the
creation-path read standing one line above it; and the packaging class from the
preceding commit — its ledger entry rides here because learnings.md is a single
append-only file and the compose fix was committed on its own to stay
self-contained.

Full unit suite: 7851 passed, 17 skipped, 0 failed (pytest-randomly).

Refs trinity-enterprise#14

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(ent14): adapt two suites to dev's newer gates after the rebase

Rebasing onto dev picked up two changes that landed under this branch and
moved what its own tests assert. Both are the other change being right.

- ent#15 (#2040) inserted an import-intent gate into `_resolve_template`
  ahead of the fork gate. Two `SimpleNamespace` config doubles predate the
  field, so `config.import_intent` raised AttributeError before reaching the
  assertion — a stub gap, not a production one. The fork/clone path and the
  S2 fail-closed gate are unchanged, and dev's `copy` intent carries its own
  `fork_to_own: required` refusal before its early return.

- #1890 made `require_admin` itself reject agent-scoped principals, closing
  the class at the gate rather than per-endpoint. This suite asserted an
  agent key could still READ the registry setting, on the reasoning that the
  human check belongs on the writes. That is now overruled, and correctly:
  the GET returns the registry URL plus a live status block, which for a
  private catalog is exactly the pointer an agent should not enumerate. The
  explicit `reject_agent_principal` on PUT/DELETE is kept as belt-and-braces
  — it states the intent locally and survives any relaxation of the gate.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: trinity-ability <[email protected]>
vybe pushed a commit that referenced this pull request Aug 16, 2026
…h sessions, close the portal agent-key hole (#2198) (#2222)

* perf(agents): join concurrent duplicate fetches instead of issuing both (#2198)

Agent Detail issues the same GET several times on one mount because several
independent triggers ask for it at the same moment. Neither existing precedent
collapses that: `stores/executions.js` is a RESULT cache, so two simultaneous
first-calls still both hit the network, and `stores/fleetGrid.js` is an
in-flight SKIP that returns no value, which `loadAgent()` cannot use because it
needs the agent object back.

Adds the missing third shape — an in-flight JOIN — as one shared primitive
(`utils/inflight.js::dedupe`) rather than a fourth bespoke mechanism, and wires
`fetchAgent`, `getAgentInfo`, `getAgentDashboard` and `checkDashboardExists`
through it.

Three semantics, each load-bearing and each covered by a test:
  - JOIN, not skip: every caller resolves with the winner's value.
  - Cleared in `finally`: this is a dedupe, NOT a cache, so two SEQUENTIAL calls
    still issue two requests. `AgentDetail.waitForAgentStatus()` polls
    `fetchAgent` in a loop and a stale entry would freeze it forever.
  - Rejection propagates to every joiner and clears the entry, so one failure
    never poisons the next attempt (`fetchAgent` re-throws and AgentDetail's
    404 branch depends on that).

Deliberately not a global axios interceptor: that is an app-wide behaviour
change, it would MASK genuine repeat-fetch bugs, it must never apply to POSTs,
and it would change what e2e `page.route()` interceptors observe.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* perf(agents): stop Agent Detail loading everything twice on first mount (#2198)

Vue fires BOTH onMounted and onActivated on the first mount of a KeepAlive'd
component (`App.vue` includes 'AgentDetail'), so every data call in both hooks
ran twice — visible as two `/api/agents/{name}` requests sharing one timestamp.
Separately, `checkDashboardExists()` has FOUR triggers (route watcher, status
watcher, onMounted, onActivated) and each ran its own 3-step boot retry ladder,
for 9 `/api/agent-dashboard/{name}` calls spread over ~9 seconds.

Three changes, all in this file:

1. A CONSUMABLE first-activation sentinel. onMounted arms it before its first
   await; onActivated reads AND clears it as its very first statement, above
   the `redirectRetiredSessionLink()` early return. Consumable matters: a
   one-way flag would skip the data half on EVERY later activation, so a
   KeepAlive revisit would never refresh the agent — the entire reason
   onActivated exists (#1672), a worse bug than this one, and invisible to a
   request-count test. Consuming it above the early return matters for the same
   reason: the retired-link path would otherwise leave it armed.

   onActivated still runs redirectRetiredSessionLink, applyDeepLinkRouting and
   startAllPolling unconditionally in both hooks (#1672/#2130/#2153/ent#358).
   reconcileDeepLinkVisibility and startEmotionCycling are deliberately NOT in
   that set — both are *consuming*, and running reconcileDeepLinkVisibility
   before the agent has loaded would judge `?tab=sharing`/`?tab=brain` invisible
   against a null agent, fall back to Overview and clear the flag, making
   onMounted's own call a no-op. That regresses #2130 and #2153 silently.

2. One dashboard probe instead of four. The store-level join cannot collapse
   this — the four triggers fire hundreds of ms apart (measured +0/+326/+396ms)
   and a promise-join only merges concurrent calls, so the join has to happen at
   the level of the probe. The probe key carries running-ness, not just the
   name, because the ladder early-returns on `status !== 'running'`: a probe
   started while the agent was booting settles without asking, and a "just
   became running" watcher joining it would strand a slow-starting agent without
   its Dashboard tab forever. The route watcher drops the probe so agent B never
   inherits A's answer.

3. The `loading` skeleton gate now compares IDENTITY, not presence
   (design-system-contract:41-43 — a background refresh of the same entity is
   invisible, a switch to a different entity animates). A plain `!agent.value`
   would be a regression: the route watcher resets hasDashboard/agentTags/
   authStatus/tokenStats but deliberately never clears `agent.value`, so an
   A -> B switch would show agent A's data while B loaded.

Measured, `acme-sage` (running, no dashboard.yaml — the worst case), full page
load then a same-document revisit:

  page load   65 -> 52 requests    revisit   27 -> 22
  /agent-dashboard/{a}    9 -> 3   (one ladder, not three)
  /agent-dashboard/{a}/exists  3 -> 1
  /api/agents/{a}         2 -> 1
  /avatar/emotions        2 -> 1
  /api/agents/{a}/info    3 -> 2   (rest in a follow-up commit)

`/api/agents/{a}/activity` x4 is unchanged on purpose — that is correct 5s
polling, not a duplicate.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* perf(agents): one /info and one /playbooks fetch per Agent Detail mount (#2198)

Two more duplicate pairs on the same page, both from a second component
independently fetching what a sibling already has.

`/api/agents/{name}/info` x3 -> x1. `OverviewPanel.loadSidecars()` issued a RAW
`axios.get` for it inside its 10-call `Promise.allSettled`, while AgentDetail's
`checkBrainOrbCapability()` asked the store for the same thing from both
lifecycle hooks. Overview is the default landing tab, so all three ran on every
mount. Routing the sidecar through `agentsStore.getAgentInfo` puts it behind the
in-flight join; `loadAnalytics()` two functions above already uses the cached
store methods, so the precedent was literally adjacent.

  Note the deliberate `.data` drop at the assignment: the store returns
  `response.data` already unwrapped, unlike the nine raw-Axios siblings. Keeping
  `.data` would have set `info` to `undefined` with no throw and no console
  error — a permanently blank "About" lead on the default tab. Silent is worse
  than loud, so it is called out in a comment at the line.

`/api/agents/{name}/playbooks` x2 -> x1. ChatPanel fetches the list for
<ChatEmptyState> and ChatInput's autocomplete composable fetched the identical
list (same endpoint, same `user_invocable` filter) for the slash-command
dropdown. ChatPanel is `v-show` in AgentDetail, so it mounts on EVERY tab, not
just Chat. ChatInput gains an OPTIONAL `playbooks` prop and skips its own load
when it is supplied.

  `null` (not supplied — fetch your own) is deliberately distinct from `[]`
  (supplied and empty): `views/PublicChat.vue` is the other <ChatInput> consumer
  and depends on the composable's public-token path, which ChatPanel never
  exercises. Defaulting the prop to `[]` would silently kill slash-commands in
  public chat. A module-scoped cache inside the composable was rejected for the
  same reason — it would leak across agents and across the public/authenticated
  boundary, which carry different auth headers.

Measured, `acme-sage` (running, no dashboard.yaml), full page load:
  /api/agents/{a}/info       3 -> 1
  /api/agents/{a}/playbooks  2 -> 1

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* perf(settings): fetch feature-flags once per page load, not once per store (#2198)

`GET /api/settings/feature-flags` was requested twice on every authenticated
page. Not a KeepAlive artifact: two domain-scoped Pinia stores fetch it
independently and parse disjoint slices of the SAME payload —
`stores/sessions.js` keeps eight booleans and derives `a2aAvailable` from
`enterprise_features`, `stores/enterprise.js` keeps only `enterprise_features`.
So `sessions.a2aAvailable` and `enterprise.enterpriseFeatures` are two HTTP
calls reading one array.

Adds `once()` beside `dedupe()` in the shared primitive: an in-flight join PLUS
a resolved-value cache. The stronger form is required here and measured, not
assumed — the two calls land 319 ms apart, so the second starts after the first
has already resolved and a pure in-flight join does not touch them.

`once()` is deliberately not the default, and the agent endpoints deliberately
stay on `dedupe`: it is only safe for a document that is immutable for the
lifetime of a page load. Agent state changes underneath you, and
`AgentDetail.waitForAgentStatus()` polls `fetchAgent` in a loop expecting a
fresh answer each time. A failure is never cached, so a later caller can retry.

Chosen over having one store call the other (the obvious minimal fix): that
would require sessions.js to start retaining `enterprise_features` it does not
want, couple two domain-scoped stores against design-system-contract:87, and
risk an import cycle. Everything that had to survive, survives —
enterprise.js's `isAuthenticated` short-circuit stays OUTSIDE the shared fetch
(sessions.js has no such guard, so folding them would issue a request where
today none is issued), `force` is threaded through so `Settings.vue`'s explicit
refresh still refetches, and both stores keep their own `featureFlagsLoaded`
flag and public API across all 13 call sites.

Blast radius: every page with a NavBar.

Measured, `acme-sage`: /api/settings/feature-flags 2 -> 1 per page load.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* perf(nav): drop NavBar's duplicate /api/users/me, keep the admin gate closed (#2198)

NavBar fetched the whole user profile on mount to populate `userRole`, which is
used for exactly one thing: `isAdmin`. `auth.js::fetchUserProfile` already
merges the identical response into `authStore.user`, on both session restore
and admin login. In-repo precedent: `MonitoringPanel.vue:278` reads the store
"rather than a duplicate /api/users/me round-trip" (#1109).

The security direction here is the opposite of the obvious one, so it is worth
stating. `initializeAuth()` restores `user` — role included — SYNCHRONOUSLY
from `localStorage['auth0_user']`, which is user-editable. So a naive
`authStore.user?.role === 'admin'` would not fail closed while the profile
loads; it would fail OPEN on a forged value, which is strictly worse than the
independent fetch it replaces.

So this adds `profileVerified` to the auth store — set true only by a
SUCCESSFUL GET /api/users/me, never in the catch, cleared on logout, and never
persisted — and gates `isAdmin` on it. That reproduces exactly today's posture,
where the nav gate only ever reflected a real server response. It stays a
computed, never a read-once, because the store reports `user` before
/api/users/me lands (Library.vue:474) and the nav must become admin reactively
when it arrives.

The gate is cosmetic either way — every admin endpoint is enforced server-side
by `require_admin`, which since #1890 also rejects agent principals — so a
forged role reveals menu items, not data. It is still worth keeping honest.

Measured, `acme-sage`: /api/users/me 2 -> 1 per page load.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(dashboard): stop re-probing an agent that already answered (#2198)

The Agent Detail page spent 3 requests over ~9 SECONDS on every load of a
running agent with no dashboard.yaml, forever. #2130 recorded that same ladder
as what delayed deep-link landing by ~10s. It is the only part of #2198 a user
can actually feel.

Root cause is missing information, not policy. An agent with no dashboard.yaml
replies HTTP 200 with `{"has_dashboard": false, "error": "No dashboard.yaml
found at /home/developer/dashboard.yaml"}` — verified live against `acme-sage`.
An unreachable agent produces `{"has_dashboard": false, "error": <string>}` too.
The two were byte-indistinguishable, so the only safe frontend behaviour was to
assume the transient case and retry at 0s / 3s / 9s.

`GET /api/agent-dashboard/{name}` now carries `settled: true` when the agent ran
its handler and answered, and the retry ladder stops on it.

Three properties worth stating:

  - Derived from the TRANSPORT, not the error text. Only an HTTP 200 with a
    parseable body reaches that line, so it is correct on every already-deployed
    agent image and needs no base-image rebuild — unlike adding a reason code
    agent-side, which would be absent on every existing container.
  - Every inconclusive path stays unsettled. Timeout, connection error, non-200
    and a stopped container all route around it, so a still-booting agent keeps
    its retries. This is the fail-safe direction and it is the load-bearing
    assertion in the tests: a false positive here would permanently hide the
    Dashboard tab of a slow-starting agent, with no retry able to recover it.
  - The frontend treats an ABSENT `settled` as today's behaviour, so an old
    backend with a new bundle simply keeps the ladder.

This supersedes the plan's proposed `/exists` tri-state, which aimed at the same
9 seconds from a worse position: `/exists` reads `agent_dashboard_cache`, which
only ever records POSITIVES (`config_json` is NOT NULL), so persisting "known:
no dashboard" would have required a new column, a dual-track migration
(Invariant #9: SQLite `migrations.py` AND an Alembic revision), and it would
still have paid the full 9s on the FIRST load of every agent because nothing is
cached yet. Fixing it where the information already exists costs no schema
change and removes the 9 seconds on the first load too.

Measured, `acme-sage` (running, no dashboard.yaml), full page load:
  /api/agent-dashboard/{a}  9 -> 1   (was 3 after the probe-dedupe commit)
  /api/agent-dashboard/{a}/exists  3 -> 1

Backend verified by `tests/unit/test_2198_dashboard_settled.py` (7 tests, all
paths). Frontend reader verified end-to-end in the browser by fulfilling the
real backend response with the field merged in, since the local stack's backend
does not yet carry it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(workspace): one viewer-scoped call for the sidebar's thread list (#2198)

`GET /api/enterprise/client-portal/sessions` returns every thread the caller
has, across every agent on their roster.

The Workspace sidebar renders a merged, cross-agent, recency-sorted list, so it
asked the per-agent route once per rostered agent — literally N+1 — from all six
`refreshThreads()` call sites, including every thread open and every completed
turn. Each of those cost 2-3 DB queries, because `list_sessions` re-resolves the
roster through `agent_on_roster` before it touches the session table. This
resolves the roster once and issues one query.

Access boundary made STRUCTURAL, not conventional. `agent_on_roster` did not
call `_roster_rows`; it independently re-queried the same two rosters. Collapsing
N gated reads into one would have left the batch's scope depending on two
functions staying set-equivalent by convention. Both now go through
`roster_agent_names()`, and a test asserts the equality directly rather than
sampling it. `agent_name IN (:agents)` is the tenant scope, not an optimisation:
filtering on `client_email` alone would re-surface threads for an un-shared
agent, which the per-agent gate hides.

`include_owned = principal.is_platform`, tested BOTH ways. Deliberately not
modelled on `search_chats`, which reads only the shared roster and so silently
omits a platform user's own agents — a real separate defect, to be filed, and
inheriting its shape would have put the same hole in the sidebar.

Details that are each a verified trap:
  - `def`, not `async def`, matching `portal_sessions`: pure sync DB work, so
    FastAPI runs it in the threadpool and it cannot block the event loop.
  - `client_email = :email` with the lowercasing python-side at the bind, like
    `list_portal_sessions` — NOT `lower(col) = :email` like
    `search_portal_sessions`, which puts a function on the column.
  - `agent_name` is SELECTed; the per-agent query omits it because the caller
    already knew it.
  - Chunked at 500: an expanding bindparam emits one placeholder per agent and
    SQLITE_MAX_VARIABLE_NUMBER is 999 on SQLite < 3.32, so a large fleet would
    have turned today's always-working N queries into a hard 500 on the
    bootstrap path. Chunking then breaks the global ORDER BY — each chunk is
    sorted independently — so the rows are re-sorted on the same key past the
    threshold. That was caught by its own test, not by review.
  - Empty roster short-circuits before any SQL (the bindparam raises on []).
  - Rate-limited per viewer (`portal_sessions_all:{email}`, 120/60s). There is
    no global limiter middleware, and this becomes the hottest authenticated
    read in the Workspace — no longer even incidentally throttled by the
    browser's per-host connection cap, and in production behind cloudflared
    (HTTP/2) there is no such cap at all.

No cap and no `total`, deliberately: today's per-agent query is unbounded and
runs N times, so this ships the same row volume in one request. Adding a cap
would be a NEW behaviour that collides with the starred-chat pinning guarantee
in requirements §5.10 — a pure recency LIMIT can drop a starred-but-old thread
out of the pinned section. That deserves its own issue, not a side effect here.

No schema change, no migration, no new index. The only index on the table is
(agent_name, client_email, last_message_at), so `client_email = ? AND agent_name
IN (...)` resolves as one index seek per agent with both leading columns on
equality — the same plan each of today's N queries already gets, once instead of
N times over HTTP.

Invariants: #1 (router thin: auth + rate limit + error map), #4 (declared beside
the other viewer-scoped literals; this router has no top-level catch-all), #8
(no agent parameter, so no existence oracle — strictly less enumerable than the
route it replaces), #9 (n/a), #13 (no MCP tool: no client-portal route has one,
and an MCP key cannot hold a PortalPrincipal), #14 (models in
`client_portal/models.py` — the guard globs `routers/*.py` and never sees this
package).

Coordinated with #2196: this touches no function it touches — `get_roster`,
`_agent_briefing`, `_row_to_card` and `_roster_rows` are untouched.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* perf(workspace): sidebar loads its threads in one call, and survives failing (#2198)

`fetchAllSessions` now issues one `GET /client-portal/sessions` instead of one
per rostered agent. Constant in roster size, on all six `refreshThreads()` call
sites — bootstrap, every thread open, every completed turn.

The count is the easy half. Collapsing N calls into one INVERTED a failure mode,
and this commit is mostly about that:

  Before, `fetchAllSessions` could not reject. Every per-agent call carried its
  own `catch { return [] }` — the in-code comment says why, "one down agent
  never blanks the whole list" — and `refreshThreads` `Promise.all`s it while
  only `fetchChatState` was caught. One request cannot degrade per agent, so a
  single 500 would (a) blank a populated sidebar, which design-system-contract
  :43/:55 forbid, and (b) reject out of `bootstrap()` BEFORE `resolveAgentQuery()`
  and the deep-link `sessionId` branch — breaking Workspace deep-link landing
  entirely, on the most client-visible surface in the product.

So: the store catches internally and returns its LAST GOOD list rather than an
empty one, raising `sessionsFailed` for an honest banner; `refreshThreads`
catches both halves as a belt on the bootstrap property. Four tests cover it,
including that a 5xx does NOT fan out (that would turn one failure into N).

Two constraints pinned by existing tests, both preserved: zero GETs on an empty
roster (`workspaceRoomsGate.spec.js` F17b breaks if the batch fires
unconditionally), and every thread carrying `agent_name`, most-recent-first
(`workspaceAgentLanding.spec.js`).

`agent_name` now arrives from the DB row instead of being stamped on client-side
from `this.agents`, so the list is filtered to the DISPLAYED roster. The backend
scopes by the caller's roster — that is the access boundary and it is not
duplicated here. This narrower filter is a rendering rule: a thread whose agent
the sidebar does not show would route nowhere. Today the two sets are identical
so it is a no-op that preserves rendering exactly, and it keeps the sidebar
correct whatever #2196 decides about hiding container-less agents. A drop is
logged in dev, because it means the two rosters have diverged.

TRANSITIONAL: a 404 falls back to the per-agent fan-out, for the deploy-skew
window where a cached bundle reaches a backend without the route. 404 only — a
5xx already degrades correctly above. Delete one release after this ships.

Behaviour change to name rather than let someone discover: today one unreadable
agent degrades alone; with one query the read is all-or-nothing. Acceptable —
it is a single indexed read, not N agent round-trips — but it is a real change
in failure granularity.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(agents): pin the dedupe semantics and the sentinel's consumability (#2198)

Two specs, plus a correction to a claim I made in the primitive's own docstring.

`agentDetailFetchDedupe.spec.js` — behavioural, over Pinia + a mocked axios. The
three semantics that a naive "just cache it" gets wrong: a JOIN returns the
value to every caller (an in-flight SKIP would leave one `undefined`, which is
why `fleetGrid`'s shape was not reusable), two SEQUENTIAL calls still issue two
requests (`waitForAgentStatus` polls `fetchAgent` in a loop and a sticky entry
freezes it forever), and a rejection reaches every joiner while clearing the
entry so the next attempt is not poisoned. Plus `once()`'s extra contract:
answers a later caller from memory, honours `force`, never caches a failure.

`agentDetailMountDedupe.spec.js` — source-structure, in the shape of
`agentDetailDeepLink.spec.js` and the Python AST guards, because there is no
component-mount harness in this project and every property is about statement
ORDER inside a lifecycle hook. The assertion that earns its keep is that
`onActivated` CLEARS the sentinel: a one-way flag passes every request-count
test on a fresh load and silently disables the KeepAlive revisit refresh, which
is a worse bug than the one being fixed. `learnings.md:189` records the same
lesson from #1804 — the transition that gets missed is the one where the before
and after states are equal.

Both suites were mutation-checked rather than assumed. Reverting each fix in
turn fails exactly the guard that owns it: one-way sentinel -> "CONSUMES it";
`!agent.value` gate -> "identity-aware"; hoisting reconcileDeepLinkVisibility
above the guard -> "the skip guards the DATA half only"; dropping running-ness
from the probe key -> "keyed on running-ness"; removing the store join -> "two
concurrent callers issue ONE request".

CORRECTION to `utils/inflight.js`: its docstring claimed no existing precedent
joins an in-flight promise. That was wrong. `src/api.js:71` (`deduplicatedGet`,
PERF-269) is exactly that — same shape, keyed on URL+params, cleared in
`.finally()`. It went unnoticed because the calls in question use raw `axios`
with an explicit `authStore.authHeader` rather than the `api` instance (the
widespread Invariant #7 deviation), so it never applied to them. Moving the
store onto `api` would have been the smaller diff and is rejected for a stated
reason rather than an oversight: `api`'s response interceptor hard-redirects to
`/login` on ANY 401, while AgentDetail deliberately renders its own error banner
and its own 404 panel (#1914). That migration is an Invariant #7 cleanup, not a
request-count fix. The docstring now says all of this.

(Found while writing the tests: the same `api.js` reassignment is why this
spec's axios mock must return a DISTINCT object from `create()`, unlike the
portal specs — otherwise `api.get = …` lands on the shared mock and clobbers
`axios.get`.)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(e2e): assert the page fetches each endpoint once, and still polls (#2198)

Two @smoke specs. `@smoke` is not optional: `frontend-e2e` runs
`test:e2e:smoke` only, so an untagged spec never executes in CI. Even tagged it
cannot block a merge (the workflow is advisory) — which is why the load-bearing
assertions for this issue live in vitest and pytest. These are the end-to-end
confirmation, not the gate.

`agent-not-found.spec.js` gains AC #3: the missing agent is fetched ONCE. It is
the natural home — it already owns a `page.route('**/api/agents/*')` handler
with the URL-shape test that isolates the single-agent GET from `/api/agents`
and `/sync-health` — so the extension is a counter inside a handler that exists.
Its sibling 500 test gains a note: that interceptor now fires once instead of
twice, which is deliberate (the rejection still propagates to every joiner), not
a symptom.

`agent-detail-request-dedupe.spec.js` asserts no agent-scoped endpoint is
fetched twice per mount, with two explicit exemption lists — the pollers, and
the dashboard boot ladder, which may legitimately spend up to 3 requests when
the agent's answer is inconclusive but never one ladder per trigger.

Its second test is the AC #5 guard and is the more interesting one: `/activity`
appears ~4x in a 20s window and looks exactly like the bug being fixed. It is
not. So a future "cleanup" that silences it has to fail here.

Both were checked against unfixed code rather than assumed. Against the
unmodified tree the dedupe test fails naming all eight classes verbatim
(`/api/users/me x2, /api/agents/{a} x2, /api/settings/feature-flags x2,
/exists x3, /playbooks x2, /info x3, /avatar/emotions x2,
/agent-dashboard/{a} x9`) and the AC #5 test PASSES — which is the correct
split for a guard whose job is that correct behaviour stays correct.

Two test defects were found and fixed by that exercise rather than shipped:
  - the activity window ran from `goto`, so it measured load latency as much as
    interval and flaked under parallel workers on a loaded instance. It now
    opens after the agent has rendered.
  - it asserted EVERY gap > 2s, which failed on unfixed code for a 66ms
    start-up burst — real, but incidental timing this change does not control,
    so it would have flaked. It now asserts that at least one gap falls in a
    plausible ~5s band, i.e. that an interval is running.

Pre-existing failures recorded, both verified identical on the unmodified tree
and untouched by this branch: `dashboard-type-filter.spec.js` (1 failed — owned
by #2200, in flight) and the #2199-owned `workspace-absorbs-session.spec.js` /
`continue-as-chat.spec.js` (2 failed, 3 passed — the missing `testfix` fixture).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: record the request-dedupe changes in the flows they belong to (#2198)

Tiered per Rule of Engagement #4, and decided at plan time rather than derived
after the fact.

`feature-flows/dynamic-dashboards.md` — the flow that owns the dashboard probe
and its retry ladder. Its Data Flow steps 1 and 2 both became wrong: the
visibility check now joins ONE probe across its four triggers, and the ladder
stops on a `settled` answer. Both entries say WHY the obvious simpler shape does
not work — a store-level in-flight join cannot collapse triggers that fire
hundreds of ms apart, and the probe key has to carry running-ness or a
slow-starting agent loses its Dashboard tab permanently. Also disambiguates the
two same-named `checkDashboardExists` functions (component vs store).

`feature-flows/agent-overview-dashboard.md` — its ASCII call diagram named
`GET /api/agents/{name}/info` inside `loadSidecars()`. That call now resolves
through the store, which is the whole reason the duplicate collapsed.

`feature-flows/workspace-sidebar-ia.md` — a new step 0 for how the list is
loaded at all, which the doc never covered. Records the three load-bearing
properties (the roster set is the tenant scope; the batch must not become a
single point of failure; the client-side filter is a rendering rule, not a
second access check), the deliberate absence of a cap, and the two honest
downsides: the change in failure granularity, and the transitional 404 fallback.

`architecture.md` Workspace block — the API change, in the prose form that block
uses (client-portal routes are not in the endpoint tables).

`requirements/core-agent.md` §5.10 — the Endpoints bullet gains the new route.
Additive; §5.10's behaviour is unchanged.

No requirements change beyond that bullet: behaviour is the same, cost is not.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(app): correct the KeepAlive rationale, drop a dead include entry (#2198)

The C3 investigation's artifact. #2198's plan escalated a question to the human:
should AgentDetail be KeepAlive'd at all? Six of the eight duplicate classes
were attributed to it, and its stated justification — "preserves terminal
WebSocket connections" — refers to a tab that is deprecated and hidden. The
answer was to investigate first, then decide.

DECISION: it stays. The justification was stale; the behaviour is not.

Verified stale: the Terminal tab is commented out of `visibleTabs`,
`TerminalPanelContent` is imported by `AgentDetail.vue` and never rendered
anywhere in its template, and `terminalRef` is bound to nothing. There is no
terminal WebSocket to preserve.

Verified live, and each of these would have broken:

  - `e2e/schedules-toggle-scroll.spec.js:203-212` names this caching as a
    "PREMISE (load-bearing)" in its own words: had AgentDetail remounted, its
    T4/T5 "would pass even with the watcher-clear and loadSeq guard deleted".
    Removing the include does not fail that spec — it silently converts two
    shipped regression tests into tautologies, which is worse than a red test
    and invisible to every metric.
  - `ChatPanel.onUnmounted` calls `closeSSE()` and stops an active voice
    session. ChatPanel is `v-show`, so it is mounted on every tab and today
    survives navigation. Un-caching makes navigating away kill an in-flight chat
    stream and end a live voice call.
  - `activeTab` is a local ref that is never URL-synced, so every revisit would
    reset the user to Overview.

And the premise itself did not hold. Measured on `acme-sage` (running, no
dashboard.yaml), same-document revisit via SPA push + history.back():

                        page load    revisit
    KeepAlive ON             65         27
    KeepAlive OFF            57         47

It removes 2 of the 8 duplicate classes, not 6 — classes 6-8 (feature-flags,
users/me, playbooks) never involved KeepAlive at all, and 3-5 are driven by the
route and status watchers, which fire either way. So it buys 6 requests once and
costs 19 on every revisit, and `learnings.md:118-120` records the cached-revisit
path as "the common path". The duplicates are fixed at their sources instead.

Two changes here, both no-ops at runtime:
  - the comment now says what is actually true, and why, so the next reader does
    not have to re-derive it;
  - `'SystemAgent'` leaves the include list. It matches no component anywhere in
    `src/` (verified by grep — the only occurrence was this line), because
    `/system-agent` redirects to `/agents/trinity-system`, i.e. to AgentDetail.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(portal): agent-scoped keys can no longer traverse the Workspace as their owner (#2198)

Plan §12.5 E7, answered rather than shipped silent. get_portal_principal's
platform branch resolves the caller through get_current_user, which resolves an
agent-scoped MCP key to its OWNER carrying the owner's role (the ent#293/#297
trap). Any agent's injected TRINITY_MCP_API_KEY therefore reached all 30 portal
routes as is_platform=True — a REST path around the MCP layer's agent-to-agent
permission matrix (it could read the owner's threads with agents the calling
agent holds no agent_permissions edge to) — and the new batch route amplified
exfiltration from N calls against N discovered names to ONE call returning the
owner's whole cross-agent thread index.

Fixed at the dependency, not the route, so every current and future portal
route inherits it. reject_agent_principal, deliberately not the stricter
reject_non_interactive_principal: the portal is a *use* surface, so a user's
own user-scoped key scripting their own Workspace stays legitimate, and
scope='system' keeps platform breadth by design. Connector and portal_delegate
keys were already fenced to their own routes inside get_current_user. There is
no legitimate agent caller to break: no MCP tool targets this surface and
neither agent images nor the base image call it (verified by grep).

Tests: agent-scoped principal → 403 at the boundary; a user-scoped key and a
JWT still pass as platform; a portal session token never touches the fence.
All 306 portal-adjacent unit tests stay green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: trinity-ability <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
vybe pushed a commit that referenced this pull request Aug 20, 2026
…h/7d limit spend, colour-banded (Abilityai/trinity-enterprise#259) (#2327)

* feat(dashboard): Subscription pressure grid tile — per-subscription 5h/7d limit spend, colour-banded (Abilityai/trinity-enterprise#259)

One row per SUBSCRIPTION on the Grid: how much of each rolling limit is
spent, colour-banded, with 429 history and honest degradation. The inverse
unit of #471's per-agent chip, which cannot say WHICH subscription is the
bottleneck — agents share a subscription and burn one 5h window together, so
reading it off the board otherwise means grouping every agent chip by eye.

ZERO backend change, per the operator ruling on the issue (2026-08-19): "a
small build on GET /api/agents/subscription-pressure + the extended
GET /api/subscriptions/{id}/usage once #471 merges". A batched admin endpoint
was built first, then reverted — at the real fleet size it optimizes ~0.5 q/s,
and `assert_admin` rejects agent principals (#1890) so ent#351 could not have
reused it anyway.

What a row may claim (all pinned in utils/subscriptionPressureTile.js):
- Both limits, each on its own band (green <60, amber <85, red >=85), shown
  ONLY while the provider snapshot is fresh. #471 made the number real, so
  the AC's "never a fake-precise X% left" governs FRAMING — utilization
  consumed, source-labelled — not disclosure. Labelled 5h/7d, never
  daily/weekly: rolling windows with a visible resets_at.
- A red window raises severity to `warn` even with a clean failure history —
  the only signal before the first 429; the chip separates `429s` (happened)
  from `near` (has not). Sort ranks on the FULLEST window.
- "429s" counts the rate_limit kind alone, never failure_events_24h, which
  also carries auth + pre-#471 unknown rows — the conflation migration 0040
  exists to fix.
- input_tokens stays OFF the row face: it is SUM(context_used), context-window
  occupancy rather than tokens consumed — the ruling architecture.md already
  records for the sibling ent#101 tile. It appears in the tooltip, labelled.
- Cost is always API-equivalent, never a bill.

Honest status: empty requires a fetch that SUCCEEDED and returned zero; a
wrong-shaped 200 is a FAULT, not an empty fleet (laundering it would tell an
operator their subscriptions are not configured); a poll failing after a good
one keeps its rows and marks the stamp stale; a failed per-subscription read
renders that row unavailable, never as zeroes. Overflow is disclosed via a
"+N more" row and a "3 of 9" stamp — past the fixed track count a row is
clipped by InfoTile's overflow:hidden with no trace.

First adminOnly tile, and load-bearing rather than cosmetic: every endpoint it
reads is admin-gated and its footer link targets an admin-only route, so the
flag doubles as the fetch gate (no 403 loop) — with a key-appearance watch,
because isAdmin is only confirmed once fetchUserProfile lands.

73 new unit tests (1037 total green). Verified against the live local stack:
real Anthropic headroom (5h 15% / 7d 10%) rendering in both themes.

Fixes Abilityai/trinity-enterprise#259

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(dashboard): small colour-coded limit bars on the subscription tile (Abilityai/trinity-enterprise#259)

Two bars per subscription — 5h and 7d — beside the percentages, each on the
same green/amber/red band. The bar is a second glanceable channel, not a
replacement for the number: colour still rides the percentage text, the row
still carries a severity chip, and each window is `role="img"` with an
aria-label spelling the reading out, so nothing depends on colour alone.

Fill width is `fill` (clamped 0-100 by `barWidthPct`), never `pct`. An overage
plan really does report over 100%, and an unclamped `width: 137%` overruns its
track and shoves the row sideways inside a body that is `overflow: hidden` —
content gone with no trace. The NUMBER stays unclamped, so an overage is still
reported honestly; only the geometry is bounded.

Track width is fixed (30x4px) rather than content-sized, so the two windows
line up into columns down the tile. Only `width` transitions, over 320ms —
a bar that springs on every 60s poll reads as activity that did not happen;
`prefers-reduced-motion` drops it.

Measured at 1:1 rather than assumed: meta fits inside the tile body on every
row, and the worst case (a 33-char name) ellipsizes the NAME to 93px — the
TileRowList contract, with the full name in the row tooltip — while the
readings keep their width. Nothing overflows.

1041 unit tests green (4 new for the clamp, incl. the >100% overage case).

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: trinity-ability <[email protected]>
vybe pushed a commit that referenced this pull request Aug 20, 2026
…tilization trends (Abilityai/trinity-enterprise#433) (#2331)

#471 shipped the live headroom probe but keeps exactly ONE last-known-good
Redis snapshot per subscription, overwritten on every probe — so "how close
did we run to the 5h wall this week" was structurally unanswerable. This adds
the durable half.

New `subscription_headroom_history` table (dual-track: schema.py + tables.py +
SQLite `subscription_headroom_history_table` + Alembic 0041), written from
`_probe_and_store` — the single chokepoint every probe passes through, so the
hook inherits #471's whole rate-bounding envelope (60s floor, single-flight,
fail-closed ambient) and **adds no probe**. Probe cadence and spend are
unchanged, which the issue requires.

Three load-bearing write properties:
- **Off the event loop** (`asyncio.to_thread`). The DB is DELETE-journal with a
  30s busy timeout; a sync write landing during the 03:30 backup or the 04:30
  VACUUM would stall /health, the WS dispatcher and every in-flight request.
  try/except handles errors, not blocking.
- **After** the Redis write — the snapshot is what every live surface reads.
  Order pinned by test, since a refactor could invert it silently.
- `except Exception`, never `BaseException`: shutdown's CancelledError must
  keep propagating.

The series is `last`-per-bucket, never `max`, for three independent reasons:
probes are demand-driven so E[max of n] rises with operator attention (the
unattended overnight burn reads LOWEST — the bias runs the wrong way twice);
5h and 7d peak at different instants so a two-column max has no single owning
row; and a 429 carries a window status with NULL utilization, which a max drops
exactly when it matters most. Selection is ROW_NUMBER() OVER (PARTITION BY
bucket ORDER BY fetched_at DESC) — a bare non-aggregated column beside an
aggregate is a SQLite-only extension that raises GroupingError on PostgreSQL,
pinned here by compiling for the PG dialect (the PG matrix is opt-in).

Honest gaps need TWO timestamps. Real timestamps alone cannot separate jitter
from a gap (10:05→11:55 is 1h50m with NO gap; 10:55→12:05 is 1h10m WITH one),
so every bucket carries the logical `bucket_start` beside the real
`fetched_at`; absent buckets stay absent, nothing is interpolated, and
`coverage_pct` lets a thin series report itself as thin.

Failed probes persist as status-only rows (else a dead token for three days is
byte-identical to nobody-watching). `no_windows` classifies the reachable
ok-with-no-windows case history-locally so it cannot look like a botched write.
A probe that never RAN records nothing — a gap has three causes, documented.

DELIBERATE SCOPE EXPANSION (operator-approved, not accidental — see below):
this also converts `subscription_rate_limit_events`' HARDCODED 24h sweep into a
real retention window. That table held the platform's only durable record of
real agent work hitting a provider rate limit — timestamped, attributed to the
causing agent — and destroyed it daily with no operator-visible window, no
#1644 blast-radius guard, and no GET /api/settings/retention entry, while every
sibling table had all three. Widening 1d → 30d is the #1638-SAFE direction: no
install loses data, and it changes no existing answer because every consumer
already time-filters.

Both windows: registered in RETENTION_OPS_KEYS, range-validated, exactly one
_guard_allows site each, count and prune sharing one predicate by construction,
excluded from COMMUNITY_FRESH_INSTALL_SEED (the 5d floor would truncate the 7d
default read window while the UI labelled it 7 days).

Alembic 0041 declares NO foreign key. `_PG_TABLE_SUBS` strips every FK clause
before DDL reaches PostgreSQL, so the platform has zero enforced FKs; adding
one would create the first and diverge the backends on the in-flight-probe
delete race. Cascade is explicit inside delete_subscription's transaction.

New GET /api/subscriptions/{id}/headroom/history?window=24h|7d|30d — admin
(which also rejects agent principals, #1890), id-OR-name + 404 parity with
/usage, 422 on an unknown window (the axis must not be silently redrawn),
read-only so viewing a trend costs no subscription quota.

Backend only. The viable ent#259 consumer is an in-tile sparkline, not a
labelled chart — FleetGrid v1 pins every tile to one cell, the body is
overflow:hidden with no scroll, and its row list silently drops past 4.

OSS-core by explicit decision (the #471 gate ruling carries over), recorded in
requirements §20.5b so it is never inferred backwards from the merge.

Four pre-existing tests updated, all characterizations of the old behaviour:
test_subscription_auto_switch_pingpong asserted the hardcoded 24h sweep (that
assertion documented the defect, not a contract); test_297 pinned
len(RETENTION_OPS_KEYS)==9; test_1834 counted alarms across the whole cycle and
is now scoped to its own window; test_cleanup_inner_sweeps needed the new prune
return values in its mock harness.

41 new tests. Full unit suite: 11,935 passed.

Fixes Abilityai/trinity-enterprise#433

Co-authored-by: trinity-ability <[email protected]>
dolho added a commit that referenced this pull request Aug 20, 2026
…absence (ent#443)

Four review findings from the #2355 re-review, none blocking, all cheap.

1. The docs half of the move was incomplete. The PR corrected three lines and
left nine, including the feature's own page opening with "**Enterprise
feature.**" and a sentence in `sharing-access-and-monetization.md` eight lines
below the one it fixed. Since the stated motivation was that the published
guide had drifted ahead of the code, a half-corrected guide is the same defect
with a smaller radius. Six files updated; the only surviving mentions of
"enterprise" beside rooms now say it *used to be* one.

Two of those lines were stale twice over: `faq/collaboration.md` and
`guides/using-trinity.md` both described reaching rooms through a **Sessions**
view that ent#381 retired. Rooms open from the Workspace by @mentioning a
second agent, which is what they now say.

2. `rooms.ts` treated any 403 or 404 as "shared sessions are not enabled on
this instance". That was true while the module was entitled — an unentitled
403 really did mean absent — and ent#443 makes it false: the rooms module
authors 403 for an agent the caller may not reach, and a deliberately uniform
404 for a room it is not a member of. Both were being reported to the agent as
a switched-off feature.

The status alone cannot answer the question, so the discriminator is now the
shape of `detail`: the serving module authors `{code, message}`, absence is a
plain string (FastAPI's own "Not Found", or an older build's entitlement
sentence). That is the rule the Workspace already follows for the same
distinction (#2128) — this is the MCP surface catching up. Everything
unrecognised still degrades to the friendly result, so the default is
unchanged. `ApiError` retains the raw body for it rather than having callers
regex the message, and a non-ApiError keeps the old string test.

Seven cases pinned in `rooms-availability.test.ts`, including the coded-404
one, which is the case a status-only rule gets wrong most often.

3. The new COPY parity guard keyed on `main.py`'s imports, so a package pulled
in only transitively would still die at import. Every non-exempt package under
`src/backend/` is copied today, so asserting that directly is free and closes
it; `_EXEMPT` stays as the escape hatch.

4. `router.py`'s gate comment, which this PR rewrote from "Triple-gated" to
"Double-gated", kept claiming `require_admin` alone would admit an agent.
#1890 / ent#297 moved that rejection into the gate itself. The code is right —
`reject_agent_principal` is belt-and-braces — but a rationale this repo treats
as load-bearing should not assert something the gate stopped doing.

Tests: 511 passed, 1 skipped (`-k "ent443 or 2128 or parity or schema or
alembic"`); MCP server 161/161.

Related to ent#443.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
vybe pushed a commit that referenced this pull request Aug 21, 2026
* refactor(rooms): move multi-agent rooms into OSS core (ent#443)

Rooms were the entitled `shared_sessions` module, 404ing in community builds —
while the frontend that drives them (`components/rooms/`, `stores/rooms.js`, the
ent#392 composer typeahead) and the MCP tools (`tools/rooms.ts`) shipped in EVERY
build and self-disabled. Three of four surfaces were already public, so gating
only the backend left an OSS install rendering an affordance it then refused.
Workspace itself moved for the same adoption reason (ent#356); rooms are the half
that makes it the place people work with agents rather than a second 1:1 chat.

The public docs had already drifted ahead of the code: the Workspace guide
presents `@`-mention → room as the ordinary continuation of a 1:1, while the FAQ
called multi-agent chat "an enterprise capability". Both are live on
docs.ability.ai; this makes the guide true and corrects the FAQ.

Engine ported VERBATIM — mention-wake turn-taking, per-room budgets, chain depth,
wake caps, the ent#218 overshoot rule and the ent#220 cancellation shield are
unchanged. A port that also fixes things is a port nobody can review.

Adoption, not creation:
* DDL to `db/schema.py` + `db/tables.py`, versioned on the OSS two-track runner
  (`shared_sessions_tables_to_oss` + Alembic `0042_shared_sessions_oss`). Both
  tracks are CREATE TABLE IF NOT EXISTS, so the migration is a NO-OP on every
  entitled install — no data migration, no lost transcripts.
* Table names keep the `enterprise_` prefix. Renaming them IS the data migration
  this forbids; the prefix is provenance, not a licensing claim (ent#356).
* The enterprise Alembic `0011_shared_sessions` stays on its own line — `0012`
  revises it, and deleting an applied revision is a PG boot failure (ent#431).

One deliberate behaviour change, and it fixes a latent bug the move surfaced:
`participants.identity` / `messages.sender_identity` are now in AGENT_REFS, so a
rename re-keys and a purge cascades. Before this, rooms sat outside the registry
(it covers OSS tables), so a renamed agent silently stopped being woken — its
participant row still named the old agent, which is what mention resolution
matches against — and a purge orphaned participants and transcript. Both columns
are POLYMORPHIC, so each ref carries a `kind` predicate: unscoped, a rename would
rewrite (and a purge DELETE) a human participant whose user id or verified email
happened to equal the agent's name. The forward parity regex cannot see either
column, so `test_agent_cleanup_parity` gains a documented
`_POLYMORPHIC_AGENT_COLUMNS` set for the backward direction and
`test_ent443_rooms_oss_core` pins the predicates explicitly.

Transition safety: the OSS routers are included BEFORE `register_enterprise(app)`,
so on an install whose submodule is not yet bumped both mount and the ungated OSS
one wins the match order. Pinned by test, source-asserted so a reorder fails loudly.

`multi_agent_chat_available` is now unconditionally true but STAYS on the roster:
it is the portal's only capability channel (#2128) — a portal principal cannot
read `/api/settings/feature-flags` — and the shipped bundle gates the picker, five
room store actions and `/workspace/r/:roomId` on it, so deleting it would hide the
feature this move exposes.

Tests: five suites ported verbatim (94 pass), `test_2128` rewritten around the new
unconditional answer, new `test_ent443_rooms_oss_core.py` (16) covering mount,
ungated first-match, no feature-id registration, both migration tracks, and the
kind-scoped rename contract.

Companion PR in trinity-enterprise deletes the module; the submodule bump follows
its merge.

Related to ent#443. Blocks ent#442.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* ci(guard): exempt the three room tables the OSS move adopted (ent#443)

`enterprise-docs-guard` failed on the architecture.md section documenting the
move: the pattern forbids `enterprise_[a-z_]+` in public docs, and naming
`enterprise_rooms` / `enterprise_room_participants` / `enterprise_room_messages`
reads as a private-schema disclosure.

It isn't one any more, and the guard already carries this exact carve-out for
ent#356's portal tables: those names moved onto the OSS track and their
`enterprise_` prefix is retained history, because renaming them would be a data
migration on every existing install. The room tables are the same case one
module later, so they join the same allowlist with the same stated reason.

Listed one by one rather than as a `room` prefix. The exemption should cover the
three tables that actually moved — a future private `enterprise_room_*` table
must still trip the guard, and it does (verified: `enterprise_room_secrets` still
matches, `enterprise_rooms` no longer does).

Related to ent#443.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(docker): ship shared_sessions in the prod image, and guard the COPY list (ent#443)

`prod-image-smoke` failed:

    File "/app/main.py", line 128, in <module>
      from shared_sessions.router import budget_router as room_budget_router
    ModuleNotFoundError: No module named 'shared_sessions'

The backend Dockerfile globs top-level MODULES (`COPY src/backend/*.py` — #1033's
fix, after redis_breaker_util.py crash-looped the backend) but enumerates
PACKAGES one COPY line at a time. So a new package builds a clean image that
dies at import. The `client_portal` COPY line carries a comment predicting
exactly this; ent#443 is the prediction coming true one module later.

Two changes:

* the missing `COPY ../../src/backend/shared_sessions /app/shared_sessions/`;
* a source-level parity guard, because the only thing standing between this
  class of bug and production was a job that builds the entire image and reports
  a runtime crash. `test_ent443_backend_package_copy_parity` parses main.py's
  module-scope imports and the Dockerfile's COPY lines and fails in
  milliseconds, naming the exact line to add. Verified by deleting the COPY and
  watching it go red — a guard that has never been seen failing is a guess.

It does NOT replace prod-image-smoke: that job proves the image boots, which no
static check can. This only proves the COPY list has not fallen behind the
import list. `enterprise` is exempt (optional submodule, guarded import).

Related to ent#443.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(rename): teach the #1819 seeder about kind-scoped AGENT_REFS (ent#443)

`regression diff` caught this: `test_rename_rekeys_every_registered_table`
failed under HEAD and not under BASE, and it is a HARNESS gap, not a rename bug.

The test seeds one row per AGENT_REFS entry, renames, and asserts nothing is
left behind. ent#443 registered the room tables with a predicate — the
`identity` / `sender_identity` columns are POLYMORPHIC, so each ref carries
`kind = 'agent'` to keep a rename off a human participant whose user id or
verified email happens to equal the agent's name. A seeded row that does not
satisfy that predicate is skipped BY DESIGN, and then reported as a strand the
seeder itself caused.

The harness already knew about this shape: it hard-coded `scope = "agent"` for
the scope-filtered `mcp_api_keys` refs, with a comment saying a synthetic value
"matches no filter, which would look like a strand when it is really this
seeder's fault". That special case is now generalized — `_filter_values` parses
any ref's `extra_filter` and seeds the columns it requires — so the next filtered
ref is covered without touching this file again.

Behaviour is unchanged and was never wrong: `test_ent443_rooms_oss_core` proves
a rename re-keys the agent participant and leaves the `user` and
`workspace_user` rows (seeded with colliding identities) untouched.

Related to ent#443.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(migrations): renumber the room revision to 0044 and pin the hotfix line (ent#443)

Review finding 2: `0039_shared_sessions_oss` shared a numeric prefix with
`dev`'s `0039_operator_queue_addressed_to`, and both chain off
`0038_portal_chat_state`.

The fork itself is not the defect — it is forced. This PR is a hotfix onto
`main`, whose Alembic head IS `0038_portal_chat_state`; 0039-0043 exist only on
`dev`, so chaining off `dev`'s head would name a revision `main` does not have
and fail boot on the line this ships to. `main` must resolve to one head, and it
does: verified with the repo's own guard (40 revisions, 1 head) and with a real
`alembic upgrade head` against PostgreSQL 16 from a narrow (VARCHAR(32))
`alembic_version`, reaching `0044_shared_sessions_oss` with the column widened
to 255. A downgrade leaves all three room tables in place and the re-upgrade
over pre-existing tables is a clean no-op — the adoption contract, exercised.

So what is fixed here is the part that was avoidable: the duplicated numeric
prefix, and the fact that the back-merge obligation lived nowhere.

- Renumbered to `0044_shared_sessions_oss` (parent unchanged, still 0038) so the
  filename does not collide with `dev`'s 0039 after the back-merge. Revision ids
  are strings, but the numeric prefix is the graph's only human ordering cue,
  and a duplicate would be the first in the repo — on exactly the graph whose
  failure mode is invisible to git.
- Documented in the revision docstring, architecture.md and a new test: the
  back-merge MUST add an `alembic merge` revision with
  `down_revision = ("0043_subscription_headroom_history",
  "0044_shared_sessions_oss")`. It cannot be added here — it would name
  revisions `main` does not carry. `check_alembic_heads` fails that PR loudly
  until it exists; the fix there is the merge revision, never renumbering a
  revision already applied wherever the hotfix went.
- `test_the_room_revision_chains_off_the_hotfix_line_and_numbers_uniquely`
  asserts the parent is 0038 and that no two revision files share a prefix.

Simulated the back-merge to prove both halves rather than assert them: dev's
`versions/` plus this file fails the guard at exactly `0038_portal_chat_state`,
and adding the prescribed merge revision collapses it to one head.

Suites: test_ent443_rooms_oss_core (17 pass), and the
`-k "schema or alembic or parity or migration"` sweep (562 pass, 1 skip).

Related to ent#443.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(learnings): capture the Dockerfile package-COPY and hotfix-Alembic-fork classes (ent#443)

Two entries from the #2355 re-review, both third-or-later occurrences.

The COPY class has now bitten three times — #1033 (a module, fixed by the
`*.py` glob), ent#356 (`client_portal`), ent#443 (`shared_sessions`) — and is
invisible to every source-only check by construction, because the source tree
always has the directory. #2355 added the static parity guard; the entry records
why the guard needs an anti-vacuity anchor and where it is still blind
(transitive imports).

The Alembic entry records the shape a hotfix migration takes: the single-head
guard is green on BOTH branches while the graph is forked, because the fork only
exists in the relationship between them. It names the four things that make it
safe — chain off the branch you ship to, number past the other branch's head,
simulate the merge with the repo's own guard, and exercise an adoption revision
by downgrading and re-upgrading over existing tables.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(rooms): finish the docs half, and stop reporting a refusal as an absence (ent#443)

Four review findings from the #2355 re-review, none blocking, all cheap.

1. The docs half of the move was incomplete. The PR corrected three lines and
left nine, including the feature's own page opening with "**Enterprise
feature.**" and a sentence in `sharing-access-and-monetization.md` eight lines
below the one it fixed. Since the stated motivation was that the published
guide had drifted ahead of the code, a half-corrected guide is the same defect
with a smaller radius. Six files updated; the only surviving mentions of
"enterprise" beside rooms now say it *used to be* one.

Two of those lines were stale twice over: `faq/collaboration.md` and
`guides/using-trinity.md` both described reaching rooms through a **Sessions**
view that ent#381 retired. Rooms open from the Workspace by @mentioning a
second agent, which is what they now say.

2. `rooms.ts` treated any 403 or 404 as "shared sessions are not enabled on
this instance". That was true while the module was entitled — an unentitled
403 really did mean absent — and ent#443 makes it false: the rooms module
authors 403 for an agent the caller may not reach, and a deliberately uniform
404 for a room it is not a member of. Both were being reported to the agent as
a switched-off feature.

The status alone cannot answer the question, so the discriminator is now the
shape of `detail`: the serving module authors `{code, message}`, absence is a
plain string (FastAPI's own "Not Found", or an older build's entitlement
sentence). That is the rule the Workspace already follows for the same
distinction (#2128) — this is the MCP surface catching up. Everything
unrecognised still degrades to the friendly result, so the default is
unchanged. `ApiError` retains the raw body for it rather than having callers
regex the message, and a non-ApiError keeps the old string test.

Seven cases pinned in `rooms-availability.test.ts`, including the coded-404
one, which is the case a status-only rule gets wrong most often.

3. The new COPY parity guard keyed on `main.py`'s imports, so a package pulled
in only transitively would still die at import. Every non-exempt package under
`src/backend/` is copied today, so asserting that directly is free and closes
it; `_EXEMPT` stays as the escape hatch.

4. `router.py`'s gate comment, which this PR rewrote from "Triple-gated" to
"Double-gated", kept claiming `require_admin` alone would admit an agent.
#1890 / ent#297 moved that rejection into the gate itself. The code is right —
`reject_agent_principal` is belt-and-braces — but a rationale this repo treats
as load-bearing should not assert something the gate stopped doing.

Tests: 511 passed, 1 skipped (`-k "ent443 or 2128 or parity or schema or
alembic"`); MCP server 161/161.

Related to ent#443.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 28, 2026
…uire_role

Review found the agent-principal test tautological: it asserted
`"reject_agent_principal" in inspect.getsource(require_role)` and passed
because `getsource` returns the DOCSTRING, which contains the sentence
"Deliberately does NOT call `reject_agent_principal`". The assertion matched
its own refutation.

`require_role` rejects CONNECTOR principals only, and that omission is
deliberate — `require_role("creator")` on `POST /api/agents` is what makes
ent#69 Part 2 agent-spawned creation work. It is not touched here.

The decision the reviewer asked for: human-only is correct, because it closes
a BYPASS rather than merely widening a gate. `POST /agents/{name}/start`,
`/stop` and `/delete` each call `enforce_agent_spawn_scope`, so an agent-scoped
caller may only start or stop agents it actually SPAWNED (name *and* key id).
`restart_system` loops every member calling `container_stop` +
`start_agent_internal` with no per-member check at all — so reaching it with an
agent key performs, in bulk and unscoped, exactly the operation that is
spawn-scoped one at a time. On a default admin-owned install an agent key
resolves to its owner carrying the owner's role, so `require_role("creator")`
alone admits the whole fleet (trinity-ops-agent#232 class).

Scoping per member was considered and rejected: a system whose every member the
caller spawned is a near-empty set, so it would be a strange capability rather
than a useful one. If an agent-driven restart is ever wanted it needs its own
design.

- `restart_system` calls `reject_agent_principal` explicitly, above the `try`
- docstring + `docs/memory/feature-flows/system-manifest.md` state the real
  reason; both previously carried the false "require_role also rejects agent
  principals since #1890"
- the tautological test is replaced by three real ones: `require_role` does NOT
  reject agent principals (the false premise pinned as its opposite, read
  through `_code_only`), `restart_system` refuses an agent principal BEFORE
  touching anything (driven for real, with `get_accessible_agents` stubbed to
  raise so a late refusal fails loudly), and a human creator is still admitted
  (so the guard is about principal KIND, not role). Mutation-checked: removing
  the guard turns the last two red.
- export: `set(member_names)` was rebuilt per row inside a comprehension, and
  the sibling branch held a redundant `_member_set` copy — `member_names` is
  already a set, so both branches now read it directly
- MCP `restart_system` description carries the tightened gate and the tag-first
  membership resolution, so an agent caller's 403 is legible

Behaviour changes (release-note material):
- `POST /api/systems/{name}/restart` now requires the `creator` role and a
  human caller. Previously bare `get_current_user`. Agent-scoped MCP keys get
  403.
- `GET /api/systems/{name}/manifest` no longer exports `trinity_prompt`.

Related to #2373

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 28, 2026
… an ungated restart, a broken export round-trip, and prefix-collision membership (#2373)

The deploy half has been hardened by every commit since ent#124; the four
post-deploy endpoints were essentially untouched since 2025.

## Membership is now ONE predicate

`get_system`, `restart_system` and `export_manifest` each matched
`startswith(f"{system_name}-")`, so an operation on `acme` also captured every
agent of a system named `acme-extra` — including `restart`, which stops and
starts containers. Three copies of a wrong rule.

`system_service.system_member_names` is the one rule, and it prefers TAGS:
`configure_tags` already applies the system name to every member, so a tag is a
RECORD of membership where a prefix is an inference from a naming convention.
The prefix survives only as a fallback for pre-tag deployments, narrowed so an
agent claimed by another system's own tag is excluded — a tagged `acme-extra`
agent is never captured by `acme` even there. A failing tag read degrades to the
prefix rather than 500ing.

Residual, stated rather than hidden: two systems deployed BEFORE tagging where
one name is a prefix of the other remain ambiguous, because nothing distinguishes
them. This is also the prerequisite for the teardown verb, where the same
collision would delete rather than restart.

## GET /{name} returns real schedules

It called `db.get_agent_schedules`, which does not exist — the facade exposes
`list_agent_schedules` and `database.py` deliberately has no `__getattr__`
fallback. The AttributeError was swallowed by the surrounding `except
Exception`, so every response omitted `schedules` for every agent and logged one
warning each, while `tests/test_systems.py` never asserted on the key. Exactly
the failure mode the db facade's own comment warns about — so the test also pins
that the fallback stays absent, since adding one would turn the next typo into a
silent Mock.

## POST /{name}/restart is creator-gated

It was bare `get_current_user` — below `POST /deploy` and below even the
READ-ONLY bundled-catalog routes — so any authenticated principal, including
`role: user`, could stop and start every container in a system whose agents it
could see. A mutating fleet-wide verb under a lighter gate than the catalog it
reads is an oversight, not a decision. `require_role` also rejects agent
principals (#1890), which matters because an agent-scoped MCP key resolves to
its owner carrying the owner's role.

## Export round-trips

The non-full-mesh permissions branch sliced `target_agent[len(name)+1:]` with no
membership filter — the sibling branch had one — so an edge pointing outside the
system exported as a blind-sliced garbage short name that then failed
`validate_manifest`'s unknown-agent check on re-deploy. The export broke its own
round trip. Both branches now test membership.

And the export no longer embeds the instance-global `trinity_prompt` as the
manifest's `prompt:`. Deploying that manifest elsewhere overwrote THAT
instance's platform-wide prompt — a fleet-wide side effect from what reads like
a copy of one system. Nothing records whether the source system ever set a
prompt, so there is no honest way to distinguish it from whatever the instance
happens to have configured, and the only correct export of an unknown is to
omit it.

## Two preview hardenings

Unknown PER-AGENT keys now warn like top-level ones (ent#126): `credentials:`,
`skills:` and `display_label:` are the fields people try first and they vanished
in silence.

Preview and deploy now resolve the identical resource default. Deploy hardcoded
`{"cpu": "2", "memory": "4g"}` while `_preflight_template` validated against the
admin-configurable `get_agent_default_resources()`, so the two disagreed the
moment an admin moved the fleet default — the one spot that escaped ent#126's
pure-resolver no-drift pattern.

## Verification

14 unit tests, one per defect plus the exempt shapes. Two mutation-checked: the
restart gate and the tag-first membership each turn a test red when reverted.
414 pass across the system/manifest/ent#126/#1884 suites.

`tests/test_systems.py` is live-backend tier and cannot run without a stack —
which is part of why these survived — so the coverage added here is unit-tier,
where the per-PR gate can see it.

Closes #2373

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 28, 2026
…uire_role

Review found the agent-principal test tautological: it asserted
`"reject_agent_principal" in inspect.getsource(require_role)` and passed
because `getsource` returns the DOCSTRING, which contains the sentence
"Deliberately does NOT call `reject_agent_principal`". The assertion matched
its own refutation.

`require_role` rejects CONNECTOR principals only, and that omission is
deliberate — `require_role("creator")` on `POST /api/agents` is what makes
ent#69 Part 2 agent-spawned creation work. It is not touched here.

The decision the reviewer asked for: human-only is correct, because it closes
a BYPASS rather than merely widening a gate. `POST /agents/{name}/start`,
`/stop` and `/delete` each call `enforce_agent_spawn_scope`, so an agent-scoped
caller may only start or stop agents it actually SPAWNED (name *and* key id).
`restart_system` loops every member calling `container_stop` +
`start_agent_internal` with no per-member check at all — so reaching it with an
agent key performs, in bulk and unscoped, exactly the operation that is
spawn-scoped one at a time. On a default admin-owned install an agent key
resolves to its owner carrying the owner's role, so `require_role("creator")`
alone admits the whole fleet (trinity-ops-agent#232 class).

Scoping per member was considered and rejected: a system whose every member the
caller spawned is a near-empty set, so it would be a strange capability rather
than a useful one. If an agent-driven restart is ever wanted it needs its own
design.

- `restart_system` calls `reject_agent_principal` explicitly, above the `try`
- docstring + `docs/memory/feature-flows/system-manifest.md` state the real
  reason; both previously carried the false "require_role also rejects agent
  principals since #1890"
- the tautological test is replaced by three real ones: `require_role` does NOT
  reject agent principals (the false premise pinned as its opposite, read
  through `_code_only`), `restart_system` refuses an agent principal BEFORE
  touching anything (driven for real, with `get_accessible_agents` stubbed to
  raise so a late refusal fails loudly), and a human creator is still admitted
  (so the guard is about principal KIND, not role). Mutation-checked: removing
  the guard turns the last two red.
- export: `set(member_names)` was rebuilt per row inside a comprehension, and
  the sibling branch held a redundant `_member_set` copy — `member_names` is
  already a set, so both branches now read it directly
- MCP `restart_system` description carries the tightened gate and the tag-first
  membership resolution, so an agent caller's 403 is legible

Behaviour changes (release-note material):
- `POST /api/systems/{name}/restart` now requires the `creator` role and a
  human caller. Previously bare `get_current_user`. Agent-scoped MCP keys get
  403.
- `GET /api/systems/{name}/manifest` no longer exports `trinity_prompt`.

Related to #2373

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 31, 2026
… an ungated restart, a broken export round-trip, and prefix-collision membership (#2373)

The deploy half has been hardened by every commit since ent#124; the four
post-deploy endpoints were essentially untouched since 2025.

## Membership is now ONE predicate

`get_system`, `restart_system` and `export_manifest` each matched
`startswith(f"{system_name}-")`, so an operation on `acme` also captured every
agent of a system named `acme-extra` — including `restart`, which stops and
starts containers. Three copies of a wrong rule.

`system_service.system_member_names` is the one rule, and it prefers TAGS:
`configure_tags` already applies the system name to every member, so a tag is a
RECORD of membership where a prefix is an inference from a naming convention.
The prefix survives only as a fallback for pre-tag deployments, narrowed so an
agent claimed by another system's own tag is excluded — a tagged `acme-extra`
agent is never captured by `acme` even there. A failing tag read degrades to the
prefix rather than 500ing.

Residual, stated rather than hidden: two systems deployed BEFORE tagging where
one name is a prefix of the other remain ambiguous, because nothing distinguishes
them. This is also the prerequisite for the teardown verb, where the same
collision would delete rather than restart.

## GET /{name} returns real schedules

It called `db.get_agent_schedules`, which does not exist — the facade exposes
`list_agent_schedules` and `database.py` deliberately has no `__getattr__`
fallback. The AttributeError was swallowed by the surrounding `except
Exception`, so every response omitted `schedules` for every agent and logged one
warning each, while `tests/test_systems.py` never asserted on the key. Exactly
the failure mode the db facade's own comment warns about — so the test also pins
that the fallback stays absent, since adding one would turn the next typo into a
silent Mock.

## POST /{name}/restart is creator-gated

It was bare `get_current_user` — below `POST /deploy` and below even the
READ-ONLY bundled-catalog routes — so any authenticated principal, including
`role: user`, could stop and start every container in a system whose agents it
could see. A mutating fleet-wide verb under a lighter gate than the catalog it
reads is an oversight, not a decision. `require_role` also rejects agent
principals (#1890), which matters because an agent-scoped MCP key resolves to
its owner carrying the owner's role.

## Export round-trips

The non-full-mesh permissions branch sliced `target_agent[len(name)+1:]` with no
membership filter — the sibling branch had one — so an edge pointing outside the
system exported as a blind-sliced garbage short name that then failed
`validate_manifest`'s unknown-agent check on re-deploy. The export broke its own
round trip. Both branches now test membership.

And the export no longer embeds the instance-global `trinity_prompt` as the
manifest's `prompt:`. Deploying that manifest elsewhere overwrote THAT
instance's platform-wide prompt — a fleet-wide side effect from what reads like
a copy of one system. Nothing records whether the source system ever set a
prompt, so there is no honest way to distinguish it from whatever the instance
happens to have configured, and the only correct export of an unknown is to
omit it.

## Two preview hardenings

Unknown PER-AGENT keys now warn like top-level ones (ent#126): `credentials:`,
`skills:` and `display_label:` are the fields people try first and they vanished
in silence.

Preview and deploy now resolve the identical resource default. Deploy hardcoded
`{"cpu": "2", "memory": "4g"}` while `_preflight_template` validated against the
admin-configurable `get_agent_default_resources()`, so the two disagreed the
moment an admin moved the fleet default — the one spot that escaped ent#126's
pure-resolver no-drift pattern.

## Verification

14 unit tests, one per defect plus the exempt shapes. Two mutation-checked: the
restart gate and the tag-first membership each turn a test red when reverted.
414 pass across the system/manifest/ent#126/#1884 suites.

`tests/test_systems.py` is live-backend tier and cannot run without a stack —
which is part of why these survived — so the coverage added here is unit-tier,
where the per-PR gate can see it.

Closes #2373

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 31, 2026
…uire_role

Review found the agent-principal test tautological: it asserted
`"reject_agent_principal" in inspect.getsource(require_role)` and passed
because `getsource` returns the DOCSTRING, which contains the sentence
"Deliberately does NOT call `reject_agent_principal`". The assertion matched
its own refutation.

`require_role` rejects CONNECTOR principals only, and that omission is
deliberate — `require_role("creator")` on `POST /api/agents` is what makes
ent#69 Part 2 agent-spawned creation work. It is not touched here.

The decision the reviewer asked for: human-only is correct, because it closes
a BYPASS rather than merely widening a gate. `POST /agents/{name}/start`,
`/stop` and `/delete` each call `enforce_agent_spawn_scope`, so an agent-scoped
caller may only start or stop agents it actually SPAWNED (name *and* key id).
`restart_system` loops every member calling `container_stop` +
`start_agent_internal` with no per-member check at all — so reaching it with an
agent key performs, in bulk and unscoped, exactly the operation that is
spawn-scoped one at a time. On a default admin-owned install an agent key
resolves to its owner carrying the owner's role, so `require_role("creator")`
alone admits the whole fleet (trinity-ops-agent#232 class).

Scoping per member was considered and rejected: a system whose every member the
caller spawned is a near-empty set, so it would be a strange capability rather
than a useful one. If an agent-driven restart is ever wanted it needs its own
design.

- `restart_system` calls `reject_agent_principal` explicitly, above the `try`
- docstring + `docs/memory/feature-flows/system-manifest.md` state the real
  reason; both previously carried the false "require_role also rejects agent
  principals since #1890"
- the tautological test is replaced by three real ones: `require_role` does NOT
  reject agent principals (the false premise pinned as its opposite, read
  through `_code_only`), `restart_system` refuses an agent principal BEFORE
  touching anything (driven for real, with `get_accessible_agents` stubbed to
  raise so a late refusal fails loudly), and a human creator is still admitted
  (so the guard is about principal KIND, not role). Mutation-checked: removing
  the guard turns the last two red.
- export: `set(member_names)` was rebuilt per row inside a comprehension, and
  the sibling branch held a redundant `_member_set` copy — `member_names` is
  already a set, so both branches now read it directly
- MCP `restart_system` description carries the tightened gate and the tag-first
  membership resolution, so an agent caller's 403 is legible

Behaviour changes (release-note material):
- `POST /api/systems/{name}/restart` now requires the `creator` role and a
  human caller. Previously bare `get_current_user`. Agent-scoped MCP keys get
  403.
- `GET /api/systems/{name}/manifest` no longer exports `trinity_prompt`.

Related to #2373

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
vybe added a commit that referenced this pull request Sep 17, 2026
* fix(workspace): the ask badge said 2 and gave you no way to find them (#2424)

The sidebar advertised "2 asks are waiting on your answer" and then stranded
you: the agent that raised them carried no badge, its tooltip did not mention
them, and it could be collapsed out of the roster entirely. The only way to
locate a blocked agent was to open agents one at a time.

Observed on a 12-agent roster with two asks on ws-sage (11th of 12), so on a
fresh load the one row that mattered was behind the "show more" toggle.

Three failures, fixed together because separately each is a half-measure — a
badge with no destination, or a destination nobody can see.

1. The unit. `askCount` is `openAsks.length`, and the tooltip said "agents":
   two asks on ONE agent rendered as "2 agents are waiting on your answer". The
   number was right, the noun was wrong, and they only diverge when a single
   agent raises more than one ask — which is why it went unnoticed. Resolved
   toward ASKS rather than agents, because the row badges added here now answer
   "which agent", leaving the header to answer "how many decisions".

2. The row. `PortalSidebar.vue:139` renders a per-agent badge from
   `unreadByAgent` — unread REPLIES. Keeping asks out of that count is
   deliberate and documented at line 9 ("one is waiting on you to decide, the
   other on you to read"), and is preserved: the ask gets the *own badge* that
   comment promised, in `status-urgent` — the token the operator NavBar's
   pending-operator-queue badge already uses, so the two surfaces agree — and
   visually distinct from the indigo unread pill beside it. `agentRowTitle` had
   the same hole, so this is an accessibility fix too: a blocked agent's
   accessible name was the bare "Open ws-sage".

3. The collapse. #2159 capped the roster at five for a good reason (a long
   fleet pushed chats below the fold), but the slice is plain roster order with
   no ask weighting. Ask-bearing agents are now never hidden — appended, NOT
   floated to the top, because re-sorting on a transient count moves rows under
   the cursor between refreshes, the same reason the roster is not re-sorted by
   availability.

Not a regression: every piece shipped in its intended form; the gap was between
them.

Everything decidable moved into `portalUtils` (`asksByAgent`, `askBadgeTitle`,
`agentRowTitle`, `visibleAgentRows`, `AGENT_COLLAPSE_LIMIT`) because vitest runs
`environment: 'node'` with no mount harness — a rule inside the SFC is one no
test can reach, which is how all three of these shipped. Mutation-checked:
reverting the noun, dropping asks from the title, and restoring the plain slice
each turn the suite red.

`bg-amber-500` -> `bg-status-urgent-500` is required, not drive-by: new code must
be at zero raw palette classes, so the new badge needed a token, and the header
had to match it or the two ask indicators would differ. Amber maps to
`state-autonomous` (an operating mode), which is the wrong claim. PortalSidebar
is now at zero non-gray raw classes.

Two pre-existing guards asserted the moved expressions as source strings and are
rewritten to assert the properties behaviourally — strictly stronger, since they
now fail on a broken bound or a dropped chip title, not only on a reworded one:
- portalRosterRow #2159 "shows a fixed number by default"
- portalAvailabilityChip #2196 "row title carries the state"

Verification: 1518/1518 frontend unit tests, raw-color ratchet exit 0,
production build clean.

Closes #2424

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(workspace): the sync portal turn never carried its session, so report-back could not fire (#2426)

ent#457 gave the Workspace a report-back: an agent that delegates during a chat
turn gets the completion posted into that thread. It could not fire on the
SYNCHRONOUS path, because the parent execution never received the session
binding the report needs. `report_completion` gates on
`if not source_channel_chat_id`, and there the field was NULL.

Measured on a dev instance — 5 of 8 portal rows NULL, split exactly by path:

    07:55 -> 09:04   chat=7d27744d...   browser, streaming path
    09:06 -> 09:09   chat=NULL          POST .../chat, synchronous path

TWO CORRECT CHANGES THAT COLLIDE. ent#457 passes the binding down, and
`execute_task` persists it — but only inside `if not execution_id:`. ent#365's
`_precreate_sync_execution` has already created the row and handed the id over,
so that branch never runs, and the pre-create stamped only `source_channel`.
Its own docstring named the invariant it broke: "Mirrors `start_portal_turn`'s
creation exactly ... so the two paths produce indistinguishable rows and a
report published from either can be joined back to its chat."

The sibling comment in `start_portal_turn` says "both creation sites or the
stamp is a coin flip depending on which path made the row" — ent#457 covered the
two sites that existed when it was written; ent#365 had added a third.

Fix: stamp `source_channel_chat_id` + `source_channel_client` in the pre-create.
`session_id` is a REQUIRED parameter, not an optional one — the value is in
scope at the only call site, and a default would let a future caller silently
reintroduce the inert row. Rejected: teaching `execute_task` to UPDATE an
adopted row, which widens a hot path used by every trigger to repair one
caller's omission.

ALSO REPAIRS TWO GUARDS THAT WERE RED ON `dev`. `backend-unit-test` is failing
on dev right now; both failures are in this feature area and both are guards
that had gone inert, so they are fixed here rather than left for the next PR to
trip over. Frontend-only PRs pass because the `changes` job path-filters the
backend suite away, which is why this went unnoticed.

  * `test_both_portal_row_creation_sites_name_the_chat` asserted a literal
    census of `== 2` sites. It went red the moment the third site appeared —
    the guard WORKING — and the bug it names shipped anyway. Now asserts the
    rule instead of the count: every site that stamps the surface must also
    stamp the destination. Census-proof.

  * `test_portal_turn_kwargs_bind_against_execute_task` parsed `portal_chat`
    for a literal `run_resumable_turn(...)` call. That call had moved into
    `_run_sync_turn_and_clear_marker`, where it is `run_resumable_turn(**kwargs)`
    — a splat, which names nothing — so the walk found no keywords and the
    guard asserted itself dead. Now reads the keywords where they are actually
    named (the wrapper's call site), scanning both entry names and subtracting
    the wrapper's own consumed parameters.

Neither rewrite loses coverage; both now fail for the reason their docstring
gives rather than because a number or a call site moved.

WHY THE BUG SURVIVED ITS TESTS. ent#457's mock the engine and assert the kwargs
are passed (they are). ent#365's assert no orphan `running` row (still true).
Nothing asserted the PERSISTED ROW, which is the only place the two meet — the
same lesson `test_ent457_portal_turn_kwargs.py` states about itself. The new
suite asserts at that layer, and adds a derived parity check so a fourth
channel field added to one writer and forgotten in another fails here instead
of shipping as another silently-inert report path.

Verification: 402 passed on the portal/ent457/ent365 selection (was 2 failed
before this branch). Mutation-checked: removing the stamp turns 4 red; feeding
`execute_task` an unknown kwarg turns the repaired binding guard red.

Closes #2426

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(subscriptions): auto-switch ranks alternatives by cached headroom, never by load alone (#2409) (#2422)

## Summary
- `select_best_alternative_subscription` returned the **first** survivor of the 2h failure filter in `agent_count ASC` order and read no headroom — SUB-003 could move an agent onto a subscription at 99% of its weekly window, and an *unused dead-token* subscription (no agents ⇒ no failure rows) sorted **first**.
- Now: **filter in the db, rank in the service, never a probe.** The db lists survivors (kind-blind 2h filter unchanged and first, #444/#2352, `agent_count ASC, name ASC`); the service ranks them over the cached provider snapshot (one `MGET`) furthest-from-the-nearest-wall first (the fuller of the 5h/7d windows — the #792 retry lands on the destination immediately), in 10-point bands so load still spreads a storm; a **fresh** provider refusal is dropped; anything unusable sorts in today's order; any failure of the ranking half falls back to today's pick **with a warning**.
- `classify_headroom` (ent#434) and the ranker share one usability gate (`headroom_reading`) — verdicts byte-identical, pinned by a differential test against a frozen copy. New-agent auto-assign (#74) rides the same ranker. The switch now records **why** (`destination_headroom` + one notification clause).
- Approved deviations from the literal AC, recorded on the issue: nearest-wall key instead of 7d-only; fresh refusals filtered instead of ranked last.

## Changes
- `src/backend/services/subscription_headroom_service.py` — gate, MGET reader, threshold-free ranker, `MAX_READING_AGE_SECONDS` (owned here now); `classify_headroom` becomes policy over the gate
- `src/backend/services/subscription_auto_switch.py` — service-layer selector (`asyncio.to_thread` under the agent lock), `destination_headroom` on activity / notification / result
- `src/backend/services/subscription_service.py` — `select_subscription_for_new_agent`
- `src/backend/db/subscriptions.py` + `database.py` — `list_viable_alternative_subscriptions` / `list_assignable_subscriptions` (filter only); first-match selectors retired
- `src/backend/services/agent_service/crud.py` — call site; `subscription_headroom_alerts.py` — constant re-export + docstring
- Tests: new `tests/unit/test_2409_headroom_ranked_switch.py`; pingpong / 2352 / concurrency / 1484 / 1759 adapted to the list form (assertions kept)
- Docs: `architecture.md`, `subscription-auto-switch.md` (+ management, usage-tracking), requirements §20.4, `learnings.md` (2 entries), CSO diff report

## Test Plan
- [x] New suite: `pytest tests/unit/test_2409_headroom_ranked_switch.py` — 83 passed; **80/81 fail on the unmodified source**
- [x] Full `tests/unit`: 12,718 passed / 30 skipped / 1 pre-existing failure (`test_1920`, private submodule, untouched)
- [x] API integration (`test_subscription_auto_switch`, `test_subscriptions`, `test_subscription_usage`): 36 passed
- [x] Live: a real switch chose the 18%/9% subscription over the 0-agent 88%/60% one; every-survivor-refused → no switch + WARNING; no snapshot → today's order
- [x] `/review` clean (informational findings fixed in-review); `/cso --diff` no findings
- Follow-ups filed while testing: #2419 (parser overage), #2420 (destructive integration suite), #2421 (subscription audit gap)

Fixes #2409

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* feat(workspace): an answer given in the Workspace resumes the agent (ent#430)

Slice 5 of ent#364, and the gate: until now the client route recorded an answer
and returned. The operator route called `spawn_resume_dispatch`; this one did
not. So an ask addressed to a Workspace client — the entire point of
ent#364/#428/#429 — was recorded, reached the agent's queue file in about three
seconds, and re-triggered nothing.

Measured on a live instance before this change: answered from the Workspace,
`operator-queue.json` flipped to `responded` with the answer in under 3s, and no
execution followed.

Unblocked because ent#329 is in dev.

WHAT THIS ADDS: one call. ent#430's body rules out the alternative — "a second
dispatch surface for the same event is how the cost, trigger-label and
loop-prevention questions get answered twice, differently" — so the per-agent
opt-in, the idempotency key, the audit row and the failure handling all stay
inside `maybe_dispatch_resume`. AC #2 and AC #3 are satisfied by REUSE rather
than by re-implementation, and the tests assert the CALL for that reason.

Four properties, each load-bearing:

* Hung off the CAS WIN only, like the operator route. The 409 above already
  returned for a lost race, so reaching the dispatch means this answer is the
  one that landed — two people answering at once produce one resume.
* `updated`, never `item`. The pre-answer read still says `pending`; a resume
  handed that row acts on an ask that does not yet carry its answer. Looks
  identical in a green test, which is why there is one for it.
* The spawn is wrapped. It is fire-and-forget, but a raise ON THE CALLING LINE
  would still propagate, and a 500 after the CAS landed would tell the client
  their answer failed while it is committed and already on its way to the agent.
  The answer is the thing that must not be lost.
* #2376's choice validator runs first, so an answer that was never offered
  cannot spend.

AC #5 — `resume_requested` on the answer response, read from the SAME accessor
the dispatch gates on, so the two cannot disagree about what is about to happen.
It reports INTENT, not success: the dispatch is backgrounded, so at that moment
the only honest claim is whether it will be attempted. Fails CLOSED — an
unreadable flag claims nothing, because over-claiming is exactly the failure
AC #5 names ("the ask does not read as resolved while nothing happened").

RESIDUAL, stated rather than implied: a dispatch that fails AFTER this point
surfaces as a FAILED execution row plus an `operator_resume_dispatch` audit
entry (ent#329) — operator-visible, and a client cannot see either. The client
half of AC #5 is satisfied negatively for now: the ask surface says nothing
about work starting, so it cannot mis-claim. `resume_requested` is the field a
surface needs to say something true; consuming it is an ent#429 UI change and is
deliberately not in this PR.

The per-agent flag DEFAULT IS UNCHANGED (`operator_resume_enabled`, OFF,
owner-only). "Turn the flag on" is an operator action per agent, not a code
default: flipping it would hand every shared agent's client a spend button,
which is the one thing AC #3 rules out.

Verification: 145 passed across the asks/ent#329/ent#364/#428/#429/#2376
selection. Mutation-checked — removing the dispatch (4 red), passing the
pre-answer row (1 red), and making the opt-in read fail open (1 red).

Closes ent#430

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(workspace): New chat means a new chat (ent#451 — the fresh-thread slice)

Reported: pressing New chat in the Workspace drops you back into the existing
conversation with that agent. Decided at the 2026-08-21 weekly.

ONE VALUE CARRYING TWO MEANINGS. An absent `session_id` meant both "I don't know
which thread" and "I want a fresh one", and the platform resolved it as the
first, in both readers:

    _resolve_session_id(..., None)  -> resume the client's latest
    get_history(..., None)          -> return the most-recent thread

Both readings are RIGHT for the case they were written for — a deep link, a
refresh, an API caller that never held a session id — so neither could be
inverted. The intent had to become sayable: `new_thread` on the request,
`newChat` on the component, checked before the resume.

The frontend tell was an asymmetry: New chat with the agent you were ALREADY on
started fresh, while New chat with a different agent resumed. The watcher read a
changed agent as "load that agent's history" and called `fetchHistory(name,
null)`, discarding the `pendingSession = null` that `newChatWithAgent` had just
set to mean the opposite.

MOST OF ent#451 TURNED OUT TO BE BUILT. Recorded because the issue is
complexity-high and this PR is not:

* the data model already allows many sessions per (agent, client) — no UNIQUE
  constraint, a `title` column, an index on
  `(agent_name, client_email, last_message_at)`, and auto-titling. AC #4's
  "migrates cleanly" is nothing to migrate.
* AC #2's list is the existing sidebar: titles, recency, starred lifted out,
  search, per-agent avatars.
* AC #3's landing rule is already decided and documented in
  `ensure_thread_for_ask` — reuse the latest thread so asks do not accumulate
  beside the conversation. UNCHANGED here, and pinned by a test so this cannot
  move it silently. It matters MORE once several chats exist, not less.

So what was missing is AC #1, and it is two bits rather than a data model.

Four properties:

* An explicit `session_id` WINS over the flag. A caller sending both contradicts
  itself; the id is a fact, the flag an intent, and abandoning a named thread
  would strand a turn meant for a conversation the caller could see.
* The ownership check runs first either way — the flag is never a route past it.
* BOTH turn entry points carry it. The Workspace uses the streaming path and
  falls back to the synchronous one, so a flag honoured by only one brings the
  bug back exactly when streaming fails.
* The intent is spent on adoption. The send guard already ANDs on "no session
  yet", so a second turn was never going to open a third thread; clearing it in
  `onSessionAdopted` keeps the two bits from disagreeing after a navigation.

Test doubles updated, not worked around: seven `_resolve_session_id` lambdas and
four `_fake_chat` stubs did not accept the new keyword. They take `**kw` now — a
stub that must be edited for every new parameter is a second signature — and one
hand-rolled `_Body` model double gained the field. All are stale stubs rather
than behaviour changes.

Verification: 392 passed across the portal/ent#286/#287/#358/#429/#430/#451
selection; 1497 frontend unit tests. Mutation-checked: making the flag inert, and
letting it override an explicit session id, each turn the suite red. The full
backend suite exceeds a local foreground run and is left to CI.

Pre-existing and NOT from this branch: `test_ent457_portal_turn_kwargs` and
`test_both_portal_row_creation_sites_name_the_chat` fail on `dev` today; both are
fixed in #2427.

Related to ent#451

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(review): the ?new=1 deep link, the missing frontend test, and three latent desyncs (ent#451)

Blocker 1 was real and I had not seen it. `resolveAgentQuery` passed `forceNew`
to `resolveAgentLanding` and set `pendingSession = null`, but never raised
`startingNewChat` — so `/workspace?agent=X&new=1` rendered an empty conversation
and then sent `new_thread: false`, resuming the thread the user asked to leave.
The reported bug, intact on the documented `?new=1` contract, in the PR that
exists to fix it.

The cause is the one this PR is about, one level up: `route.query.new` was read
in two places for two different decisions — WHICH THREAD to land on and WHAT THE
FIRST SEND ASKS FOR — and only the first honoured it. Now read ONCE into a local
that feeds both, so they cannot drift again. AND-ed with the landing result, so
a `?new=1` that still resolved a thread never claims a fresh start.

Blocker 2: a frontend test, which the change genuinely had none of — the
`1497 passed` in the body was the pre-existing suite, as the review says.
`workspaceNewChat.spec.js` (9 tests) covers the deep link, the watcher branch
ORDER, the first-paint guard, both send conjunctions, and the settle-everywhere
rule, using the two established patterns (pure function + source assertion in
the `portalLeaveSpecificRoute.spec.js` shape) since vitest runs
`environment: 'node'` with no mount harness. Mutation-checked, and M1 is the
reviewer's own blocker: reverting it turns the suite red.

Blocker 3: `test_history_without_a_session_is_unchanged` cited "the spec in
tests/unit/... frontend suite" — a dangling reference asserting coverage that
did not exist. It now names the real file.

Comments addressed:

* Three more sites nulled `pendingSession` without settling the intent — the
  deep-link watcher (the commonest way in), `openRoom`, `openAgentPage`, plus
  the unreachable-agent branch. Latent because both consumers AND on "no session
  yet", but a flag that is only correct because of a second variable is one
  refactor from being wrong, and the declaration claims it is cleared the moment
  a real thread exists. Now true.
* `test_both_turn_entry_points_forward_it` was `getsource` + a substring, so a
  comment or a misspelled kwarg satisfied it. It now BINDS the keyword against
  each service signature and asserts the routes forward `body.new_thread`
  through a comment-stripped source — verified by mutation.
* `workspace-absorbs-session.md` updated at both seams the change touches
  (`resolveAgentLanding`'s landing rule and `_resolve_session_id`'s three
  states), and `architecture.md`'s Workspace section documents the new public
  `new_thread` field on the ent#83 headless surface.
* Gating stated rather than inferred: "OSS-core by decision (ent#451)", matching
  the ent#326/#384/#392 convention.

ONE CORRECTION, offered with evidence rather than silently applied. The review
says "`test_ent457_portal_turn_kwargs.py` doesn't exist on `dev`, #2427
introduces it". It does exist on `dev` — added by d6a4bc10 (ent#457) — and #2427
modifies it. `git cat-file -e origin/dev:tests/unit/test_ent457_portal_turn_kwargs.py`
succeeds, and `backend-unit-test` is failing on `dev` independently of any PR.
So the body's "fails on dev today" stands. Everything else in the review is
accepted as written.

Verification: frontend 1497 -> 1506 (+9). Backend 392 passed on the portal
selection, the same 2 pre-existing dev failures unchanged.

Related to ent#451

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(resume): the respond→resume dispatch never ran — bad import, masked by its own stub (ent#329)

Found by testing this PR's feature against a live local instance. ent#430 wires
a Workspace answer to `spawn_resume_dispatch`, so this PR is dead on arrival
without it — the client path would have hit the same wall the operator path has
been hitting since ent#329 merged.

THE BUG. `operator_resume_service.maybe_dispatch_resume` did:

    from services.task_execution_service import task_execution_service

That name has never existed on that module; it exports
`get_task_execution_service()`. The import sits on the FIRST line of the
function, above the try, so every dispatch raised ImportError before it even
read the opt-in.

WHY NOBODY NOTICED, twice over:

* the call is fire-and-forget, so the traceback surfaces only as asyncio's
  "Task exception was never retrieved" — nothing fails, nothing 500s, the
  answer is recorded and the config audit row is written. It looks like it
  worked.
* the ent#329 unit test stubbed `services.task_execution_service` with
  `SimpleNamespace(task_execution_service=recorder)` — MANUFACTURING the very
  symbol whose absence was the bug. 21 tests green, feature dead.

MEASURED on a live instance, opt-in ON:

  before: answer 200, audit row written, executions 0->0, log carries
          "cannot import name 'task_execution_service'"
  after : answer 200, executions 0->1, triggered_by=operator_response,
          audit `operator_resume_dispatch` with the execution id, 0 ImportErrors

(The dispatched run then failed on a missing AGENT_AUTH_SECRET — a limitation of
the test box, and correctly recorded as an honest FAILED row, which is ent#329's
"never silent" requirement doing its job.)

THE GUARD is the durable part, because the stub is the real lesson: a stub that
invents an API the real module lacks converts a production crash into a green
suite. `test_the_names_this_service_imports_actually_exist_on_the_real_modules`
parses the REAL module source with `ast` — never the stubbed `sys.modules`
entry, which is what made this invisible — and asserts every
`from services.X import Y` resolves. Mutation-checked: reverting the import
turns 11 tests red.

Related to ent#430, ent#329

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(review): the dispatch could not run, the race loser spent, the flag over-claimed (ent#430)

All three blockers from the review, each verified rather than argued.

1. THE FEATURE WAS INERT. `client_portal/asks/router.py` declares `answer_ask`
as a plain `def`, so FastAPI runs it through `run_in_threadpool` — a worker
thread with no event loop — and `asyncio.create_task` raises
`RuntimeError: no running event loop` there. The `except` swallowed it, so every
client answer recorded the answer and dispatched nothing: byte-for-byte the
behaviour this PR exists to remove.

Fixed in `spawn_resume_dispatch` rather than by flipping the route to
`async def`, for the two reasons the review names: the route does blocking DB
I/O, so `async def` alone would move it onto the loop; and ent#430's stated
shape is ONE dispatch site, which moving the spawn back out to the caller would
undo. It now detects the absence of a loop and hops back via
`anyio.from_thread.run_sync` — Starlette's threadpool is anyio's, so the portal
is always there on this path. Any future sync caller inherits the fix.

A thread anyio does not own reaches neither branch. That is not a production
shape, but it must not become the silent no-op this change removes, so it raises
with the cause named instead.

2. THE RACE LOSER SPENT MONEY. `respond_to_operator_queue_item` returns None
only when the row is GONE; when the row exists and has left `pending` — the race
that actually happens — it returns a TRUTHY dict carrying `_status_conflict`,
having written nothing. `if not updated` fell straight through it. The loser
then dispatched a paid execution for an answer not in the database, and because
the idempotency key hashes the response text, the loser's differing text yields
a different digest: one queue item, two paid dispatches. `routers/operator_queue.py`
already pops that flag before its own spawn; this is that rule, not a new one.
Popped, not read, so the sentinel cannot serialize to the client.

3. `resume_requested` OVER-CLAIMED. It was computed after the swallowed spawn
from the opt-in flag alone, so a spawn that raised still answered `true` — the
exact failure AC #5 names, and given (1) that was EVERY production answer on an
opted-in agent. It now reports what was actually scheduled.

TESTS — the reason all three survived 24 green checks is that every existing test
replaced `spawn_resume_dispatch` with a synchronous lambda, stubbing out the one
call whose runtime context was the defect. `test_ent430_dispatch_actually_runs.py`
drives the REAL spawn from a REAL anyio worker thread (the production context,
not an approximation) and asserts the premise before the behaviour. The lost-race
test uses the truthy `_status_conflict` shape that actually occurs, not the
`None` shape that does not. Mutation-checked: reverting fix 1 turns 1 red, fix 2
turns 3 red, fix 3 turns 2 red.

Writing those tests also caught a stubbing bug of my own, worth recording because
it is the trap that hid the original: patching only `sys.modules` leaves
`from services import operator_resume_service` resolving the PACKAGE ATTRIBUTE,
so the real function ran anyway. Both paths are patched now.

Related to ent#430

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(review): the answered ask said pending, and the docs described one caller (ent#430)

Non-blocking findings from review pass 2. The three blockers landed in d11956a8.

STATUS. `_project` mapped every row to pending/expired, so the response to a
just-recorded answer read `status: "pending"` beside `resume_requested: true` —
one row reporting both that nobody has answered it and that answering it started
work. Harmless while the second field did not exist; contradictory once it did.
`_status_of` adds `answered` (`responded`/`acknowledged`), reachable only from
the answer response since the listing carries neither. Answered is checked
BEFORE expiry — an answer that landed is a fact, and an `expires_at` that has
since passed does not un-answer it; the obvious refactor is to test expiry first,
which would make a slow client's own answer vanish, so the ordering is pinned.

The existing test asserted `out.status in ("pending", "expired")` with the
comment 'the point is it returned at all' — it was papering over exactly this.
It now asserts `answered` and, on the spawn-failure path it covers, that
`resume_requested` is False.

THE TWO READS. `_resume_requested`'s docstring claimed it read 'the SAME
accessor … so the two cannot disagree'. True of the accessor, false of the
instant: it is a second read a task hop earlier, and an owner disabling the
opt-in in between gets `true` and no resume. Collapsing them is not the fix —
they answer different questions (one must produce a value for THIS response, the
other is the authority at the moment it would spend), so the window is stated,
with AC #5's own remedy named, rather than described away.

DOCS. architecture.md's ent#329 section described a single caller and stated the
CAS-win property the second caller broke. It now carries the second caller, the
truthy-`_status_conflict` shape that defeated `if not updated`, the
sync-endpoint/no-loop defect and its `anyio.from_thread.run_sync` fix, and what
`resume_requested` actually reports.

Related to abilityai/trinity-enterprise#430

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore(enterprise): bump the submodule pointer to main (a419812 -> 90f2f2c) (#2440)

dev's pointer was OLDER than main's — an inversion, not just staleness. The
next dev -> main release merge would have carried it backwards and undone
ent#443's enterprise-side removal:

  OSS main -> 2a5def3   (ent#443: shared_sessions removed from enterprise)
  OSS dev  -> a419812   (4 behind enterprise main, 2026-08-19)
  ENT main -> 90f2f2c

90f2f2c is a fast-forward from BOTH (a419812...main = ahead 0 / behind 4;
2a5def3...main = ahead 3 / behind 0), so nothing is being rewound.

WHAT THE FOUR COMMITS ARE

  2a5def3  refactor(rooms): remove shared_sessions — it now lives in OSS core (ent#443)
  ff0a4f1  fix(security): guard the enterprise system_settings sinks against
           cleartext credentials (ent#435) — the private twin of the OSS sink
           guard architecture.md already records as "the private submodule owns
           its twin"
  6d82a3f  docs(workspace): agent-initiated asks — design of record
  90f2f2c  feat(credential-vault): governed system credential vault module (ent#279)

WHY IT MATTERS RATHER THAN BEING HOUSEKEEPING. ent#443 moved rooms into OSS
core, and dev has that. With the stale pin an entitled dev install mounts the
OSS rooms routers AND the enterprise shared_sessions module, and relies on
main.py's include-order (OSS before register_enterprise) to decide which one
serves. architecture.md documents that ordering as the transition safety net —
this bump is the follow-through that ends the transition.

VERIFIED BY BOOTING BOTH POINTERS against dev, same box, same DB shape:

  a419812 (today):  17 modules | shared_sessions registered: True  | 6 room paths | 0 errors
  90f2f2c (this):   17 modules | shared_sessions registered: False | 6 room paths | 0 errors

Both boot clean and log "Trinity Enterprise modules registered" — the line
deploy-dev greps. Module count is unchanged because shared_sessions leaves as
credential_vault arrives. No duplicate room paths in either, confirming the
ordering net held; after the bump there is nothing to net.

Gitlink only — no OSS source changes, so public CI (which never checks the
submodule out) is unaffected.

Related to ent#443, ent#435, ent#279

* chore(metrics): code-health dashboard 2026-08-31 @ 135248e9 (#2438)

Co-authored-by: Trinity Agent (trinity) <[email protected]>

* chore(deps): bump node (#2400)

Bumps the docker-base-images group with 1 update in the /docker/frontend directory: node.


Updates `node` from 24-alpine to 26-alpine

---
updated-dependencies:
- dependency-name: node
  dependency-version: 26-alpine
  dependency-type: direct:production
  dependency-group: docker-base-images
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* fix(files): shared links were unopenable on mobile — Range, disposition, MIME, CORP (trinity-enterprise#461) (#2439)

* fix(files): shared links were unopenable on mobile — Range, disposition, MIME, CORP (trinity-enterprise#461)

The bytes were never wrong. Verified from the Cloudflare edge, the object
returned HTTP 200 with correct content-length and correct WAV bytes for every
user-agent tried, and the signature check worked. The RESPONSE SHAPE was wrong
in four ways at once, and each one alone is enough to break playback in an iOS
in-app browser:

* no Range support — `Range: bytes=0-1023` returned 200 with the whole 2 MB
  body and no `accept-ranges`. iOS Safari and Telegram's player require a 206
  to start audio at all, so this alone made the file unplayable.
* `content-disposition: attachment` — a forced 2 MB download inside Telegram's
  iOS browser is a blank screen.
* `audio/x-wav` under `nosniff` — unregistered type, so a strict player
  declines it and the browser is forbidden from guessing better.
* `cross-origin-resource-policy: same-origin` on a link whose entire purpose is
  to be opened from another platform.

Plus `cache-control: no-store`, which forbids the in-app browser from buffering
media it will not play without buffering.

THE INLINE CHANGE IS A NARROWING, NOT A REVERSAL. The old code forced
`attachment` on everything with the note 'defense against XSS via
agent-uploaded HTML', and that reasoning is still correct — this route serves
agent-authored bytes from the same origin as public chat. So inline is an
ALLOWLIST (`_INLINE_SAFE_TYPES`: audio, video, image, PDF) and `text/html`,
`application/xhtml+xml` and `image/svg+xml` stay attachments. SVG is called out
because it is the one a reviewer waves through: it is an image by name and a
script host in fact. The type is python-magic-detected from the file's own bytes
at share time, never agent-supplied, and its unavailable-fallback
(`application/octet-stream`) sits outside the allowlist, so the failure
direction is `attachment`. `nosniff` is kept and matters more now, not less.

TWO THINGS THE ISSUE DID NOT ASK FOR, both found while implementing:

* `Content-Length` came from the DB's `size_bytes`, written at share time. Any
  drift from the file on disk is unrecoverable for the client — too small
  truncates, too large hangs — and Range math against a wrong total produces a
  `Content-Range` that contradicts the body. It now comes from
  `os.path.getsize`, with a WARNING on divergence.
* a media player fetches one file as MANY ranged requests. Counting each as a
  download would turn one play into dozens and write an audit row per chunk, so
  the counter and the audit fire only on the transfer START (a plain GET, or a
  range beginning at byte 0).

VERIFIED end-to-end against the real route, not just the parsers:

  full GET      : 200 | type audio/wav | disp inline | ranges bytes
                | corp cross-origin | cc private, max-age=3600
  range 0-1023  : 206 | body 1024 | bytes 0-1023/2048000 | bytes ok
  suffix -500   : 206 | bytes 2047500-2047999/2048000 | bytes ok
  unsatisfiable : 416 | bytes */2048000
  HEAD          : 200 | accept-ranges bytes | content-length 2048000
  no sig / bad sig / unknown id / expired : 401 / 401 / 404 / 410
  html file / svg file : attachment

That covers the issue's Definition of Done line by line, including that the
signature check still rejects unsigned and expired requests.

46 new unit tests, weighted to the allowlist and to the range parser's
silent-corruption case (`bytes=-500` is the LAST 500 bytes; reading it as
start=0 serves the wrong bytes under a 206, which no client can detect).

Related to trinity-enterprise#461

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(files): the CORP header was inert — the security middleware clobbered it (trinity-enterprise#461)

Found by testing the PR against a real local instance rather than a TestClient.

`main.add_security_headers` runs after EVERY route and set
`Cross-Origin-Resource-Policy` with a plain assignment. So the `cross-origin`
policy the file-download route sets — one of the four fixes in this PR, and the
one that decides whether Telegram, Slack or WhatsApp can embed or preview the
link at all — was silently overwritten back to `same-origin` on its way out.

The fix shipped INERT and every test passed, because a bare `FastAPI()` +
router harness has no middleware. Measured on the running server:

  before: cross-origin-resource-policy: same-origin
  after : cross-origin-resource-policy: cross-origin   (file route)
          cross-origin-resource-policy: same-origin    (/health, unchanged)

`setdefault` rather than a route allowlist: absence still resolves to the strict
default, so every other route keeps today's behaviour and a new route has to opt
out deliberately rather than inherit an exception.

Pinned by a source assertion — asserting it end-to-end needs a live stack, and
what must not regress is the `setdefault`; an edit back to `=` would re-break it
invisibly.

Related to trinity-enterprise#461

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

* refactor(main): lifespan is an orchestrator, not a 580-line procedure (#1028) (#2437)

* refactor(main): lifespan is an orchestrator, not a 580-line procedure (#1028)

`main.py::lifespan` was 580 lines at cyclomatic complexity 109 — the longest
function in the backend and the first item the 2026-06-02 refactor audit named.
It is now 25 lines at CC 1: a flat list of `await _phase()` calls over twelve
startup helpers and four shutdown helpers.

WHAT MOVED, AND THE PROOF THAT NOTHING ELSE DID. Every body is verbatim. That
is asserted mechanically rather than claimed: extracting all non-blank lines
from the sixteen helpers in call order and diffing against the original
`lifespan` body gives 518 = 518, identical. The only relocated line is `yield`.
No behaviour change, no logic touched, no try/except reshaped — each phase keeps
its own guard, because a failing phase must not take the boot down, which is
what the original did.

WHY THE TEST IS THE POINT. Splitting the function is easy; keeping it split is
not, and the thing worth guarding is not the line count — it is THE ORDER.
Boot ordering is load-bearing in ways invisible at the call site: a reviewer
looking at sixteen await lines cannot see that moving one breaks something,
because the coupling lives in the bodies. Before this it was implicit in a
function nobody could read in one sitting; after it, it is a list — which is an
improvement only if something enforces the list.

So `tests/unit/test_1028_lifespan_phases.py` pins the sequence WITH the reason
for each constrained pair recorded beside it: logging first so a later hang
cannot swallow the boot log (#858); the event bus before any WebSocket client
needs a live dispatcher (#306); Docker/system-agent before the fleet sweepers;
startup recovery before the channel transports, so inbound traffic cannot create
an execution that races the reconcile; the event-bus drain LAST on shutdown so
late broadcasts still land. A reorder now fails with the reason attached instead
of surfacing weeks later as a boot bug nobody connects to this commit.

It also pins the `yield` split (a phase appended after it silently becomes
shutdown work), the per-helper thresholds the issue asked for (<100 lines,
CC <20), and orphan/double calls. Mutation-checked five ways — recovery moved
after the transports, event bus after Docker, a dropped shutdown phase, the
drain no longer last, a phase pushed past `yield` — all caught.

ONE DEFECT THIS FOUND IN ITSELF, worth recording because it is the failure this
refactor's shape invites. The extraction moved `@asynccontextmanager` by one
definition: it landed on the first phase helper and `lifespan` was left a bare
async generator, which FastAPI cannot use as a lifespan. Boot-breaking — and the
entire 12,900-test unit suite stayed green, because nothing in it imports `main`
and asks what shape `lifespan` is. It surfaced only from an explicit import
check (`iscoroutinefunction` on each helper returned False for one, with
`co_filename` pointing into contextlib). Fixed, and pinned by its own test.

Docs: the `main.py` row in architecture.md now records that the order is the
contract and where the constraints are, so the next person to add a startup step
knows it belongs in a phase helper.

Scope: one file per the issue's own recommendation. The remaining ACs
(`routers/settings.py`, `routers/ops.py`, `services/git_service.py`,
`services/agent_client.py`, `routers/public.py::public_chat`) stay open on #1028.

Related to #1028

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(review): three phase helpers used locals the split left behind (#1028)

/review's scope pass caught a real runtime break in my own extraction, and the
interesting part is that three separate verifications had already passed on it.

`main.py` never imports `database` at module level. The old `lifespan` did
`from database import db as _db` once near the top, and three blocks 100+ lines
later used it through the enclosing function scope: the system-agent
`setup_completed` gate, the Telegram transport and the WhatsApp transport.
`message_router` was the same shape — imported in the Slack block, used by the
Telegram one. After the split all four are NameError.

The severity is in the swallow. Every one of those use sites sits inside
`try/except Exception`, so the boot SUCCEEDS: the log carries "Error starting
Telegram transport: name '_db' is not defined" and the Telegram and WhatsApp
integrations are simply never wired. A silently dead integration, not a failed
boot — and the per-phase guard that makes each phase fail-open is exactly what
hides the extraction bug.

Why the existing checks missed it, all three: the AST equivalence proof compares
LINES and the lines are identical; the structural pin asserts order, thresholds
and decorators, not name resolution; and the `import main` smoke never RUNS
`lifespan`, so nothing resolves those names at import time.

Fixed by re-materialising each import in the helper that needs it — the
original's own idiom — with a comment saying why it is there, so a later reader
does not "tidy" it back out.

CORRECTION TO THE CLAIM: the bodies are no longer byte-identical. They are
verbatim EXCEPT these four re-materialised imports, which is now what the PR
body and the docstrings say. A verbatim claim stops being true the moment a
leaked name has to be restored, and quietly keeping the claim is worse than the
bug.

Also pinned, because this gets more likely with every future split of the same
function: test_no_phase_helper_depends_on_another_phases_locals asserts, per
helper, that `names_loaded - names_bound - module_globals` is empty. Mutation-
checked by deleting the restored `_db` import — reproduces the shipped bug and
turns the suite red.

Also: the phase-count docstrings said "of 10" in 9 helpers; the transports were
split into three after that text was written, so it is 12.

learnings.md gains the class: extract-method has a failure mode the diff cannot
show and an import smoke cannot reach.

Related to #1028

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(review): the verbatim claim survived in three docstrings (#1028)

Re-review finding. The previous commit corrected "bodies are byte-identical"
in the PR body but left the same claim standing in the code, where it is more
likely to be believed: the three helpers that gained a re-materialised import
still said "the body below is unchanged".

A stale claim next to the exact line that falsifies it is worse than no claim —
it is the thing a future reader checks against before deciding the import looks
redundant. Now each says verbatim EXCEPT the restored import, and points at the
comment explaining why it is there.

Related to #1028

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(tests): two pre-existing lifespan guards read a function the split emptied (#1028)

CI's regression diff caught 4 new failures, deterministic across all three
seeds. Both guards assert properties of `lifespan`'s SOURCE, and #1028 moved
that source into phase helpers — so they were asserting things about a function
that is now 25 lines of `await` calls.

The properties still hold. The guards had stopped being able to see them, which
is the worse failure: a guard that silently stops covering its subject reads
identically to one that passes.

test_1267_lifespan_db_alias — and this one is pointed: #1267 IS the bug class
/review caught in this branch. It fired when the transport blocks called a bare
`db` while only `_db` was in scope, NameError swallowed by the surrounding
try/except and surfaced as a misleading "Error starting Telegram transport".
The split re-introduced the same class in a new form (`_db` bound in phase 1,
read in three later helpers), and this guard could not see it because it only
ever looked inside `lifespan`.

So it now follows the calls: `_lifespan_surface()` returns `lifespan` plus the
helpers it awaits, and every check scans all of them. The alias check is
STRENGTHENED rather than merely relocated — binding `_db` somewhere on the
surface is no longer sufficient, because after the split each helper is its own
scope, so every function that READS `_db` must bind it. That assertion fails on
the exact defect this branch shipped.

test_858_dockerfile_unbuffered — the #858 invariant is an ORDERING one
(setup_logging -> first-run notice -> event_bus.start), and after the split
those three sit in three different functions. `_lifespan_body()` now flattens
the phases inline in call order, so the existing index comparisons keep meaning
what they meant. An unresolvable helper is left as the bare `await` rather than
skipped, so a phase this cannot expand can never silently drop the statements
it contains.

No production code changed.

Related to #1028

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

* fix(retention): every install writes its own retention rows, not just fresh ones (#2085) (#2432)

#1645 closed #1638 by reverting OPS_SETTINGS_DEFAULTS to the wide historical
values and applying the #1039 community floor through explicit system_settings
rows seeded on FRESH installs only. Every install that has ever upgraded rather
than been created fresh therefore had no rows at all, so cleanup_service
resolved all 11 windows at prune time from a dict that ships inside the backend
image and is replaced on every rebuild. The only thing between a future edit to
that dict and the #1638 failure mode — a silent hard-DELETE of existing data
seconds after the next boot, green /health, no error — was a code comment.

database._seed_retention_windows{,_engine} now writes an explicit row for every
RETENTION_OPS_KEYS member that has none, at the value already in force, on every
boot and regardless of install age. Behaviourally inert: it writes the number the
prune already used, so nothing prunes differently the day it runs.

Three properties are load-bearing:

* The key set is DERIVED from RETENTION_OPS_KEYS, never a second hand-written
  list, so a window added later is covered the day it ships instead of quietly
  inheriting the image default forever (the issue text said "eight windows"; it
  was 11 by the time this landed — ent#433 added two, #2216 a third).

* Ordering. It MUST run after _seed_fresh_install_retention. Both writers are
  insert-or-ignore, so the first to reach a key wins: reversed, a fresh install
  silently gets the wide defaults instead of the #1039 floor — the community
  floor deleted by the change meant to protect retention. Pinned behaviourally
  and by a source-order guard on both the SQLite and engine arms.

* It must actually run. The first cut imported the constants from
  services.settings_service, which has a module-level `from database import db`.
  init_database() is called from DatabaseManager.__init__, i.e. while database.py
  is still executing its own module body, so database.db does not exist yet and
  that import raises ImportError — which this seed's fail-safe contract then
  SWALLOWS. The feature was dead on every boot with a fully green unit suite,
  because every in-process test calls the function after database has finished
  importing. RETENTION_OPS_KEYS, OPS_SETTINGS_DEFAULTS and
  NON_ROW_RETENTION_OPS_KEYS therefore move to config.py (a leaf, already home to
  OPS_SETTINGS_VALIDATION and validate_ops_setting for these same keys) and are
  re-exported from settings_service, extending the pattern
  COMMUNITY_FRESH_INSTALL_SEED already used for exactly this reason. Two tests
  now pay for a real subprocess import; both fail if the import is reverted.

Stated tradeoff: a seeded install stops inheriting later changes to the code
default in EITHER direction, so widening a window for existing installs becomes a
deliberate migration rather than something that arrives silently with an image.
That is the intended consequence — retention becomes explicit per-install config
instead of implicit inheritance from whatever image happens to be running,
symmetric with the rule the OPS_SETTINGS_DEFAULTS comment already imposes on
narrowing.

backup_retention_days is seeded too. That makes OPS_SETTINGS_DEFAULTS' value the
one that lands in the DB for a key whose private reader
(db_backup_service.effective_backup_retention_days, inverted coercion) falls back
to its own module constant; the two are now parity-tested.

No schema change, no migration — row inserts at boot, same as the #1638 seed.

Not fixed here: generic DELETE /api/settings/{key} carries no RETENTION_OPS_KEYS
guard (only PUT does), so an admin can still delete a window row. After this it is
transient — the next boot re-seeds it — but the asymmetry with PUT remains.

Unblocks ops#300 once deployed: with rows on every install, /update step 8e can
drop its source-text guessing for a plain assertion over stored values.

Closes #2085

* fix(watchdog): stop false-orphaning executions parked before the agent spawns them (abilityai/trinity#2433) (#2435)

* fix(watchdog): stop false-orphaning executions parked before the agent spawns them

The cleanup watchdog's proof-of-life (GET agent/api/executions/running:
running ∪ recently-completed) could not see an admitted execution that was
waiting in the backend's global agent-call queue, in the agent's CPU-sized
default thread pool, behind the agent chat lock, or in the post-exit drain
before unregister(). After the 60s grace it wrote a false `failed`
("completed on agent but status not reported"), released the slot, and the
parked call then ran anyway — billed, overbooked, its late 200 silently
overwriting the row (#378). Reproduced twice locally; three mechanisms, one
string.

Orphan now means: the agent does not know the execution AND no live backend
dispatcher owns it.

- agent server: /api/executions/running gains `pending_ids` (accepted at
  /api/task, /api/chat and the #1083 async spawn but not yet spawned; lazily
  expired) and `recently_completed_ids` covers exited-but-registered handles.
  Cancel-while-pending is consumed by register() (SIGKILL at spawn, #679 marker
  kept); the pre-spawn 409 is only an optimisation. Headless runs use a
  dedicated 32-thread pool pinned to MAX_PARALLEL_TASKS_CEILING_MAX; the Gemini
  runtime now registers its subprocess at both Popen sites (it never did).
- backend: every outbound agent call is registered for its whole lifetime
  (track_inflight_dispatch — queue wait, connect retries, POST) in an
  in-process registry plus a cross-worker Redis liveness marker
  execution:inflight:{id} (60s TTL, one refresher task per process, 15s tick).
  The watchdog reads a tri-state verdict (alive / absent / unknown) and
  withholds recovery on `alive`, and on `unknown` only while a dispatcher could
  still own the row; a process with no Redis reads `absent` (its own registry
  is the whole truth). CleanupReport.dispatch_inflight_skipped counts withheld
  rows; the orphan error string states what was observed.
- a park no longer spends the run's budget: at grant, a park ≥ 5s restamps
  started_at (admission kept in queued_at, the drained-backlog shape, CAS on
  RUNNING + NULL lease) and renews the slot lease (ZADD XX + EXPIRE together);
  the refresher renews the slot every tick while parked.
- parked rows are cancellable and agent-scoped: terminate consults the
  in-process registry, then the cross-worker cancel key; a parked phase is
  finalized CANCELLED and the grant raises BackendAgentCallCancelled, where the
  dispatcher writes CANCELLED itself (never FAILED; the /chat arm answers 409).
- terminate_execution gains ONE agent-scope gate at its entry for all three
  arms: the row behind the caller-supplied task_execution_id must belong to the
  agent the route proved (uniform 404; an unreadable row fails closed with
  503). The proxy arm's 404 scoped only execution_id while the CANCELLED CAS
  was keyed on task_execution_id, so a caller authorised on agent A could flip
  agent B's running row (found by the /cso --diff verifier; report under
  docs/security-reports/).
- packaging: BACKEND_AGENT_CALL_LIMIT / BACKEND_AGENT_CALL_QUEUE_TIMEOUT_S
  forwarded in prod + hosted compose and documented in .env.example; the >5s
  queue-wait warning fires on both acquire branches.

Verified: full unit suite under CI conditions 12969 passed / 0 failed
(baseline origin/dev 12863 / 0); Repro A 10/10 success (2 parked 485s,
withheld at both watchdog cycles, re-anchored at dispatch); Repro B 8/8
success (5 parked, two waves); live pending_ids probe on the agent. The
agent-side half needs a rebuilt base image; the backend half alone covers old
images through the whole-call marker.

Fixes abilityai/trinity#2433

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(watchdog): close the cross-worker cancel race and bound the exited-but-registered set (#2435 review)

Review of the #2433 fix found that it reintroduced the #378 symptom in a
narrower window and turned a pre-existing registry leak into a permanent one.

1. Cross-worker cancel acted on a marker phase that predated its own write.
   `entry.phase` flipped parked->calling in memory only; the marker was
   rewritten by the 15s refresher, so `execution:inflight:{id}` advertised
   `parked` for up to a full tick after the POST had begun. Under --workers 2
   about half of all cancels are served by the worker that does NOT own the
   coroutine and therefore read it: the row was finalized CANCELLED and its
   slot released while the agent ran the turn to a billed completion whose
   SUCCESS then lost the CAS. Closed by ordering, not by narrowing — the owner
   publishes the transition in the SAME round-trip that reads the cancel key
   (`_publish_calling_and_check_cancel_sync`), and the remote sets the cancel
   key BEFORE re-reading the phase (`_set_cancel_then_reread_phase_sync`), so
   an observed `parked` gives W_remote(cancel) < R_remote(marker) <
   W_owner(marker) < R_owner(cancel) and the grant is guaranteed to see the
   key. Neither side pays an extra round-trip. The owner gates the publish on
   the ENTRY's age rather than this attempt's park, because
   `track_inflight_dispatch` wraps the whole retry loop and a retry can grant
   instantly under a marker a tick left saying `parked`; the remote's scope
   check stays on its first read, so no key is written for a foreign agent.

2. `list_recently_completed_ids` reported exited-but-registered ids with no
   age bound, so a leaked entry was agent-known forever and the watchdog never
   recovered that row — a regression against pre-#2433, where `list_running()`
   self-healed it. Now bounded by the same 300s TTL as the buffer, measured
   from when the exit was first OBSERVED (not `started_at`, which would drop a
   long turn the moment it entered its drain). The leak is also closed at
   source: `register()` SIGKILLs the group for a cancel that arrived while
   pending, so the following `stdin.write` can raise BrokenPipeError — all
   three prompt-writing runtimes (claude_code, gemini x2) now pair that write
   with `unregister()` on failure.

3. `restamp_execution_dispatch` is a sync sqlite write and ran on the event
   loop, while both semaphores are held and the queue is by definition
   congested. Now `asyncio.to_thread`, like the slot renewal beside it.

Smaller items from the same review:
- /api/chat sizes its pending entry to PENDING_CHAT_TIMEOUT_SECONDS (7200s):
  `ChatRequest` carries no timeout and a chat can wait on the execution lock
  for the agent's whole budget, so the /api/task default evicted the entry
  mid-wait. Its discard now wraps the lock acquisition, so a request cancelled
  while waiting (client disconnect) cannot leak one.
- Phase 3 batches its in-flight verdict read (one MGET per cycle, not per row),
  matching Phase 0.
- `renew_slot` refuses, score untouched, when the metadata hash has already
  expired: `ZADD XX` succeeds while `EXPIRE` no-ops, so it used to report a
  renewal it had not performed and re-anchor exactly the ZSET-without-hash
  state canary S-03 calls `missing`.
- `register_pending` logs at DEBUG (it fires on every /api/task and /api/chat).
- Documented that the in-flight marker is not eviction-proof under the prod
  `allkeys-lru` policy.

Tests: tests/unit/test_2433_review_fixes.py (15) — 11 of them fail against
cfc2cfef, verified in a worktree. Full unit suite under CI conditions
(clean origin/dev worktree, no submodules): 12985 passed, 0 failed.

Refs abilityai/trinity#2433

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>

* test(resume): the guard architecture.md promised did not exist (ent#430 review)

The reviewer's one condition before merge. `architecture.md`'s 'Two callers,
one rule' bullet said the CAS-win rule was 'guarded now by enumerating every
caller rather than the one route ent#329 knew about, so a third site inherits
the rule instead of re-losing it'. No such guard existed:
`test_dispatch_hangs_off_the_cas_win_only` read exactly one hardcoded file,
`routers/operator_queue.py` — so `client_portal/asks/service.py`, the caller
this PR adds and the one that LOST the rule, was outside its reach.

A sentence claiming protection that is not there is worse than no sentence: the
next person adding a dispatch site reads it and stops looking. This is the shape
#2428 filed a learnings entry about this morning — a comment that names a
failure mode is a request for a guard — so it lands the same way.

DISCOVERED, NOT LISTED. `_dispatch_call_sites` walks the backend tree for
callers, because a hardcoded list structurally cannot catch the case that
matters: the file it would need to check is the one being added.

ASSERTED AGAINST CODE, NOT FILE TEXT — and this is the part I got wrong first.
The initial version tested `"_status_conflict" in source` against the raw file
and MUTATION PROVED IT BLIND: deleting the check from the `if` still passed,
because the long comment above it explaining the race still contained the
string. A source-substring guard cannot tell a check from a paragraph about the
check — the same defect the guard exists to prevent, inside the guard. It now
parses each dispatching function and compares `ast.unparse` output, where
comments do not survive.

Verified by three mutations, each caught:
  1. delete the check in asks/service.py, keep the comment  -> FAIL
  2. neuter the check in routers/operator_queue.py          -> FAIL
  3. add a brand-new third caller with no check at all      -> FAIL
and all 23 pass on the real tree.

`test_the_discovery_walk_finds_both_known_callers` pins the floor, so a rename
of the helper cannot leave the loop iterating an empty list and passing in
silence — the failure a discovery guard trades for the one it fixes.

ALSO (non-blocking, from the same review): `WorkspaceAsk.status`'s comment still
read 'pending | expired (terminal ones are not listed)' after `_status_of`
gained a third value. Corrected to say where each value is reachable from.

The remaining non-blocking item — `resume_requested` and the new `answered`
status are unconsumed by any surface — is deliberately NOT in this commit. It is
a product decision about where a transient confirmation lives, and it is filed
so it stays a decision rather than becoming an oversight.

Related to abilityai/trinity-enterprise#430
Related to abilityai/trinity-enterprise#329

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(systems): the four post-deploy endpoints — a nonexistent DB call, an ungated restart, a broken export round-trip, and prefix-collision membership (#2373)

The deploy half has been hardened by every commit since ent#124; the four
post-deploy endpoints were essentially untouched since 2025.

## Membership is now ONE predicate

`get_system`, `restart_system` and `export_manifest` each matched
`startswith(f"{system_name}-")`, so an operation on `acme` also captured every
agent of a system named `acme-extra` — including `restart`, which stops and
starts containers. Three copies of a wrong rule.

`system_service.system_member_names` is the one rule, and it prefers TAGS:
`configure_tags` already applies the system name to every member, so a tag is a
RECORD of membership where a prefix is an inference from a naming convention.
The prefix survives only as a fallback for pre-tag deployments, narrowed so an
agent claimed by another system's own tag is excluded — a tagged `acme-extra`
agent is never captured by `acme` even there. A failing tag read degrades to the
prefix rather than 500ing.

Residual, stated rather than hidden: two systems deployed BEFORE tagging where
one name is a prefix of the other remain ambiguous, because nothing distinguishes
them. This is also the prerequisite for the teardown verb, where the same
collision would delete rather than restart.

## GET /{name} returns real schedules

It called `db.get_agent_schedules`, which does not exist — the facade exposes
`list_agent_schedules` and `database.py` deliberately has no `__getattr__`
fallback. The AttributeError was swallowed by the surrounding `except
Exception`, so every response omitted `schedules` for every agent and logged one
warning each, while `tests/test_systems.py` never asserted on the key. Exactly
the failure mode the db facade's own comment warns about — so the test also pins
that the fallback stays absent, since adding one would turn the next typo into a
silent Mock.

## POST /{name}/restart is creator-gated

It was bare `get_current_user` — below `POST /deploy` and below even the
READ-ONLY bundled-catalog routes — so any authenticated principal, including
`role: user`, could stop and start every container in a system whose agents it
could see. A mutating fleet-wide verb under a lighter gate than the catalog it
reads is an oversight, not a decision. `require_role` also rejects agent
principals (#1890), which matters because an agent-scoped MCP key resolves to
its owner carrying the owner's role.

## Export round-trips

The non-full-mesh permissions branch sliced `target_agent[len(name)+1:]` with no
membership filter — the sibling branch had one — so an edge pointing outside the
system exported as a blind-sliced garbage short name that then failed
`validate_manifest`'s unknown-agent check on re-deploy. The export broke its own
round trip. Both branches now test membership.

And the export no longer embeds the instance-global `trinity_prompt` as the
manifest's `prompt:`. Deploying that manifest elsewhere overwrote THAT
instance's platform-wide prompt — a fleet-wide side effect from what reads like
a copy of one system. Nothing records whether the source system ever set a
prompt, so there is no honest way to distinguish it from whatever the instance
happens to have configured, and the only correct export of an unknown is to
omit it.

## Two preview hardenings

Unknown PER-AGENT keys now warn like top-level ones (ent#126): `credentials:`,
`skills:` and `display_label:` are the fields people try first and they vanished
in silence.

Preview and deploy now resolve the identical resource default. Deploy hardcoded
`{"cpu": "2", "memory": "4g"}` while `_preflight_template` validated against the
admin-configurable `get_agent_default_resources()`, so the two disagreed the
moment an admin moved the fleet default — the one spot that escaped ent#126's
pure-resolver no-drift pattern.

## Verification

14 unit tests, one per defect plus the exempt shapes. Two mutation-checked: the
restart gate and the tag-first membership each turn a test red when reverted.
414 pass across the system/manifest/ent#126/#1884 suites.

`tests/test_systems.py` is live-backend tier and…
vybe pushed a commit that referenced this pull request Oct 13, 2026
… it spawned — on the raw backend routes too (trinity-enterprise#629) (#3346)

* fix(auth): an agent key reaches only itself, its edges and the agents it spawned — on the raw backend routes too (trinity-enterprise#629)

An agent-scoped MCP key resolves to its OWNER carrying the owner's role
(Invariant #8), so every access/owner predicate said yes for any sibling the
owner holds — on an admin-owned install, every agent. The agent_permissions
edge the MCP layer checks (P-02) did not exist one hop down: with its injected
key and TRINITY_BACKEND_URL, agent A could chat with, task, loop, read the
history and logs of, or replace the git token of any sibling B. Ruling
(operator, 2026-10-06): fix the hole.

Narrowed in the shared gate, not per endpoint (the #1890 lesson):

- dependencies.agent_may_reach(current_user, target, manage=):
  * use tier — get_authorized_agent[_by_name], assert_agent_access, A2A
    inbound: itself, an edge target, an agent it spawned with its current key;
  * manage tier — get_owned_agent[_by_name], assert_agent_owner: itself or an
    agent it spawned. An edge means "may call", never "may manage".
  Outside its reach reads as the uniform 404 (#186). Every other principal is
  unchanged. The edge read fails closed, like the MCP layer's.
- get_skill_managed_agent_by_name keeps the plain owner fence: skills.manage
  (ent#596) IS the grant to manage the owner's other agents.
- Every inline can_user_access_agent / can_user_share_agent call (16 files)
  ANDs the reach in; nevermined's admin shortcut no longer skips it.
- The operator queue had its own predicate (admin role → no filter): an agent
  key now always gets a set narrowed to its reach.
- MCP: every `baselined: ENT629` row in TOOL_ACCESS_POLICY is `enforce` on its
  agent parameter; the "tool-surface gate only" notes now name the backend fence.

Collection reads (the agent list, event-subscription list, MCP key list) are
not narrowed: they disclose names, never act on an agent.

Tests: tests/unit/test_ent629_agent_reach.py — the reach truth table on a real
schema, every helper, A2A inbound, the operator queue, the skills capability
keeping its reach, the dispatch routes resolving through the narrowed gate,
and an AST guard that fails the build on an inline access check without the
reach (exemptions carry their reason). Mutation-checked: reach always-true,
edge-as-manage, the access dependency dropping it, and an inline site
dropping it each turn tests red.

Docs: Invariant #8, security.md §5, P-02, the J10 docstring, mcp-server.md
and the affected feature flows and requirements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(auth): keep skills.manage's owner-wide reach through the files tab; regression fixes (trinity-enterprise#629)

From the regression run over every unit file touching a changed module
(14 new failures vs dev, all traced):

- The skill fence's owner check is its own seam again,
  `get_capability_owned_agent_by_name` (not narrowed: the capability is the
  grant), so the ent#596 recorder patches a named function.
- files.py: a skills.manage holder writing a sibling's skills path reaches it
  without an edge (`_may_reach_for_path`); every other path is narrowed. The
  capability gate still decides the write.
- share_agent_file checks "an agent key shares only its own volume" before the
  (now narrowed) owner gate, so a sibling gets the specific refusal.
- The depth suites (#2806, #2973) seed the A→B edge their sibling calls need.
- The edge read fails closed (a fixture schema without agent_permissions
  refused instead of raising — the enterprise assignment suites).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(operator-queue): an agent key's queue scope is {self} ∪ edges ∪ spawned, read directly (trinity-enterprise#629)

dev's ent#611/#715/#815 queue suites (29 tests) went red after the merge:
an admin-owned agent key's scope was built from the owner's
accessible-agent list and then filtered agent by agent, so a self or
permitted agent without an ownership row (every one in those fixtures)
dropped out. The scope now starts from {self} ∪ the agent's edges — the
MCP's own rule — bounded by a non-admin owner's set, plus the owner's
agents it spawned. The edge read fails closed. The router also gets the
logger it was missing.

ent#715's heads-ups fixture seeds the agent key's edge to the agent it
reads, so the test still checks that person rows are withheld, not that
the whole queue is refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(auth): a capability earns reach per request, not per holder (trinity-enterprise#629)

Merge-train review (2026-10-08, 2026-10-10): the narrowed gate revoked the
cross-agent reach that ent#164 capabilities exist to grant. A
`schedules.manage` holder got 404/403 on a sibling's schedule routes, an
`instructions.manage` holder on its instruction files and git reset, and an
`agents.manage` holder on `PUT /{name}/model`, because `agent_may_reach`
never saw which capability the route had checked.

- The two capability fences (`capability_fence`,
  `require_person_or_capability`) record the target they admitted on the
  request's principal (`User._capability_reach`, a private attribute), after
  the grant check and the owner bound. `agent_may_reach` honours that record
  on both tiers. This replaces `_manages_owners_agent`, which widened every
  owner check for an `agents.manage` holder on every route.
- `files._may_reach_for_path`: the path exception covers `instructions.manage`
  as well as `skills.manage`, needs the grant for each file class the path
  touches, and is bounded to agents the owner OWNS (`owner_owns_agent`). It
  used to reach any agent the owner could access.
- `loops._check_loop_access`: reach is checked before the admin and
  initiator shortcuts, so an agent key cannot read or stop a sibling's loop
  by id.
- Operator queue: the spawned set is one query
  (`list_agents_spawned_by_key`), not two lookups per held agent.

Also merges dev: the agents.py activity routes stay deleted (#3483), and
access.ts takes dev's owner constants alongside this PR's enforce rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(mcp): a backend refusal of the loop read is the uniform loop refusal (trinity-enterprise#629)

J10 `test_without_permission_an_agent_cannot_read_or_stop_a_loop_on_another`
failed on journey-smoke. Since the backend checks an agent key's reach before
the admin shortcut in `_check_loop_access`, `GET /api/loops/{id}` answers 403
for a loop on an agent outside the caller's reach. `get_loop_status` and
`stop_loop` resolve the loop through that read before their own gate, so the
caller got a raw `API error (403)` instead of "Loop '<id>' not found or not
accessible" and the hint.

A 403 on the read now returns the same uniform body as the MCP gate, with the
same log line and audit row. The stop is still never sent. A 404 (no such
loop) keeps the backend's own shape, as the existing test pins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(credentials): an agent key gets the human-only refusal before the owner fence (trinity-enterprise#629)

The backend regression diff caught 4 new failures in
`test_3435_credential_tool_gates::test_agent_key_is_refused_human_only_even_for_its_owner`.
With the narrowed owner fence, `get_owned_agent_by_name` answers an agent key
on a sibling with the uniform 404, so the handler-body
`reject_agent_principal` never ran. The agent was told "Agent not found"
instead of the rule it hit.

`dependencies.human_only` is the route-level form of `reject_agent_principal`.
On export and import it now runs before the ownership dependency. The refusal
depends on the principal alone, before any lookup, so it discloses nothing
about the target (#186). The inline call stays as belt-and-braces.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(auth): one owner bound per capability, a DB-decided MCP edge, and the #3346 review (trinity-enterprise#629)

Addresses webmixgamer's review of f9cd838.

1. `skills.manage` reached another user's agent through the skills routes on
   an admin-owned install. `get_skill_managed_agent_by_name` went through the
   unnarrowed owner fence, which `can_user_share_agent` answers True for any
   agent when the owner is admin; the files tab refused the same target. The
   skills fence now applies the bound every capability fence applies (grant,
   then `owner_owns_agent`, then record the reach) and returns the narrowed
   `get_owned_agent_by_name`. `can_manage_agent_skills` takes the same bound.
   The skill-gate writes use `get_owned_agent_by_name` (`_gate_writer`
   records first), so `get_capability_owned_agent[_by_name]` and
   `_owned_agent_or_404(narrow=False)` are gone: one mechanism.
2. The MCP `enforce` gate read the lenient permissions list, which is built
   from the Docker-filtered fleet. A ghost with no container, a child being
   recreated, a spawned child whose edge was removed, and every call during a
   Docker fault all read as "not permitted". New
   `GET /api/agents/{caller}/reach/{target}` answers from the edge or the
   spawn record in the database; `TrinityClient.isAgentPermitted` reads it
   and fails closed.
3. security.md no longer says collection reads "disclose names, never act":
   fleet-level routes still answer an agent key with its owner's reach, some
   of them write, and some return task text and emails. A private follow-up
   tracks them.
4. Tests for the review's surviving mutations:
   - credential export's `human_only`;
   - the queue's non-admin bound;
   - `deleted_at` in the spawned set;
   - a schedules holder through the real route via TestClient (same principal
     object for the fence and the path dependency);
   - another user's agent on the skills fence;
   - the reach endpoint.
   Each mutation now fails a test.
5. An agent key never gets the admin "every user" chat history or sessions
   view: "may call" is not "may read everyone's conversations with it".

Also: learnings fragment (capability bound in one helper).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(ent754): the gate-map world records who owns the gated agent (trinity-enterprise#629)

The backend regression diff caught
`test_probe_is_a_persons_even_for_a_key_that_may_manage_skills[agent_key_with_skills_manage]`.
Since the #3346 review, an agent key's `skills.manage` reaches only agents its
owner OWNS (`owner_owns_agent`), not every agent `can_user_share_agent`
admits. The fixture stubbed "may share" but never said who owns
`gated-agent`, so the bound read "unknown owner" and refused. The test's
premise is unchanged: the key's owner owns the agent, so the manage check
admits it and the probe is still refused for a key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants