Repository navigation
Add internal health route, without which main didn't start - #14
Merged
Merged
Conversation
This was referenced Apr 25, 2026
vybe
added a commit
that referenced
this pull request
Apr 30, 2026
- Update requirements.md req 16.1 with RES-001 system-defaults description - Add GET/PUT /api/settings/agent-defaults/resources to architecture.md - Move AgentDefaultResourcesUpdate from settings.py to models.py (Invariant #14) Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
vybe
added a commit
that referenced
this pull request
Apr 30, 2026
* feat(resources): add system-wide agent CPU/memory defaults with per-agent override Adds GET/PUT /api/settings/agent-defaults/resources (admin-only) so instance admins can set fleet-wide CPU (number of processors) and memory limits. Container creation falls back: per-agent DB limit → system default → hardcoded. Also fixes pre-existing '4Gi' → '4g' bug in crud.py (Docker rejects IEC suffix) and tightens the fallback ordering in lifecycle.py to include system defaults. Fixes #611 Co-Authored-By: Claude <[email protected]> * docs(feature-flows): update agent-resource-allocation with RES-001 system defaults Co-Authored-By: Claude <[email protected]> * fix(resources): address PR #613 review — docs and model placement - Update requirements.md req 16.1 with RES-001 system-defaults description - Add GET/PUT /api/settings/agent-defaults/resources to architecture.md - Move AgentDefaultResourcesUpdate from settings.py to models.py (Invariant #14) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> --------- Co-authored-by: Claude <[email protected]>
9 tasks done
This was referenced May 11, 2026
dolho
added a commit
that referenced
this pull request
May 18, 2026
Addresses PR #840 review (vybe, CHANGES_REQUESTED); rebased onto the updated #839/#838. - Move SoftDeletedAgent / SoftDeletedSchedule from routers/admin_recovery.py to models.py (Architectural Invariant #14 — response models are centralized, not declared in router files). - Cap limit on both list endpoints: limit: int = Query(200, le=500) — prevents unbounded DB reads (422 on >500). - requirements.md: §32.3 fleshed out (endpoints, recovery semantics, metadata-only/container-recreate-is-Phase-2, audit events, model location). - architecture.md: new "Soft-Delete Admin Recovery (#834 Phase 1c)" endpoint table with all 4 endpoints, auth, and behavior notes. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
dolho
added a commit
that referenced
this pull request
May 20, 2026
Addresses PR #840 review (vybe, CHANGES_REQUESTED); rebased onto the updated #839/#838. - Move SoftDeletedAgent / SoftDeletedSchedule from routers/admin_recovery.py to models.py (Architectural Invariant #14 — response models are centralized, not declared in router files). - Cap limit on both list endpoints: limit: int = Query(200, le=500) — prevents unbounded DB reads (422 on >500). - requirements.md: §32.3 fleshed out (endpoints, recovery semantics, metadata-only/container-recreate-is-Phase-2, audit events, model location). - architecture.md: new "Soft-Delete Admin Recovery (#834 Phase 1c)" endpoint table with all 4 endpoints, auth, and behavior notes. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
dolho
added a commit
that referenced
this pull request
May 21, 2026
Addresses PR #840 review (vybe, CHANGES_REQUESTED); rebased onto the updated #839/#838. - Move SoftDeletedAgent / SoftDeletedSchedule from routers/admin_recovery.py to models.py (Architectural Invariant #14 — response models are centralized, not declared in router files). - Cap limit on both list endpoints: limit: int = Query(200, le=500) — prevents unbounded DB reads (422 on >500). - requirements.md: §32.3 fleshed out (endpoints, recovery semantics, metadata-only/container-recreate-is-Phase-2, audit events, model location). - architecture.md: new "Soft-Delete Admin Recovery (#834 Phase 1c)" endpoint table with all 4 endpoints, auth, and behavior notes. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
dolho
added a commit
that referenced
this pull request
May 21, 2026
Addresses PR #840 review (vybe, CHANGES_REQUESTED); rebased onto the updated #839/#838. - Move SoftDeletedAgent / SoftDeletedSchedule from routers/admin_recovery.py to models.py (Architectural Invariant #14 — response models are centralized, not declared in router files). - Cap limit on both list endpoints: limit: int = Query(200, le=500) — prevents unbounded DB reads (422 on >500). - requirements.md: §32.3 fleshed out (endpoints, recovery semantics, metadata-only/container-recreate-is-Phase-2, audit events, model location). - architecture.md: new "Soft-Delete Admin Recovery (#834 Phase 1c)" endpoint table with all 4 endpoints, auth, and behavior notes. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
dolho
added a commit
that referenced
this pull request
May 21, 2026
Addresses PR #840 review (vybe, CHANGES_REQUESTED); rebased onto the updated #839/#838. - Move SoftDeletedAgent / SoftDeletedSchedule from routers/admin_recovery.py to models.py (Architectural Invariant #14 — response models are centralized, not declared in router files). - Cap limit on both list endpoints: limit: int = Query(200, le=500) — prevents unbounded DB reads (422 on >500). - requirements.md: §32.3 fleshed out (endpoints, recovery semantics, metadata-only/container-recreate-is-Phase-2, audit events, model location). - architecture.md: new "Soft-Delete Admin Recovery (#834 Phase 1c)" endpoint table with all 4 endpoints, auth, and behavior notes. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
vybe
pushed a commit
that referenced
this pull request
May 21, 2026
Addresses PR #840 review (vybe, CHANGES_REQUESTED); rebased onto the updated #839/#838. - Move SoftDeletedAgent / SoftDeletedSchedule from routers/admin_recovery.py to models.py (Architectural Invariant #14 — response models are centralized, not declared in router files). - Cap limit on both list endpoints: limit: int = Query(200, le=500) — prevents unbounded DB reads (422 on >500). - requirements.md: §32.3 fleshed out (endpoints, recovery semantics, metadata-only/container-recreate-is-Phase-2, audit events, model location). - architecture.md: new "Soft-Delete Admin Recovery (#834 Phase 1c)" endpoint table with all 4 endpoints, auth, and behavior notes. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
vybe
pushed a commit
that referenced
this pull request
May 21, 2026
* feat(soft-delete): admin recovery endpoints for agents + schedules (#834 Phase 1c) Closes the user-facing side of the soft-delete story. Pre-#834 recovery was a direct-DB `UPDATE deleted_at = NULL` — unauditable, required shell access, soft-deleted set wasn't surfaced anywhere. Endpoints (admin-only, all audit-logged): GET /api/admin/soft-deleted/agents list soft-deleted agents with `deleted_at` + `purge_eta` (= deleted_at + agent_soft_delete_retention_days) POST /api/admin/soft-deleted/agents/{name}/recover clear deleted_at; 404 if not in the soft-deleted set GET /api/admin/soft-deleted/schedules[?agent_name=...] list soft-deleted schedules; purge_eta from schedule_soft_delete_retention_days POST /api/admin/soft-deleted/schedules/{id}/recover same shape as the agent variant Recovery is metadata-only: flipping deleted_at back to NULL makes the row reappear via all the user-facing read paths Phase 1a+1b filtered. For agents, the container is NOT recreated automatically; the operator does that explicitly via POST /api/agents/{name}/start. The preserved workspace volume keeps the agent's files intact. DB helpers (mirror Phase 1a/1b shape): - AgentOperations.recover_agent_ownership / list_soft_deleted_agents - ScheduleOperations.recover_schedule / list_soft_deleted_schedules (latter takes optional agent_name to scope per agent) All four refuse live rows (returns False / 404). All return False for nonexistent ids — admin endpoint translates to 404. Stacked on #839 (Phase 1b schedules). Stack: #838 (1a) → #839 (1b) → this (1c). Merge order matters because the schedule helpers live on Phase 1b's branch. Live verification on the running stack: 1. CREATE agent + schedule, soft-delete both 2. GET /api/admin/soft-deleted/agents → match found, purge_eta=2026-11-10 (180d from now) 3. GET /api/admin/soft-deleted/schedules?agent_name=X → 1 row, purge_eta=2026-06-13 (30d from now) 4. POST recover agent → 200, deleted_at cleared in DB ✓ 5. POST recover schedule → 200, deleted_at cleared ✓ 6. POST recover on now-live agent → 404 (correct refusal) ✓ 10 unit tests in test_admin_recovery.py cover: recover/list/scope, refuse-live-row, refuse-nonexistent, newest-first ordering, limit handling, agent_name scoping. Related to #834. Phase 1c. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(recover): make recovered agents visible + honest message (#834 Phase 1c) Smoke-testing the rebased stack on the live instance surfaced a recovery dead-end: 1. `GET /api/agents/{name}` 404'd after a successful recover. The handler resolves the agent via `get_agent_by_name` (Docker-backed); soft-delete removed the container and recovery is metadata-only, so there's no container → 404. The operator literally could not see the agent they just recovered, let alone act on it. Recovery was pointless from the UI's perspective. Fix: when `get_agent_by_name` returns None but a live agent_ownership row exists (the auth dependency already proved it does — `get_agent_owner` filters `deleted_at IS NULL`), synthesize a DB-backed `status=stopped, needs_start=true` representation so the agent lists and the UI can offer a Start affordance. 2. The recover endpoint's success message claimed "POST /start to bring it back online" — but Start also 404s on a container-less agent (it too requires an existing container). Container recreate from the preserved workspace volume is the explicitly-deferred #834 Phase 2. Rewrote the message to be accurate: recovery restores all *relational* state (the hard-to-recreate part that #834 exists to protect); re-running the agent needs Phase 2. Added `needs_container_recreate: true` to the response. What recovery delivers today (correct + tested): the agent_ownership row, chat history, schedules, sharing, permissions, credentials config — every relational artifact — comes back intact and visible. What it doesn't (Phase 2): a runnable container. Live-verified on the running stack: create → soft-delete (GET 404) → recover (200) → GET now 200 with needs_start=true → agent visible. Start still 404s by design until Phase 2; message + flag now say so. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(recover): centralize models + cap limit + docs (#834 Phase 1c) Addresses PR #840 review (vybe, CHANGES_REQUESTED); rebased onto the updated #839/#838. - Move SoftDeletedAgent / SoftDeletedSchedule from routers/admin_recovery.py to models.py (Architectural Invariant #14 — response models are centralized, not declared in router files). - Cap limit on both list endpoints: limit: int = Query(200, le=500) — prevents unbounded DB reads (422 on >500). - requirements.md: §32.3 fleshed out (endpoints, recovery semantics, metadata-only/container-recreate-is-Phase-2, audit events, model location). - architecture.md: new "Soft-Delete Admin Recovery (#834 Phase 1c)" endpoint table with all 4 endpoints, auth, and behavior notes. Related to #834 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
6 tasks done
This was referenced Jun 9, 2026
7 tasks done
7 tasks
vybe
added a commit
that referenced
this pull request
Jun 19, 2026
…#1149) Surface per-schedule performance on the Overview tab and the Schedules tab, both from a SINGLE compact aggregate (no N per-schedule round-trips) — extends #1107 (Overview) and generalises #868 (per-schedule deep analytics). Backend: - db `get_agent_schedules_summary(agent, hours)` — one rollup row per non-deleted schedule (zero-run schedules included): terminal success_rate (success / (success + failed[incl. error]); None when zero terminal), NULL-skipping avg_duration_ms, cost_total, context_avg, tool_call_total (parsed over newest 5,000 rows agent-wide, tool_calls_sampled flag), and last-run outcome. Cheap grouped SQL; iso_cutoff window (Invariant #16). - GET /api/agents/{name}/schedules/analytics-summary?window=7d|14d|30d (AuthorizedAgent). Declared BEFORE /{schedule_id} in routers/schedules.py so the literal segment isn't captured as a schedule_id (Invariant #4) — putting it in analytics.py would be shadowed (schedules_router mounts first). - models: ScheduleSummaryRow + AgentSchedulesSummaryResponse (Invariant #14). Frontend (single fetch, two consumers — Invariant #7): - executions.js fetchSchedulesSummary, cached per ${name}:${window} like fetchAgentAnalytics. - OverviewPanel: "Schedules performance" section, honors the existing 7/14/30d window selector, each row deep-links to the Schedules tab; hidden at zero. - SchedulesPanel: inline mini-stats per row (success rate, avg duration, runs, last-run dot) — badge style, no new chart/modal — from the same call. Tests: tests/unit/test_1115_schedules_summary.py (6) — terminal success rate, NULL-skip avg, tool-call total, zero-run-still-appears, soft-delete excluded, out-of-window excluded. Full analytics suites green (30 passed). Frontend prod build clean; endpoint verified live across 7/14/30d windows. Related to #1115 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
AndriiPasternak31
added a commit
that referenced
this pull request
Jun 23, 2026
…-14, #654) Move 97 request/response BaseModel classes from 32 routers into src/backend/models.py (Architectural Invariant #14), plus the fan_out / loops / webhooks module-level constants their validators reference. Each class moved verbatim — validators, default_factory, and Config preserved. Behaviour preserved, proven two ways the move could silently break it: - Normalized app.openapi() snapshot diff: 330 paths / 198 schemas, byte-identical origin/dev vs branch (schema-level proof). - Validator-preservation unit tests for the 5 behaviour-bearing files (fan_out, loops, canary, audit_log, schedules) — the field_validator logic, default_factory dicts, and Config.from_attributes an OpenAPI diff can't see. One documented exception, allowlisted in the new static guard: canary.py::RunCycleRequest evaluates INVARIANTS (the canary library) in a Field(description=...) at class-definition time, and the canary library imports TaskExecutionStatus back from models — relocating it would force models.py to `from canary import ...`, inverting the dependency direction of a module meant to be a low-level leaf everything imports from. Flat models.py (not a package): a models/ dir would break tests/conftest.py's by-file model preload and the Dockerfile's by-file COPY *.py (the #1033 crash-loop class). Scope is router models only — db_models.py and adapters/base.py are intentional separate homes. New / changed: - tests/unit/test_models_centralized.py: static guard (no BaseModel under routers/ except the documented allowlist) + planted-violation tests - tests/unit/test_router_model_validators.py: validator / default_factory / Config preservation negatives - tests/unit/test_telegram_webhook_backfill.py: load the real models module in the standalone settings.py stub (was already red on dev) and stub the #1197 services.agent_service.capabilities import -> green - docs/memory/architecture.md: Invariant #14 scope note + re-measured router/service/agents counts Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
AndriiPasternak31
added a commit
that referenced
this pull request
Jun 23, 2026
- feature-flows.md: Recent Updates row for the router-model centralization (Invariant #14), noting behavior-preserved / OpenAPI-byte-identical and the documented canary.RunCycleRequest allowlist exception. - security-reports: CSO --diff report for PR #1308 (37 files); zero findings across all categories. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
7 tasks done
obasilakis
added a commit
that referenced
this pull request
Jul 31, 2026
…on (ent#237) Adds the REST surface for multi-source: list, create, update, delete, and per-source sync, plus the SkillSourceCreate/SkillSourceUpdate models in models.py (invariant #14). Every MUTATING route carries `reject_agent_principal` in ADDITION to `require_admin`, and that is load-bearing, not padding. `require_admin` answers "what role", never "is this a human": 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 satisfies it (ent#293 — the third occurrence after trinity-ops-agent#232 → #1644 → #1816). Registering a source is the GRANT action from the learnings.md grant-vs-use distinction: it decides which repo the fleet executes code from, and skills are instructions Claude follows. A prompt-injected agent able to add its own source would get unattended, fleet-wide, persistent prompt injection — the exact chain ent#293 documents, reopened through a new door. ent#237 removes that issue's step-1 target (`skills_library_url`), so shipping these routes with only `assert_admin` would have re-created the hole it closes. Reading and syncing an already-configured source is USE, so those stay role-gated only. Other boundary decisions: * `is_default` is absent from BOTH models — a caller must not be able to claim the bundled source's trust posture (tag-pinned, ours to bump) for an arbitrary repo. The db layer refuses it too, so adding the field back here cannot silently start working. * the SSRF allowlist (#179) runs on write, so a bad URL is rejected at the boundary instead of surfacing later as a recurring sync failure * distinct 409s for duplicate-(url,ref) vs default-already-exists, so the UI can say which * audit is best-effort — a logging failure must not undo a completed write * list is admin-only because the rows carry repo URLs, which for a private source are themselves sensitive; the per-agent Skills tab gets `source_name` from GET /skills/library instead, which exposes no URLs Tests pin the gate statically (an integration test needs a live app + DB, and this must fail the moment a new mutating route lands without it) plus a guards-the-guard test that fails on any unreviewed POST/PUT/DELETE under /skills/sources. Mutation-verified: dropping the call from one handler fails exactly one test. Also fixes a leaky test: the adoption tests assigned `ss.get_skills_library_url` directly instead of via monkeypatch. Since skill_service imports those getters by value, the assignment persisted for the whole session and made every later sync adopt the fixture repo as an extra source — surfacing as unrelated failures once random ordering moved them. 46 tests now pass on three consecutive randomized orderings. Refs Abilityai/trinity-enterprise#237
7 tasks done
obasilakis
added a commit
that referenced
this pull request
Aug 5, 2026
…per-instance custom repos (Abilityai/trinity-enterprise#237) (#1901) * feat(skills): skill_sources data model + per-assignment source (ent#237) Replaces the single `skills_library_url` setting with a `skill_sources` table: one row per git repo the library syncs from, so an install can carry the bundled community catalog AND its own repo(s) at once. Two AC-flagged design decisions are encoded here: * Custom-wins precedence, bare names (AC#4). Resolution is `priority` ASC then `created_at` ASC; custom sources default to 100 and the bundled source to 1000. Names stay bare because the agent-side identity IS the directory `.claude/skills/<name>/`, and both the ent#139 runner and the ent#178 A2A card resolve by bare name — prefixing would change every agent's invocation string and require a fleet-wide re-inject. `agent_skills.source_id` RECORDS which source a name resolved to (so a cross-source swap is detectable) but is deliberately not part of the UNIQUE, which would permit two rows that cannot coexist on disk. * Branch-vs-tag refs (AC#5). `ref`/`ref_type` let the bundled source pin to a tag while custom sources track a branch. At most one default source, enforced by a partial-unique index rather than a read-then-write check, so a concurrent second worker loses at the DB. `is_default` is immutable: promoting a custom source would change its trust posture without changing where it points. Deleting a source does not cascade to assignments — the skill keeps resolving by bare name through whatever source still provides it, and cascading would silently unassign skills that are still available. Adopting an existing `skills_library_url` is NOT done in the migration: the legacy clone at /data/skills-library/ must move into a per-source subdir in the same operation, so it belongs in skill_service where both halves succeed or fail together. Dual-track per invariant #9: SQLite `skill_sources_table` + Alembic 0031_skill_sources, with schema.py DDL and tables.py MetaData kept consistent. Refs Abilityai/trinity-enterprise#237 * feat(skills): per-source clone with tag pinning (ent#237) Extracts one source's git lifecycle into `SkillSourceClone` so the library can hold N checkouts, one per `skill_sources` row, under /data/skills-library/. Behaviour for a branch source is the old single-clone path unchanged. The addition is tag pinning (AC#5). Skills carry executable `scripts/` (ent#183) that the ent#139 runner executes, and ent#236 makes syncing automatic — so a branch-tracking source puts every merged upstream commit on every install with no human in the loop. The bundled community source pins to a tag; custom sources, whose write access the operator controls, keep tracking a branch. A pin is only worth as much as the tag's immutability, which git does not enforce, so a tag resolving to a different commit than the last sync is refused as `moved_tag` rather than adopted. Two independent mechanisms: the fetch deliberately omits `--force` (git then refuses to clobber a moved tag ref), and an explicit SHA comparison catches the same condition on a fresh clone where no local ref exists to conflict. Moving to new content is done by pointing the source at a new tag NAME — an explicit admin action. Source ids and refs become argv and directory names, so both are regex-gated at construction rather than trusted from the DB: this blocks traversal via either, and `-`-leading refs that would smuggle a git option. The realpath containment check is now per-clone, closing an escape route that did not exist with a single checkout (a symlink resolving into a *different* source's tree). tests/unit/test_ent237_skill_sources.py builds the actual attack — upstream force-moves a tag onto a commit adding a payload — and asserts the payload never reaches disk, not merely that the call returned an error. Verified by mutation: neutering the pin fails that test and only that test. Refs Abilityai/trinity-enterprise#237 * feat(skills): merge skills across sources, custom-wins, shadow-reported (ent#237) Makes the library actually multi-source. `skill_service` now orchestrates N `SkillSourceClone`s instead of being one clone: sync, list, get, and inject all resolve through the precedence order from `skill_sources`. Resolution (AC#4): the first source offering a name owns it, and every lower-precedence source shipping that name is recorded in `shadowed_by`. The record is the point — a bare "first wins" with no trace is exactly the silent overwrite AC#4 forbids. The shadowed copy is deliberately NOT a second list entry: it is unreachable, and offering it would imply a choice the flat `.claude/skills/<name>/` namespace cannot honour. Injection reports it too (`shadowed_source:<name>` warning), so "I assigned Community's copy and got Acme's" can't happen quietly. One source failing never blinds the others: per-source sync outcomes are reported individually and the aggregate succeeds if any source synced. With several repos configured some will be broken at any moment, so this is the normal case, not the edge. `_git` in the clone now tolerates a missing directory. A source whose first clone failed has none, and `subprocess.run(cwd=<missing>)` raises FileNotFoundError — which escaped through `current_commit` into the list-cache fingerprint and took down the whole merged listing over ONE unreachable repo. Caught by test_one_broken_source_does_not_blind_the_others. Other correctness points: * the list cache is keyed on a fingerprint over EVERY enabled source's commit, not one SHA — otherwise adding/disabling/re-syncing a second source serves a stale merged list indefinitely * injection resolves ONCE up front; re-resolving per skill would let a concurrent admin sync inject a half-and-half set * the agent-side version marker records the OWNING source's commit plus its source_id — with N sources there is no single library commit, and stamping the wrong one makes the record unauditable * `_skill_files`/`_parse_skill_info` take the clone explicitly rather than re-resolving, so describing a non-winning copy can't silently describe a different source's files * realpath containment moved into the clone, applied per-source — a shared root would let a symlink in one source resolve into another's checkout and pass Legacy adoption (AC#6, kept per vybe): an existing `skills_library_url` becomes a regular CUSTOM source — custom, not default, so precedence keeps preferring the repo the operator actually chose. DB row is written before the clone moves, so a crash between them leaves a source that simply re-clones; the reverse order would strand a checkout no row points at. Idempotent and fail-soft. `get_library_status` reports per source (with each one's WON skill count, the number that matters when sources overlap) and retains the legacy url/branch/commit_sha fields so the pre-ent#237 MCP tool and Settings panel keep rendering until they migrate. 11 new tests covering the merge, precedence handover on disable, cache invalidation, broken-source isolation, and all three adoption properties. Refs Abilityai/trinity-enterprise#237 * feat(skills): seed the bundled community source on fresh installs (ent#237 AC#3) A fresh install now starts with the community catalog configured, so the library is never empty out of the box. Seeded as a ROW, not resolved as a code default at read time. That distinction is the design, and it mirrors the #1638 retention-floor lesson: a read-time default is re-applied on every boot, so it would resurrect a source the admin deliberately deleted and would silently hand an EXISTING install a source it never configured. A row can be deleted or disabled and stay that way. Fresh-install detection reuses #1638's signal — `users` is empty for exactly one moment in a database's life — so the seed runs in the same window and, like the retention seed, must run BEFORE _ensure_admin_user (which is what makes `users` non-empty). * ref_type is `tag`, per AC#5: the community catalog takes PRs from strangers and its skills carry executables the ent#139 runner runs, so instances follow a tag we bump, never the branch head. * priority is DEFAULT_SOURCE_PRIORITY (highest number = lowest precedence), so any custom source added later wins a name collision with no reordering (AC#4). * INSERT OR IGNORE against the partial-unique default index: both migration locks fail open, so two workers can race this and must not produce two defaults. * TRINITY_DEFAULT_SKILL_SOURCE="" disables it entirely, for an operator who wants no community catalog (mirrors TRINITY_DEFAULT_SYSTEM_MANIFEST). * Never raises. `init_database` runs at import, so a raising seed would crash-loop boot permanently; a skipped seed just leaves an empty library, which is the pre-ent#237 status quo. Both dialects, as invariant #9 requires: the sqlite cursor path and the engine-based path for PostgreSQL, sharing one `_default_skill_source_values` so the seeded row cannot drift between them. The repo it points at is ent#296 and does not exist yet, so until that lands a fresh install reports one failed source rather than a populated catalog — fail-soft by design, `sync_library` never raises. Refs Abilityai/trinity-enterprise#237 * feat(skills): source-management endpoints, human-only on every mutation (ent#237) Adds the REST surface for multi-source: list, create, update, delete, and per-source sync, plus the SkillSourceCreate/SkillSourceUpdate models in models.py (invariant #14). Every MUTATING route carries `reject_agent_principal` in ADDITION to `require_admin`, and that is load-bearing, not padding. `require_admin` answers "what role", never "is this a human": 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 satisfies it (ent#293 — the third occurrence after trinity-ops-agent#232 → #1644 → #1816). Registering a source is the GRANT action from the learnings.md grant-vs-use distinction: it decides which repo the fleet executes code from, and skills are instructions Claude follows. A prompt-injected agent able to add its own source would get unattended, fleet-wide, persistent prompt injection — the exact chain ent#293 documents, reopened through a new door. ent#237 removes that issue's step-1 target (`skills_library_url`), so shipping these routes with only `assert_admin` would have re-created the hole it closes. Reading and syncing an already-configured source is USE, so those stay role-gated only. Other boundary decisions: * `is_default` is absent from BOTH models — a caller must not be able to claim the bundled source's trust posture (tag-pinned, ours to bump) for an arbitrary repo. The db layer refuses it too, so adding the field back here cannot silently start working. * the SSRF allowlist (#179) runs on write, so a bad URL is rejected at the boundary instead of surfacing later as a recurring sync failure * distinct 409s for duplicate-(url,ref) vs default-already-exists, so the UI can say which * audit is best-effort — a logging failure must not undo a completed write * list is admin-only because the rows carry repo URLs, which for a private source are themselves sensitive; the per-agent Skills tab gets `source_name` from GET /skills/library instead, which exposes no URLs Tests pin the gate statically (an integration test needs a live app + DB, and this must fail the moment a new mutating route lands without it) plus a guards-the-guard test that fails on any unreviewed POST/PUT/DELETE under /skills/sources. Mutation-verified: dropping the call from one handler fails exactly one test. Also fixes a leaky test: the adoption tests assigned `ss.get_skills_library_url` directly instead of via monkeypatch. Since skill_service imports those getters by value, the assignment persisted for the whole session and made every later sync adopt the fixture repo as an extra source — surfacing as unrelated failures once random ordering moved them. 46 tests now pass on three consecutive randomized orderings. Refs Abilityai/trinity-enterprise#237 * feat(skills): surface source provenance on the REST + MCP surfaces (ent#237) Threads `source_id`, `source_name` and `shadowed_by` out to the two consumer surfaces, and documents the multi-source model in requirements. `SkillInfo` is constructed field-by-field in the router, so a new service-layer field is invisible over REST until it is named there — the three provenance fields are spelled out explicitly for that reason. Same in the MCP tool: the list output now carries `source` and `shadowed_by`. `source_name` only, never the URL, on both surfaces. `list_skills` is reachable by agent-scoped keys, and a private source's repo URL is itself sensitive — the URLs stay on the admin-only `GET /skills/sources`. Source *management* is deliberately REST-only and not an MCP tool at all: it is the grant action, and the whole point of the ent#293 gate is that an agent principal must not reach it. `SkillsLibraryStatus` in the MCP types gains the `sources` array; the flat url/branch/commit_sha fields are retained (reflecting the first source in resolution order) so the existing tool and Settings panel keep rendering until they migrate. Typechecked with tsc --noEmit. requirements/skills.md §21.1 rewritten for multi-source with three new subsections — 21.1.1 custom-wins resolution, 21.1.2 the tag-pinning supply-chain posture and the grant/use auth boundary, 21.1.3 migration + fresh-install seeding — each recording WHY, since every one of those was a decision with a rejected alternative. §21.1 also now records the AC#7 outcome (all OSS-core) and the honest Not-Built list, including the fixed `.claude/skills/` layout convention: a repo shaped differently syncs to zero skills. Refs Abilityai/trinity-enterprise#237 * feat(skills): Settings panel becomes a source list (ent#237) Replaces the single URL+branch form with `components/SkillSourcesPanel.vue` backed by `stores/skillSources.js`, and strips the now-dead single-repo state and methods out of Settings.vue (~130 lines). Extracted to a component rather than grown inline: Settings.vue was already 3800+ lines, and per-source rows, an add form, and error surfacing would have added meaningfully to that. The store is a SEPARATE domain from `stores/skills.js` on purpose. That store owns per-agent skill assignment (an owner surface); this one owns which repositories the platform syncs from (an admin surface, and the grant action of requirements §21.1.2). They share no state — and keeping them apart also avoids colliding with the Skills-tab rebuild in ent#235 / PR #1877, which is rewriting stores/skills.js right now. UI decisions that carry the design rather than decorate it: * the list renders in backend RESOLUTION order and the first row is badged "wins conflicts". The store never re-sorts — ordering is a backend contract, and a client-side sort would silently misreport which source actually wins * `ref_type` shows as "pinned" vs "branch" with a tooltip explaining that a pinned tag which moves is REFUSED. That is the supply-chain posture (§21.1.2), so it belongs on the row, not buried in an edit form * the add form warns when to pin: "when you don't fully control who can merge" * backend errors surface VERBATIM. A refused moved tag names the tag and says to point at a new one; a generic "sync failed" would throw exactly that away * the shadowed-skills count gets its own banner — non-zero means someone is running a different source's version of a skill than intended (AC#4) * Remove says explicitly that agents keep installed skills and assignments are not removed, so it can't read as "strip these skills from my agents" * a failed fetch leaves the list untouched rather than clearing it — blanking would read as "no sources configured", a different and alarming claim * the add form stays filled on failure so a bad URL is corrected, not retyped Verified with a real `vite build`. NOT included: the per-skill source badge + shadow warning in SkillsPanel.vue. That file is being rewritten in PR #1877 (dolho), so editing it here would hand him a conflict. The backend already exposes `source_name`/`shadowed_by` on GET /api/skills/library, so it is a small additive change once #1877 lands. Refs Abilityai/trinity-enterprise#237 * test(skills): retarget the pre-ent#183 skills tests to the multi-source API Fixes 27 regressions this branch introduced. My new ent#237 tests passing said nothing about the existing ones: they exercise the single-clone API that moved onto SkillSourceClone (`_git_clone`, `_git_pull`, `_get_current_commit`, `_git_tree_shas`, `_git_archive_skill`) or whose signature gained the owning clone (`_parse_skill_info`, `_skill_files`). No production behaviour changed here — the properties these tests pin are all still true, just relocated: * test_ent183_skill_packages: the shared fixture now wires exactly ONE source (still a valid configuration), so all 22 injection/listing assertions stand unchanged. The git seams are mocked on the clone instead of the service. * test_skill_service_user_agent: the #184 User-Agent property is pinned on SkillSourceClone, where the subprocess calls now live. `_clone(exists=True)` creates the directory because `_git` short-circuits to a synthetic failure when the clone is absent. * the containment guard moved with it. Note `service._skill_dir` now also requires the skill to EXIST in a source, so the pure path-safety property is pinned on `clone.skill_dir` to keep it independent of existence — otherwise "does the regex-less containment check hold" would silently become "does this skill exist". Two ordering bugs surfaced while fixing this, both mine, both order-dependent and therefore worth removing rather than working around: 1. test_ent183 installs sys.modules stubs at IMPORT time, which permanently binds `skill_service.db` to a MagicMock for the session. My tests depended on that singleton, so they passed or failed based on which files ran first. They now inject an explicit `_SourcesFacade`, removing the ordering question. 2. the same stubs make `get_skills_library_url()` return a real-looking URL, so every sync in my fixture also adopted a phantom legacy source and inflated the expected counts. The fixture now pins that getter to None; the adoption tests opt in via `_fake_legacy_setting`. Also switched the two static auth guards from `inspect.getsource(module)` to reading the router file off disk: importing the module can be affected by another file's stubs, and a static guard that silently stops running is worse than no guard. 115 tests across the four skills files pass, stable under both file orderings. Refs Abilityai/trinity-enterprise#237 * fix(skills): make legacy adoption a one-way migration (ent#237) `_adopt_legacy_clone` left `skills_library_url` in place after adopting it as a source, so the setting acted as a read-time default: an admin who deliberately deleted the migrated source got it silently re-created on the next sync. That is the same resurrection trap the fresh-install seed is a ROW specifically to avoid (#1638's lesson — a read-time default is re-applied on every boot, so it cannot honour a deletion). I wrote that reasoning into the seed and then reintroduced the bug one function away. Adoption now consumes both legacy keys once it succeeds. Nothing else reads them after ent#237 (verified: the only remaining references are the SSRF validator's name and the settings-router special case), so consuming them strands no consumer. Best-effort — a failed delete leaves a duplicate-suppressed re-adoption on the next sync via the existing `existing` check, never a broken migration. Regression test asserts the full sequence: adopt, admin deletes, sync again, source stays gone. Mutation-verified — neutering the delete fails it. Refs Abilityai/trinity-enterprise#237 * fix(skills): reject agent principals on the source LIST endpoint too (ent#237) Found by /review on this branch. `GET /api/skills/sources` was `require_admin` only, and its own docstring justified that gate as "the rows carry repo URLs, which for a private source are themselves sensitive." `require_admin` does not deliver that. An agent-scoped MCP key resolves to its owner carrying the owner's role (ent#293), so on a default admin-owned install every agent could read exactly the private repo URLs the gate exists to protect — and a prompt-injected agent reading them is the disclosure, not a hypothetical. I had applied `reject_agent_principal` to all three mutating routes on the grant-vs-use reasoning, and that framing is what hid this: grant-vs-use quietly implies reads are fine on a role gate. It is the wrong axis for a read. The right question is whether the RESPONSE is sensitive, and here it is. Sync stays `require_admin` only: it pulls an already-admin-configured repo and returns no URLs, so it is genuinely use. The static guard gains a GATED_READS list so a future read endpoint carrying source URLs fails the same way rather than being argued about again. Lesson recorded in learnings.md — the ledger already tracks this class (trinity-ops-agent#232 → #1644 → #1816 → ent#293) and the read-vs-write blind spot is the new part. Refs Abilityai/trinity-enterprise#237 * fix(skills): use the status-danger design token, reject credentialed source URLs (ent#237) Two fixes. **CI, frontend-build**: SkillSourcesPanel used `status-error-*`, which does not exist. The palette is `status-success` / `status-warning` / `status-danger` / `status-info` / `status-urgent` — I invented `error` by analogy from the two I happened to see in Settings.vue. `vite build` passes on an unknown Tailwind class (it just emits nothing), so only `npm run check:tokens` catches it, and I had run the build but not that check. **Security, from /cso --diff**: a source URL embedding a token (`https://<token>@github.com/owner/repo`) passed validation and was persisted verbatim. `validate_skills_library_url` checks `parsed.hostname`, which IGNORES userinfo, and returns the URL unchanged — so the credential would land in `skill_sources.url` in plain text, be returned by GET /skills/sources, and be rendered in the Settings panel. Pasting one is an easy mistake: it is the form GitHub hands you for scripted clones. Rejected with a named 400 pointing at the GitHub PAT setting, rather than stripped silently — a silently-stripped token would leave the admin believing private-repo auth was configured when it was not. Enforced at the ent#237 routes, deliberately NOT in the shared validator: that helper also serves the pre-ent#237 `skills_library_url` setting, and an install relying on an embedded token for private-repo access would break on upgrade. The class is pre-existing; this branch widens the exposure (N sources, a new endpoint returning them, a panel rendering them), so the guard sits on the new surface. A test pins that the shared validator does NOT strip userinfo — if that ever changes, it fails and the extra guard can be reconsidered rather than lingering as unexplained defense. Refs Abilityai/trinity-enterprise#237 * fix(skills): parse the host before splicing the PAT; drop the sys.modules footgun (ent#237) CodeQL flagged 4 new alerts on PR #1901; this addresses the actionable one and relocates the credential guard so it is testable. **py/incomplete-url-substring-sanitization (high)** — `_authenticated_url` decided whether to splice the platform GitHub PAT with `"github.com" in url`, then spliced via `url.replace("https://", f"https://{pat}@")`. A substring test is satisfied by `https://evil.example/?x=github.com`, so that pair would have sent a live GitHub credential to an attacker host. Not reachable today — `sync_library` validates every source URL against the github.com allowlist first — but "safe only because a caller three frames up validates" is exactly the property that breaks when a caller is added, and the blast radius is a live PAT. Now: shorthand is normalised to an absolute https URL first, the host is PARSED, and the splice happens only on an exact match against the same `ALLOWED_SKILLS_LIBRARY_HOSTS` the SSRF guard uses. Rebuilt via urlunparse rather than str.replace, which would also rewrite a second "https://" occurrence inside a path or query. Moves the embedded-credential guard from `routers/skills.py` into `utils/url_validation.py` as `reject_embedded_credentials` + `EmbeddedCredentialError`. It is URL policy and belongs with URL policy, and testing it through the router required importing the whole `routers` package, which drags in the agent-service chain and collapsed under another module's import-time stubs. A leaf module is importable from anywhere. The remaining CodeQL alerts are pre-existing on dev (a test file untouched here, and a path-injection alert on the `_skill_dir` chokepoint whose realpath containment is the documented guard, now applied per-source). Test-ordering fixes forced by the same stub fragility (#1898): the ent#183 stub of `utils.url_validation` now mirrors every name `skill_service` imports — a missing constant is an ImportError at collection, not graceful degradation — and this file gets an autouse fixture that evicts detectable stubs (a stub has no `__file__`) so results do not depend on which file pytest runs first. That fixture uses `monkeypatch.delitem`, NOT a bare `del sys.modules[...]`: `tests/lint_sys_modules.py` exists to stop exactly that pattern, and working around sys.modules pollution by polluting sys.modules is how this file would have become the next #1898. The eviction is undone at teardown. Squashed with its follow-up because a test-only commit matches no workflow path filter, so CI never ran on it. Refs Abilityai/trinity-enterprise#237 * fix(skills): clear the three new CodeQL alerts on this PR (ent#237) CI's CodeQL check flagged 3 new alerts in code this PR changed. 1. py/incomplete-url-substring-sanitization (high) — `_authenticated_url` decided whether a scheme-less source URL already carried a host with `url.startswith("github.com/")`. That is the same bypassable class of check the surrounding docstring says this function exists to avoid, one line below the comment saying so. Decided by parsing now, against the same allowlist the splice itself uses, so there is exactly ONE way this module answers "which host is this". Side effect: `www.github.com/owner/repo` shorthand now resolves to that host instead of becoming a repo path under github.com. 2+3. py/stack-trace-exposure (medium ×2) — both sync routes hand `sync_library()["error"]` to FastAPI verbatim as an HTTP `detail`, so that string is an API surface, not a log line; three `except ... as e` branches interpolated the caught exception into it. The messages are rebuilt from the stored source row (ref / ref_type / a fixed URL-shape hint) and the full exception goes to the log, which is where an operator debugs from anyway. The second alert is the pre-existing one on `/skills/library/sync`, re-flagged because this PR rewrote its sources — same root cause, cleared by the same change. Tests pin all three: without the fix 3 of the new cases fail on the exception text and one on the www host. * fix(skills): close the two defects /review and /cso found on this branch (ent#237) Both are pre-merge finds on this branch, not regressions from dev. ## Alembic revision graph forked into two heads (/review, CRITICAL) This branch cut `0031_skill_sources` off `0030`; dev independently cut `0031_channel_report_back` off the same parent. Separate files, so the merge never conflicted — but `alembic upgrade head` refuses a multi-head argument, so `init_database()`'s non-SQLite branch would fail and PostgreSQL boot with it. CI could not have caught this before the merge: it ran when `0031_skill_sources` was the only 0031. Renumbered to `0034_skill_sources` onto the current head rather than adding an Alembic merge revision — this table has no relationship to the channel/telegram/evaluations chain, and a linear history is what the `schema-parity` and `pg-migrations` jobs assert. ## Tag pin bypassed on the clone path (/cso, HIGH, exploit executed) `_update_tag` enforced the AC#5 pin two ways — a `fetch` without `--force` (git refuses to clobber an existing tag ref) and an explicit recorded-SHA comparison — and BOTH are properties of an existing checkout. `sync()` routes to `_clone()` whenever `.git` is absent, and that path took no `expected_sha` and compared nothing. The `_update_tag` docstring claimed to cover the fresh-clone case; it does not, because a fresh clone never reaches it. Lose the checkout — this class's OWN quarantine rename, a restored /data backup, a recreated volume — while upstream moves the tag, and the moved tag was adopted silently: success=True, moved_tag=None, commit changed. `commit_changed` then goes true, so ent#236's fleet re-inject pushes the moved tag's executables to every running agent with no human in the loop. That is the exact scenario tag pinning exists to prevent, defeated behind a successful-looking sync. Verified by executing it against a local upstream: before the fix the payload landed on disk; after, sync refuses with moved_tag and the checkout is gone. `_refuse_moved_pin_after_clone` re-checks the resolved HEAD against the recorded SHA after a fresh clone and DELETES the checkout on refusal — `list_skills` and injection read the working tree, so a failed sync that left it behind would still serve the moved tag's content. A first-ever sync has no recorded SHA and is untouched. The existing `test_moved_tag_is_refused_and_payload_never_lands` passed throughout because it clones BEFORE moving the tag, so it can only ever exercise the update path. The new regression test varies the starting state instead, and fails without the fix. ## Also - `POST /skills/sources/{id}/sync` returned 400 on lock contention where its sibling returns 409, and ran a git clone inline in an async handler. Both are consequences of ent#237 moving the ent#236 sync lock into the shared `sync_library`; now `asyncio.to_thread` + 409, mirroring the full sweep. - architecture.md: `skill_sources` DDL, the three source routes, the sync-lock Redis key, and a `skill_service` description that still described single-repo sync (CLAUDE.md rule 4 — API/schema change). - requirements/skills.md §21.1.2 asserted the fresh-clone coverage the code did not have; corrected to describe both paths. - learnings.md: the durable class — a "must not have changed" control enforced on the update path is bypassed on the create path, and the test that proves it clones first. Full unit suite at seed 12345: 7250 passed / 0 failed. Refs Abilityai/trinity-enterprise#237 * feat(skills): vendor-neutral library layout — per-source skills root (Abilityai/trinity-enterprise#332) The skills-library source layout was hardcoded to `.claude/skills/`, so the public community catalog (abilityai/trinity-skills, ent#296) — which already ships a vendor-neutral top-level `skills/` layout plus a root `catalog.yaml` declaring `skills_root: skills/` — synced to zero skills. The SKILL.md format is harness-portable; only the *discovery path* is Claude-specific. Deliberately reopens ent#237's "root not configurable per source" call: the repo is untagged with zero syncing instances today, so this is the cheap moment — after the first `v*` tag it becomes a breaking migration. Resolution is per source, in `SkillSourceClone.skills_rel_root()` (lazily cached; instances are per-operation, so no staleness across syncs): catalog.yaml `skills_root:` → evidence-gated `skills/` probe → `.claude/skills/` Every invalid tier falls THROUGH to the next rather than blanking the source: an unusable catalog (unparseable, alias-bearing, non-mapping, unknown `schema_version`, oversized, symlinked, invalid value) degrades to the probe, and a symlinked or clone-escaping declared root does too. Only the final tier escaping containment yields an empty listing — None/empty-propagated through `skill_dir`/`skill_names`, never a raise through `list_skills`. A source serving skills today cannot be blanked by a tier it does not use. The agent-side destination stays `~/.claude/skills/<name>/`, and `filter_skill_archive(source_root=…)` is the ONE point where source layout becomes destination: it rewrites tar arcnames to `.claude/skills/<name>/…` (identity for the legacy layout). That placement is required, not merely tidy — `executable_paths` → the agent-side chmod list, the restore sent-vs-restored accounting, the persisted manifest, and `_legacy_fallback`'s SKILL.md lookup all key on post-filter arcnames. Consequence: manifests, prune/removal confinement, per-skill `.gitignore` lines, the restore `paths` allowlist and the whole ent#236 removal machinery stay destination-canonical with ZERO migration, and installed packages keep pruning correctly across a repo restructure. Three guards on the author-controlled value, each catching what the others structurally cannot (see docs/memory/learnings.md): - Segment-wise validation — split on `/`, reject any segment that is empty, `.` or `..`. A whole-string charset regex admits `.`, `./skills` and `skills//x`, each of which breaks archive-prefix math into per-skill "empty package" failures. A leading `-` is refused so the value can never read as a git option (the `--` separators at every pathspec are the belt to this suspenders). - lstat-order symlink refusal on catalog.yaml and on both candidate roots, with a bounded `read(cap+1)` — a post-read length check is defeated by `catalog.yaml -> /dev/zero`, and git materializes author symlinks. A symlinked `skills/` would list fine but yield empty `git archive` output from HEAD, failing every injection. - realpath containment against the REALPATH'd base — `/data/skills-library` may itself be a symlink, so comparing a resolved target to an unresolved base would refuse every source spuriously. Parsing goes through the shared ent#314 hardened loader (`AliasPolicy.REJECT`, 64 KB cap), catching `HardenedYamlError` explicitly alongside `yaml.YAMLError` — it is a ValueError, not a YAMLError, and missing it would escape through `list_skills` and 500 the merged listing. `schema_version` gates the whole catalog (absent or `1` — int and string both tolerated); anything else degrades to the probe rather than being silently misread, which keeps a future schema bump safe. Platform parses only these two keys; `categories`/`providers` stay catalog metadata for UIs. Dual-layout guard: SKILL.md evidence under BOTH roots with no catalog to decide keeps `.claude/skills/` and flags `layout_conflict` in status. A pre-existing dual-layout source must never silently flip *which executable content* the ent#236 unattended auto-sync injects fleet-wide; switching requires the explicit declaration. Also: per-source `skills_root` + `layout_conflict` in library status (null until cloned, honest rather than guessed), honest per-source `path` provenance, and the now-stale operator copy in SkillSourcesPanel. 52 new tests. Independently reviewed by strategy + engineering agents and a second-opinion model; `/cso --diff` found zero findings introduced by this change (report under docs/security-reports/; one pre-existing inherited disclosure filed separately as Abilityai/trinity-enterprise#334). Refs Abilityai/trinity-enterprise#237, Abilityai/trinity-enterprise#296 Fixes Abilityai/trinity-enterprise#332 Co-Authored-By: Claude Opus 5 <[email protected]> * fix(skills): make source edits reach disk, and gate sync on effect (ent#237) Four defects from review, three of one shape: the row moved and the checkout did not. 1. Repointing a source's `url` was a no-op on disk. `_update_*` fetches `origin`, written at clone time, so every later sync silently pulled the OLD repo — reporting success, with a moving commit that feeds ent#236's fleet re-inject. `sync` now compares `origin` against the configured remote and discards + re-clones on a genuine mismatch. Discard rather than `remote set-url`: the latter leaves the old repo's refs behind, and a tag name present in both repos at different commits then reads as a moved pin and is refused forever. The compare strips credentials (a private source's on-disk origin carries a PAT the stored URL never does, so a naive compare re-clones on every sync), and an unreadable origin counts as a MATCH — the action gated on that answer is an rmtree, so ambiguity resolves to "don't". 2. The documented tag-bump path was unreachable. `update_source` never cleared `last_commit_sha`, so bumping `v1` → `v2` compared v2 against v1's recorded SHA and was refused as `moved_tag`, with the error telling the operator to do what they had just done; on the fresh-clone path the refusal rmtree's first, so the source ended up empty. The bookkeeping is now cleared when `url`/`ref`/`ref_type` change — and deliberately NOT on name/enabled/priority, since a cleared baseline on disable would let a tag moved during the disabled window be adopted silently on re-enable (the AC#5 bypass via a checkbox — and the enabled toggle is the only edit the UI currently wires to PUT). 3. Deleting a source leaked its checkout. `discard_source_checkout` reclaims `<id>/` + `<id>.broken` on delete (row first, disk second), with `_reclaim_orphan_checkouts` on full sweeps as the backstop for the crash window and for installs that already accumulated clones. Fail- closed on the row read — a sweep reading "DB error" as "no sources" deletes the whole library — and scoped to the server-minted id shape, so the legacy checkout and operator directories are out of reach. 4. Both sync routes are now human-only. They were role-gated as "use, not grant", but grant-vs-use is a claim about EFFECT: a sync clones executable material and spawns `run_fleet_reinject`, pushing skill scripts/ to every running agent, and an agent-scoped key resolves to its owner carrying the owner's role (ent#293). The coverage scan widened from /skills/sources to /skills/ — `POST /skills/library/sync` sits outside the sources prefix, so the old scan reported full coverage while missing the route in question. Also: `test_mutating_routes_reject_agent_principals` was satisfiable by a comment. It grepped `ast.dump(fn)`, which renders docstrings, so documenting the gate in (4) made the guard pass with the real call deleted. Now matches an ast.Call node. 20 new tests. Each of the four fixes mutation-verified to fail exactly its own test. Full unit suite: 7322 passed, 18 skipped. * test(skills): pin the fail-safe direction of the repoint discard (ent#237) @dolho's I1 on #1901: `_origin_matches` returns MATCH when `git config` cannot read `origin`, because the action gated on the answer is an `rmtree` and an unknown answer must not widen an unattended delete (#1638/#1644). The argument lived only in the docstring — flipping the branch to `return False`, so a transient git failure discards the checkout, left all 92 tests green. The feature half was already covered (neutering the origin check fails `test_repointing_moves_the_git_remote_too`); only the safe direction was not. Staged as the case where a discard would otherwise be CORRECT — the url IS genuinely repointed, and only the origin read is blinded — so the assertion is about the ambiguity resolving to "leave it alone", not about a mismatch simply not existing. Asserts both halves: `_origin_matches` is True, and a marker written inside `.git` survives the sync. Mutation-verified: `return True` → `return False` fails exactly this test (1 failed, 92 passed) and nothing else. Refs Abilityai/trinity-enterprise#237 * fix(skills): reclaim the old repo's quarantine when a source is repointed (ent#237) @dolho's I2 on #1901: `_discard_repointed_checkout` removed `<id>/` but not `<id>.broken`, and neither reclamation path can reach a quarantine while the source still exists — `discard_source_checkout` runs on delete, and `_reclaim_orphan_checkouts` considers only ids with NO row. So the previous repo's content sat in the library root for the life of the source. Bounded at one per source, so disk hygiene rather than a correctness bug, but a repoint makes that directory permanently irrelevant by construction. `.broken` was already spelled in four places across two modules — the writer here and both reclaimers in `skill_service` — so this adds a shared `QUARANTINE_SUFFIX` and a `quarantine_path` property rather than a fifth literal. A suffix that drifts between the writer and the reclaimer leaves quarantines nothing can collect, which is this same bug one level up. The test produces the quarantine the way production does (a checkout that has lost its `.git`, taking the clone branch) rather than writing the directory by hand, so it breaks if the naming ever moves, and asserts the old-repo content was really there before the repoint. Mutation-verified: restoring the single-path `rmtree` fails exactly this test (1 failed, 93 passed). Full unit suite 7557 passed, 18 skipped (+64 in test_ent236_skills_lifecycle.py, which still cannot be co-collected with test_ent183_skill_packages.py — the pre-existing #1898 sys.modules stub, present on this branch before these two commits). Refs Abilityai/trinity-enterprise#237 --------- Co-authored-by: Eugene Vyborov <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: dolho <[email protected]>
obasilakis
added a commit
that referenced
this pull request
Aug 5, 2026
… key (#848) (#1707) * harden(mcp): operator tool visibility is an allow-list, not a deny-check (#848 prereq) The operator-tool gate was `auth?.scope !== "connector"` — it admitted every scope it had not heard of, including a context with no auth at all. Replace it with an explicit `OPERATOR_SCOPES = {user, agent, system}` allow-list that fails closed. Not currently exploitable: our `authenticate` callback throws on a missing or invalid key rather than returning undefined, so no falsy-auth session exists today. It is a trap door sitting exactly where #848 must step — the natural way to let an unauthenticated caller reach `request_login` is to return undefined instead of throwing, and [email protected] turns that into full operator exposure via two independent behaviours: 1. `FastMCP#createSession` skips filtering entirely for falsy auth: `auth ? this.#tools.filter(...canAccess...) : this.#tools` (dist/chunk-MDIESGNI.js:1762) — every registered tool is advertised and `canAccess` never runs. 2. The stateful httpStream branch we run does NOT reject an `authenticate()` returning undefined; only the stateless branch guards it (:1640 vs :1690). Blast radius had it been tripped: disclosure of the full operator tool catalog (create_agent, delete_agent, inject_credentials, export_credentials, get_credential_encryption_key, get_agent_ssh_access, ...). Execution of most would still fail in `getClient()` for want of an mcpApiKey — but that is a client-construction guard, not an authorization check, so any tool not routed through it would genuinely run. Renames `connectorDenied` -> `operatorOnly` across server/index/dynamic-agents; the old name would actively misdescribe the new semantics on a security predicate. ent#46 connector isolation is unchanged (`connectorOnly` untouched). Adds src/tool-visibility.test.ts (9 cases) pinning: the three operator scopes admitted, connector denied, an anonymous pre-login sentinel denied, unknown and future scopes denied, absent auth denied under MCP_REQUIRE_API_KEY, dev-mode semantics preserved, the two gates mutually exclusive, and the scope set itself pinned so widening it must be deliberate. Each fail-open case also asserts the legacy predicate admitted it, so the tests prove the fix changes behaviour. 99/99 mcp-server tests pass; tsc --noEmit clean. Refs #848 * feat(mcp): anonymous session tier + inline-auth tools scaffolding (#848) First half of inline email auth. Flag-gated OFF (MCP_INLINE_AUTH_ENABLED), so this commit changes no runtime behaviour. - requirements/mcp.md §7.6 written first per RoE #1: credential model (session not key, and the per-connection lifetime that implies), the anonymous tier, why the tool surface is static across login, the internal backend path, whitelist bypass + why, and enumeration safety. - McpAuthContext gains `anonymous` scope plus verifiedEmail / pendingEmail / sessionId. verify_login upgrades the session by mutating this object IN PLACE — FastMCP hands every tool the same reference, so the upgrade needs no library support. `scope` deliberately STAYS "anonymous" after login: the session still holds no API key and must never satisfy operatorOnly. - authenticate(): an ABSENT Authorization header opens an anonymous sentinel; an INVALID key still throws. The sentinel is a truthy object with no `authenticated` key — [email protected] skips canAccess entirely for falsy auth and rejects `{authenticated:false}` outright. - Gates: `anonymousOnly` for the login tools, `connectorOrAnonymous` for the connector tools. The anonymous tool list is deliberately IDENTICAL before and after login — a session's tools are resolved once at construction with no per-session refresh API, so gating visibility on login state would need a client reconnect to take effect. Login flips behaviour, not visibility. - tools/auth.ts: request_login / verify_login. request_login returns one constant body on every path (unknown address, malformed input, per-session limit, backend error) and emits no audit event — wording, timing or an audit row would each be an enumeration oracle (#186). Backend errors are swallowed for the same reason. verify_login failures are uniform (never wrong-code vs unknown-email). Per-session attempt caps sit on top of the backend limiters, which Telegram's inline /login lacks entirely. - client.ts: requestInlineLoginCode / verifyInlineLoginCode bypass _fetch (an anonymous session has no bearer token) and authenticate the CALLER with X-Internal-Secret. The secret proves who is asking, never what they may do — the backend gates on email_has_agent_access. Still to come: connector tools acting for a verified email, the four internal backend endpoints, tests both sides, feature-flow doc. tsc --noEmit clean; 99/99 mcp-server tests pass. Refs #848 * feat(mcp): connector tools serve an email-verified session (#848) Completes the MCP-server half. Connector tools now handle two caller kinds that resolve BOTH the agent and the backend credential differently: - connector key (ent#46): bound agent from the auth context, backend reached with the key. Unchanged. - email-verified anonymous session (#848): no key at all; the agent is chosen from the set shared with the verified email, and the backend is reached over the internal surface carrying that email. The tools gain an OPTIONAL `agent` argument — unambiguous when one agent is available, required when several. It selects among ALREADY-authorized agents and is never a way to reach an unauthorized one: `session.agents` is a convenience for defaulting and error messages, and the backend re-gates every call on `email_has_agent_access`, so a stale or tampered list cannot widen access. For a connector key the bound agent stays authoritative and a disagreeing `agent` argument is REFUSED rather than ignored — silently reaching a different agent than the client named is the worse failure. A pre-login anonymous session is advertised these tools (the list is frozen at session construction) and refuses to act, returning a structured `login_required` rather than throwing. Adds src/inline-auth.test.ts (21 cases) pinning the security-relevant properties, not the cosmetic ones: - request_login is byte-identical across known / unknown / malformed / rate-limited / backend-threw — every enumeration path asserted equal - a malformed address is never relayed to the backend - verify_login upgrades in place but scope STAYS "anonymous" and no key is attached (it must never satisfy operatorOnly) - the verify response leaks no credential (asserts absence of trinity_mcp_/api_key/token/secret anywhere in the payload) - failures are uniform; a failed verify never binds the session - pre-login refusal on all three connector tools - an agent outside the authorized set dispatches nothing - the exposed-playbook allow-list still holds on the inline path - connector-key behaviour unchanged, incl. bound-agent mismatch refused tsc --noEmit clean; 120/120 mcp-server tests pass. Refs #848 * feat(backend): internal surface for MCP inline email auth (#848) Backend half. Four endpoints under /api/internal/mcp-auth (X-Internal-Secret, reusing routers/internal.py's C-003 dependency verbatim), router → service → db per Invariant #1, models in models.py per Invariant #14. No new tables — reuses email_login_codes. No migration. /request email a 6-digit code, iff the address is already known /verify check the code, resolve reachable agents, audit the outcome /playbooks exposed playbooks for a verified email /chat one turn via TaskExecutionService, attributed to that email The internal secret authenticates the CALLER, never the action. /playbooks and /chat re-gate on email_has_agent_access + connector-enabled per call, so a compromised MCP server still cannot reach an agent the asserted email cannot, and nothing here ever returns a credential. Security properties, each pinned by test: - /request is not an open email relay. A code is generated only for an address with a users row or an agent_sharing entry. That lookup FAILS CLOSED — being unable to answer "do we know this address" must not degrade into "email anyone who asks". - Every /request branch is byte-identical: 202 + {"status":"ok"} for known, unknown and rate-limited, send dispatched fire-and-forget (strong-ref set, the asyncio GC footgun), and NO audit row — an audit entry is itself an enumeration oracle, which is why routers/auth.py emits none either. A test asserts known.content == unknown.content and pins the key set to {"status"}, so a future expires_in_seconds or per-branch message fails loudly. - Rate limiting is keyed on EMAIL, not IP: every call arrives from the MCP server, so one IP bucket would be fleet-shared — useless as a limit and a trivial fleet-wide DoS. session_id is logged only, never a limiter key (a client picks its own session ids and could rotate past any cap). - The data gate returns ONE 403 body for no-access / connector-disabled / no-such-agent; splitting them enumerates the fleet (Invariant #8). - The gate runs BEFORE the idempotency claim on /chat, so an unauthorized caller cannot occupy a key slot for an agent it cannot reach. - get_or_create_email_user is called with no role argument; a test asserts the created role is `user` (the #314 silent-promotion regression). - The verify response is scanned whole for token/api_key/secret/bearer and its key set asserted exhaustively — a nested credential would fail, not just a top-level one. Shared rather than duplicated: _fetch_live_playbooks moves out of routers/connector.py into connector_service.fetch_live_playbooks, used by both the owner route and the inline route. Verbatim move, no behaviour change; the module docstring now admits it is no longer purely pure. New db accessors: get_agents_shared_with_email (the existing get_shared_agents is username-keyed, and inline auth must answer "is this address known" BEFORE any user row exists) and list_connector_enabled_agents. Docs: requirements §7.6 updated to match what shipped — the per-call denial is a flat 403 and deliberately does NOT write an access_requests row, because that gate runs per tool call and would be a spam vector (the channel gate runs once per conversation, which is why it can). An explicit request-access affordance is noted as deferred. feature-flows/mcp-connector.md gains the end-to-end Part B flow. learnings.md records the two fastmcp findings from this work, including a correction to a wrong claim in a dated security report. .env.example documents MCP_INLINE_AUTH_ENABLED with the posture warning. Tests: tests/unit/test_848_mcp_inline_auth.py, 33 cases. Full backend unit suite deterministic (-p no:randomly): 4635 passed, 1 failed — test_1474_read_boundary_z.py::test_schedules_summary_last_run_at_normalized, verified PRE-EXISTING by running it in a clean worktree at HEAD with zero backend changes, where it fails identically. Refs #848 * fix(848): review findings — cross-user replay, ungated backend, IP-bucket DoS /review with two independent adversarial passes (backend + mcp-server). Seven findings fixed; two were confirmed empirically by the reviewers, not just read. CRITICAL — cross-user disclosure on /chat The idempotency scope was `agent:{name}` with a caller-supplied key, so two different verified users of the same shared agent produced the SAME (scope, key): the second was served the first's stored response snapshot and execution_id. Reachable by accident as well as malice — MCP clients derive deterministic keys from call args, so two users asking one agent the same question collide by design. New `make_inline_auth_scope(agent, email)` folds the identity in. Every other `make_agent_scope` caller sits behind a per-user auth dependency; inline auth is the first where identity arrives in the BODY. The old test replayed with ONE identity, proving caching but never isolation — the new test asserts a different principal with the same key does NOT replay. CRITICAL — the backend was not gated at all MCP_INLINE_AUTH_ENABLED existed only in the mcp-server. `include_router` was unconditional, so a surface that bypasses the email whitelist, creates accounts and dispatches chat answered on EVERY install. My own PR description claimed "flag-gated, default OFF" — false for the backend half. Now config.MCP_INLINE_AUTH_ENABLED + a router dependency that 404s the surface (404 not 403, so a disabled deploy does not advertise it), with a parametrized test over all four endpoints. HIGH — /verify poisoned a shared per-IP lockout bucket client_ip is always the MCP server, so all users collapsed into one bucket. At 30 fails/5min, ONE anonymous client could lock inline login out fleet-wide and burn real web logins from the same egress — the platform-wide DoS #591 removed, reintroduced structurally. Added account-only limiter variants; the IP bucket is never written from this path. HIGH — /request timing oracle (measured 1.89x) The known branch did a committing INSERT the unknown branch did not, so identical bytes still leaked membership. All branch-dependent work moved behind Starlette BackgroundTasks (after the response is flushed). NOT asyncio.to_thread: that was tried and silently broke every send — SQLite is thread-affine, `_email_is_known` raised in the worker and its fail-closed handler swallowed it into "unknown address". Caught only because a test asserts the send fires. HIGH — /request had no bound on the unknown-address branch The per-address cap sits behind the known-check, so unknown addresses were never counted. Added a coarse global ceiling, checked BEFORE the branch so it cannot itself become a differential; over-limit is a silent skip, same 202. MEDIUM — mcp-server * `available.length > 0 &&` let ANY requested agent through when nothing was shared — the exact state meaning "you have nothing". Guard removed. * verify_login echoed upstream errors to an unauthenticated caller (raw HTTP statuses; the INTERNAL_API_SECRET env-var name when unset) and created a second distinguishable failure shape. Now one constant body, cause logged. * The per-session counter Map had no eviction and no session-close hook — unbounded growth from anonymous connections. Bounded, oldest-first. * Four new fetch calls had no timeout while the key-based path bounds itself, so a hung agent pinned an anonymous tool call forever. All bounded. * Audit rows for inline calls were unattributable: the new `agent` param was invisible to resolveTargetId, and run_playbook's `name` (a PLAYBOOK) was being stamped as target_type:"agent". Fixed, plus actor_email threaded end-to-end — note InternalAuditRequest would have SILENTLY DROPPED it (Pydantic extra='ignore'), so the field was added to the model, the router and platform_audit_service.log as a resolver fallback. Also fixed in my own work, before the reviewers ran: tool-visibility.test.ts hand-copied OPERATOR_SCOPES from server.ts with a comment claiming it was "kept in sync" — it pinned its own copy, so widening the real set would have left it green. That is the drift trap already in learnings.md (2026-07-16). Predicates now exported and imported; guard proven to fire by temporarily widening the real set. CORRECTED DOCS — a load-bearing claim of mine was wrong I wrote that FastMCP has "no per-session refresh API", and built the static tool-surface rationale on it. False: `toolsListChanged` re-filters LIVE sessions against current auth (dist:548-553), fanned by addTool/removeTool (:2202-2206) — which Trinity's own #846 reconciler fires every ~20s. The design stands, for the OPPOSITE reason: a login-keyed gate would flip non-deterministically at reconciler timing. Corrected in requirements §7.6, the feature-flow doc, server.ts, types.ts and connector.ts. Also noted: `updateAuth` REPLACES the auth object, which would discard the in-place upgrade entirely. learnings.md: three entries — idempotency scope vs. caller identity, to_thread-breaks-SQLite hidden by a fail-closed handler, and per-IP limiters behind a single-egress proxy. Tests: backend 41 (was 33), mcp-server 125 (was 120). Full backend suite -p no:randomly: 4643 passed, 1 failed — the pre-existing test_1474 failure, previously verified in a clean worktree at HEAD. Refs #848 * feat(848): keyless connector setup — the last acceptance criterion (AC6) AC6: "the default .mcp.json snippet in docs / UI works without a pre-filled API key." Delivered in both surfaces. - connector_service: `build_keyless_snippets` + a shared `_client_snippets` builder that `build_snippets` now also uses, so the keyed and keyless variants cannot drift. The keyless config is the keyed block minus the Authorization header, with a note pointing at request_login/verify_login. - ConnectorStatus gains `inline_auth_available` + `keyless_snippets`, populated by the connector router ONLY when config.MCP_INLINE_AUTH_ENABLED is on — an anonymous MCP session is rejected otherwise, so offering a keyless config on a disabled install would be dead setup instructions. Independent of has_key: the keyless flow is an ALTERNATIVE to minting a key, so it shows with or without one. - ConnectorChannelPanel.vue: a "Share without a key — sign in by email" block, gated on status.inline_auth_available, reusing the existing copy affordance. The UI reads the flag off the connector status it already fetches — no new endpoint, and NO feature-flags entry (an earlier draft added one; it was redundant with inline_auth_available and out of the issue's scope, so it was dropped). - docs: the keyless config block + flow in feature-flows/mcp-connector.md and requirements §7.6. Tests: keyless snippets carry no Authorization and keep client parity with the keyed set; the status endpoint offers keyless ONLY when the flag is on, and does so even with no key. Frontend builds clean. Closes the last open box on #848. Refs #848 * docs(security): CSO --diff audit of #848 — no findings above gate 7 attack axes independently refuted (default-safe posture, internal-secret authz, cross-user replay, enumeration/relay, anon->operator reach, verify_login disclosure, audit integrity). Verifies the 7 /review fixes hold. Two informational accepted-risk notes (internal-secret widening; pre-existing per-account bucket). Report: docs/security-reports/cso-2026-07-21.{json,md}. Refs #848 * fix(mcp): wire MCP_INLINE_AUTH_ENABLED into compose; correct fastmcp citations (#848) Addresses the /validate-pr review on #1707. BLOCKING — the flag reached neither container. MCP_INLINE_AUTH_ENABLED was defined in config.py, read in server.ts, documented in .env.example, gated at the router and covered by a parametrized endpoint test — and wired into zero compose services. Compose reads .env only for ${...} interpolation, never to inject into a container, and there is no env_file: or Dockerfile ENV, so the whole feature was permanently off with no operator lever. Now wired in all four places (backend + mcp-server x dev + prod), verified with compose's own resolution rather than grep. It fails safe, which is why nothing caught it: CI and /verify-local both boot at defaults, so a flag that can never be enabled boots clean and goes green. The durable fix is tests/unit/test_848_inline_auth_compose_wiring.py — a static packaging guard (precedent: test_1489_vite_bug_build_args.py) asserting all four wirings, the ${VAR:-false} shape (a hardcoded value is the same un-switchable bug with extra steps; a non-false default would make a network-exposed keyless path opt-out), and the reader set itself, so a third process reading the flag without wiring it fails here. Mutation-checked: removing one wiring fails 2. fastmcp citations were wrong, twice over. The reviewer caught 4.4.0 vs the pinned 4.8.0; the dev merge has since bumped to 4.12.1, so 4.4.0 was only what a stale local node_modules held. Re-verified both load-bearing behaviours against the version package-lock actually resolves — the falsy-auth filter-skip is still present, so the 87b2abb allow-list hardening is warranted — and corrected every citation to symbol-first with the line as an "as of" locator, since the minified chunk filename moves between releases. Also corrected the mechanism: canAccess is never re-invoked per call; enforcement is by absence from the toolsMap setupToolHandlers builds from the filtered list. Per the review, that assumption is now pinned by a test instead of prose: tool-visibility.test.ts boots a real FastMCP server and drives it with a real MCP client, asserting a filtered-out tool is not merely hidden from tools/list but rejected on call AND that its body never executes. Behavioural, so it survives chunk renames — the churn that made the citations wrong. Mutation-checked against the pre-#848 deny-check. Corrected a live error in learnings.md: the entry claiming canAccess filtering happens "once at session construction, so any log-in-and-new-tools-appear design needs a client reconnect". toolsListChanged re-filters live sessions and the #846 reconciler fires it every ~20s. The static-surface design stands for the opposite reason — a login-keyed gate would flip non-deterministically at reconciler timing. New entry for the compose-wiring class. Docs (Invariant #13 third-surface record): architecture.md gains routers/mcp_auth.py, services/mcp_auth_service.py, the tools/auth.ts row, the four /api/internal/mcp-auth/* endpoints, and the missing `connector` + `anonymous` scope rows. Module counts left alone — already stale independent of this PR, and reconciling them is /validate-architecture drift. feature-flows.md gains its Recent Updates row. Also: MCP_INLINE_AUTH_TIMEOUT_MS documented and wired (mcp-server only — the backend never reads it, asserted); mcp_inline_auth_enabled surfaced on GET /api/settings/feature-flags as observability, mirroring its two siblings and giving operators a post-deploy check that the two halves agree; CSO report renamed to the cso-diff-DATE-issue convention; CSO N1 (set INTERNAL_API_SECRET explicitly rather than relying on the SECRET_KEY fallback) carried into .env.example and requirements §7.6 — there is no unreleased-notes file, and .env.example is where an operator looks when enabling the flag. Verified: backend unit 5620 passed / 0 failed (the previously-known pre-existing test_1474 failure now passes, fixed by the dev merge); mcp-server 127/127 (was 125) and tsc --noEmit clean, both against the real 4.12.1 after npm ci. * docs(security): /cso --diff re-audit of #848; fix a docstring naming a known landmine CSO --diff pass over the post-review branch. 0 findings above the daily 8/10 gate; 3 informational, 1 fixed here. The re-run is not a formality. The 2026-07-21 audit assessed gates that were correct but UNREACHABLE — MCP_INLINE_AUTH_ENABLED reached zero containers, so its "default-safe posture" was unconditional rather than opt-in. With the four wirings in place the surface is genuinely reachable on an opt-in deploy, so the live controls were re-verified against code rather than re-read from the prior report: router-level gating of all 4 routes, assert_email_may_reach_agent running before the idempotency claim and failing closed, uniform 403 on both denial reasons, account-only limiters that never touch _ip_key, constant-time /request with everything branch-dependent in BackgroundTasks, name-only build_tool_description (#846 precedent), and the OPERATOR_SCOPES allow-list. Parity/uniformity guards: 38 passed. N2, found and fixed: routers/mcp_auth.py claimed the branch-dependent work runs "in a worker thread". It does not and must not — asyncio.to_thread there silently stops every code send, because SQLite connections are thread-affine so _email_is_known raises in the worker and its own fail-closed handler swallows that into "unknown address" while the endpoint keeps answering 202. The router is the file a maintainer opens first, so the natural "make these consistent" edit was to reintroduce a total silent outage. Not a security finding — the invited failure is availability, not a bypass — but a real defect sitting on the enumeration-safety contract. Now names BackgroundTasks and says why a thread is wrong. N1 (INTERNAL_API_SECRET can act as any verified email) carried forward unchanged and still accepted; its operational recommendation is no longer theoretical now the surface is reachable, and was carried into .env.example and requirements §7.6 in the previous commit. N3: 4 transitive npm vulns in src/mcp-server, all isDirect:false, pre-existing on dev and untouched by this PR — noted because package.json already overrides fast-uri, so the pin is evidently not resolving the advisory. Stated plainly in the report: this is the author auditing their own change on a keyless auth surface, same caveat as the prior audit. Independent assurance needs a fresh-context run by someone who did not write it.
5 of 6 tasks
vybe
pushed a commit
that referenced
this pull request
Aug 6, 2026
…nterprise#126) (#1911) * fix(manifests): drop acme-consulting.yaml — broken duplicate of the live seed The upcoming UI manifest picker (trinity-enterprise#126) renders one card per file in config/manifests/, which promotes these files from zero-consumer samples to the primary one-click install path on a fresh install. acme-consulting.yaml does not survive that promotion: * `cpu: 1.0` is an unquoted YAML float. `normalize_cpu` compares against VALID_CPU = ("1","2","4","8","16") as strings, and the scout/sage/scribe templates declare no `resources` of their own, so the manifest value survives the template merge and every one of the 3 agents fails at create — deploy returns status "failed" / HTTP 500. The dry-run does NOT catch it: preflight builds a throwaway AgentConfig carrying only name+template. * `auto_start:` and `trinity_prompt:` are not parsed by parse_manifest and were silently dropped. `trinity_prompt` is a typo for `prompt:`, so the prompt this manifest's author intended was never installed. * It declares the SAME system name (`acme`) and the same three short names as default-system.yaml, the first-run seed. The seed runs on every fresh install, so clicking this card would resolve to acme-scout_2/acme-sage_2/acme-scribe_2 — a duplicate fleet whose recovery is manual and per-agent. The cpu bug was masking this; fixing cpu alone would have unmasked it. Deleted rather than renamed. Renaming the system to `acme-consulting` unmasks a worse problem: the shared-folder mount is /home/developer/shared-in/{full_agent_name} (db/shared_folders.py:231) and the consumed templates hard-code the sibling names (scribe/CLAUDE.md:21-22, sage/CLAUDE.md:21,70, sage/.claude/commands/request-research.md:9), so the renamed fleet would document shared-in/acme-scout/ while mounting shared-in/acme-consulting-scout/ — exactly what default-system.yaml:16-17 warns about. Making the templates name-agnostic instead would change the agent-facing behaviour surface of the live default fleet from inside a UI issue. default-system.yaml already IS this fleet, correctly specified, and remains untouched. The structural fix for the defect class — validating merged resources in the dry-run preflight — lands with the rest of ent#126. Refs trinity-enterprise#126 * test(systems): characterize configure_permissions + create_schedules pre-refactor ent#126 extracts the permission-topology and schedule-iteration logic out of these two shipped writers into pure resolvers, so the dry-run preview and the real deploy compute the same thing from the same code. That refactor needs behaviour-preservation evidence, and neither obvious candidate supplies it: * A parity test asserting `resolve_permission_edges()` matches a writer that was just refactored to loop that same resolver is tautological — resolver and writer drift together and the test stays green. * test_ent125_resilient_system_deploy.py monkeypatches BOTH configure_permissions and create_schedules (lines 71-88), so that suite never executes either function and proves nothing about them. These 25 tests pin the writers' observable behaviour — the exact ordered db.set_agent_permissions / db.create_schedule call sequences and the integers returned — hand-derived from the shipped code and written independently of the resolvers. Captured GREEN here, BEFORE any production change; that run is the artifact the refactor is measured against. They pin, specifically, the truthiness guards that are easiest to "tidy" into a behaviour change: * full-mesh `if targets:` — a lone agent is skipped entirely, never written as [] * orchestrator-workers `if workers:` guards the WHOLE body, so a lone orchestrator with zero workers writes nothing and counts 0 * orchestrator-workers counts len(workers) by assignment, not by summation, and the worker-clearing calls are not counted * `explicit: {}` is falsy => the branch is skipped and nothing is cleared, which is NOT the same as the `none` preset * explicit phase 1 clears every agent that is not an explicit SOURCE, so a target-only agent is cleared first and granted-to second * explicit targets are filtered by membership (unknown targets silently dropped); an unknown source is skipped with a log warning * create_schedules maps manifest `cron` -> `cron_expression` and defaults enabled=True / timezone=UTC / description=None * count-only-on-success: a falsy db.create_schedule return is logged, not counted * create_schedules has no internal try/except — the raise escapes to deploy_manifest step 9 and prior writes stand (no schedule rollback) The odd permission branches are reachable in production despite validate_manifest rejecting unknown explicit sources/targets from a manifest: the partial-deploy path calls configure_permissions with `created_map`, a SUBSET of resolved names. Sync `asyncio.run` idiom rather than a bare `async def test_*`: tests/unit/pytest.ini is the effective inifile for this directory, so pyproject's asyncio_mode="auto" does not apply here and bare async tests are not collected. Refs trinity-enterprise#126 * refactor(systems): extract pure permission + schedule resolvers Preparation for the ent#126 dry-run preview, which must show permission topology and schedules. Those cannot be derived client-side: only the backend knows the resolved `_N`-suffixed agent names (resolve_agent_names already runs on the dry-run path), and a preview that re-implemented the preset rules would drift from the writer the first time either side changed. So the decision moves into pure functions that BOTH the preview and the writers consume: * `resolve_permission_edges(agent_names, permissions) -> (write_set, count)` returns the exact ordered sequence of db.set_agent_permissions calls the deploy would make, plus the integer it would report. An ordered list of pairs rather than a dict, so the write SEQUENCE stays faithful — clearing an agent and then granting to it is observable ordering a dict would normalise away. * `resolve_schedule_previews(agent_names, agents_config) -> [SystemSchedulePreview]` * `_build_schedule_create(schedule_data)` — the one manifest->ScheduleCreate mapping, shared by the resolver and the writer, so the key rename (`cron` -> `cron_expression`) and the three `.get()` defaults cannot diverge between preview and deploy. configure_permissions and create_schedules become thin loops over these. Behaviour is unchanged, and this is measured rather than asserted: the 25 characterization tests from the previous commit were captured GREEN against the pre-refactor writers and are still green (80 passed with the ent124/ent125/1759 system suites). Every truthiness guard the resolver preserves is documented in its docstring and pinned by those tests — full-mesh's `if targets`, orchestrator-workers' whole-body `if workers` and assignment-not-summation count, `explicit: {}` being falsy, explicit phase 1 clearing target-only agents, and the silent filtering of unknown targets. Logging: the per-branch messages are unified into one line per write plus a mode/count summary. Net MORE coverage than before (the `none` preset previously logged only a summary, never per agent) while keeping the mode context. No test asserts on these strings. models.py (Invariant #14): adds SystemSchedulePreview, BundledManifestSummary and BundledManifestDetail for the catalog, MANIFEST_MAX_BYTES (256 KB) with a Field(max_length=...) cap on SystemDeployRequest.manifest — which was previously unbounded, and is a size cap only, NOT a YAML-bomb defence — and three additive SystemDeployResponse fields (permission_edges, schedules_preview, system_view_requested). system_view_requested disambiguates a system_view_created of None, which today means both "no view requested" and "view creation failed and was swallowed". Refs trinity-enterprise#126 * feat(systems): dry-run preview shows topology + schedules, and validates resources AC #2 of trinity-enterprise#126: the preview must show agents-to-create, permission topology AND schedules. Only the first existed. * `permission_edges` + `schedules_preview` on the dry-run branch, computed by the pure resolvers the real writers consume. `permission_edges` collapses the resolver's ordered write-set to {source: targets} for display — lossless for the set of writes, since each branch writes any agent at most once. The topology is OPTIMISTIC (resolved against the full agent map, while a partial deploy configures against the created subset); the UI says so. * `permissions_configured` / `schedules_created` deliberately stay 0 on this branch. They mean "written", and repurposing a shipped field would mislead any existing consumer; callers count the new arrays. * A schedule that ScheduleCreate rejects now becomes a preview BLOCKER instead of a post-deploy warning discovered once the fleet already exists. The structural half of the manifest fix — the reason the deleted manifest's `cpu: 1.0` reached production at all is that `_preflight_template` validated template SHAPE only. It now also validates resources through the create path's own `normalize_cpu`/`normalize_memory`, with the create path's own precedence: `_resolve_local_template` overwrites config.resources when the template declares a block, so a manifest value only survives when the template is silent — exactly the case that failed. Verified end to end: a `cpu: 1.0` manifest previews as status "invalid" carrying "Invalid cpu '1.0': must be one of 1, 2, 4, 8, 16" where it previously previewed clean and then failed 100% of its agents. For a `github:` template the merge needs the network call this function refuses to make, so the DECLARED values are validated instead. That can over-report when the remote template overrides them — accepted deliberately and documented, because the alternative is silence about a value that is either fatal or dead config, and the fix is harmless either way. Two smaller honesty fixes: * `parse_manifest` records unrecognised top-level keys on the manifest and `validate_manifest` warns about them. Warned, never rejected — rejecting would 400 manifests that deploy today. This is the durable guard for the class that let `trinity_prompt:` (a typo for `prompt:`) and `auto_start:` sit in a shipped manifest doing nothing; both now surface. Recorded via a model field rather than a changed parse_manifest signature, which has two external callers. * A REQUESTED system view that fails to create now appends a warning. create_system_view swallows its exception and returns None, so the response was previously indistinguishable from "no view requested" and a caller would silently navigate to an unfiltered dashboard. Behaviour preservation: 84 tests green, including the 25 pre-refactor characterization tests and the untouched ent124/ent125/1759 suites. Refs trinity-enterprise#126 * feat(systems): read-only bundled-manifest catalog endpoints AC #1 of trinity-enterprise#126 asks for paste/upload AND/OR pick. Paste and upload need no backend at all, but "pick" had nothing to read: the only reference to config/manifests anywhere in src/ was the first-run seeder's single hard-coded filename. This adds the two read-only endpoints the picker needs. GET /api/systems/manifests -> [BundledManifestSummary] GET /api/systems/manifests/{id} -> BundledManifestDetail (+ raw YAML) Both require_role("creator"), mirroring POST /deploy rather than the looser get_current_user on the neighbouring list/get routes: a surface you cannot act on should not be advertised, and require_role also rejects connector principals. Invariant #4 is load-bearing TWICE here, which is why both routes are declared above the parameterized ones: * GET /manifests would be captured by GET /{system_name} and 404 as "system 'manifests' not found" — a silent, plausible-looking failure. * GET /manifests/manifest would ALSO be captured by GET /{system_name}/manifest with system_name="manifests". Verified by real requests: /manifests/manifest returns the detail route's JSON 404, not get_system_manifest's PlainTextResponse. `valid` means all THREE stages passed — parse, validate, and the same side-effect-free template/resource preflight the dry-run uses. parse_manifest alone is not a validity check: it accepts invalid names, unsupported template prefixes and bogus presets, and raises AttributeError (not ValueError) on a non-mapping `agents:`. If this is ever reduced to parsing, the field must be renamed `parseable`. Listing is fail-soft per file — an unreadable/oversized/invalid manifest is listed with valid:false and a reason instead of 500-ing the request, because one bad file hiding the other two is exactly how a broken bundled manifest stays invisible. Path confinement on {manifest_id} is layered, because no single check suffices: 1. character allowlist (also kills percent-encoded traversal, which FastAPI has already decoded by the time we see it, and ASCII-only kills homoglyphs) 2. EXPLICIT rejection of "", ".", ".." and any id containing ".." — the regex does NOT do this, since `.` is inside its character class and `..` matches it happily. Relying on the regex here is the #1759 lesson. 3. a length cap, so an over-long id is a 400 and not an escaping OSError(ENAMETOOLONG) surfacing as a bare 500 (found by probing) 4. the suffix is ours by construction (the id is a stem), so a caller cannot steer the extension at all; an explicit .yaml/.yml is tolerated and stripped 5. resolve() both sides then is_relative_to, which is what actually defeats a symlink inside the directory pointing outside it Reads open ONCE and fstat that same descriptor with O_NOFOLLOW, reading at most cap+1 bytes — config/manifests is a host bind mount in both compose files, so a stat-then-read sequence has a real swap/growth window and the file checked must be the file read. Symlinked entries are declined explicitly rather than surfacing as an unexplained ELOOP. Probed against 13 traversal shapes. MANIFESTS_DIR is env-overridable (TRINITY_MANIFESTS_DIR) and read at call time: the bare relative default is right at runtime (WORKDIR /app + the :ro mount) but CWD-dependent under pytest, and a catalog silently returning [] because the CWD differs is a silent failure. Not exported over MCP (Invariant #13) — this is a UI affordance and deploy_system already exists there. Also corrects the deploy docstring, which listed four statuses and omitted "invalid" (added by #1841), and now records that `status` covers agent creation only. Refs trinity-enterprise#126 * test(systems): bundled-manifest smoke, catalog endpoints, dry-run preview 89 tests across three files, completing the ent#126 backend coverage. test_ent126_bundled_manifests.py (15) — the test whose ABSENCE let `cpu: 1.0` ship. Table-driven over the real config/manifests directory (located from the test file, not the CWD), so a manifest added later is covered automatically. Asserts each file parses, validates, dry-runs `valid` through the real service, has no unrecognised top-level keys, and — the actual regression — that every agent's MERGED resources pass the create path's own normalize_cpu/normalize_memory with the create path's own template-wins precedence. Plus a cross-file check that no two manifests declare the same system name, and a pin on default-system.yaml staying schedule-free and prompt-free (its header states both; the picker now makes it clickable, so they are enforced rather than merely documented). Verified this suite actually catches the defects rather than merely passing: restoring the deleted acme-consulting.yaml turns 4 of these red — unknown keys, merged-resource validators, dry-run status, and the duplicate system name. test_ent126_manifest_catalog.py (47) — the endpoints, against a tmp_path catalog via TRINITY_MANIFESTS_DIR so nothing depends on the repo's own directory or the CWD. Covers summary fields, sets_prompt, already_deployed (incl. degrading on a DB error), fail-soft listing (unparseable / invalid / oversized / bad-resources files listed as valid:false, and one bad file not hiding the good ones), .yml and mixed-case suffixes, non-YAML ignored, symlinks declined, read-one incl. the tolerated explicit extension and the "invalid manifests must still open in the editor" case, and the creator/connector authorization matrix. Both Invariant #4 collisions are asserted through REAL requests and distinguished by response SHAPE, not just status: /manifests must return a list (not get_system's dict) and /manifests/manifest must return the detail route's JSON 404 (not get_system_manifest's PlainTextResponse). A third test proves the sibling export route still works for a genuinely-named system, so the guard did not break what it shadows. The traversal tests are split deliberately after probing showed two DIFFERENT layers stop these: dot segments like ".." and "." are collapsed by URL normalisation before routing (".." lands on GET /api/systems/, "." on the catalog listing — neither a traversal), while anything surviving normalisation hits the guard. So one test asserts 400 for the shapes that actually reach the handler (incl. "..yaml", where extension-stripping would otherwise hand a bare ".." onward, and "%2e%2e", proving the decode happens upstream of the regex), and a second asserts the property that actually matters across all 12 shapes: no response ever carries manifest content. Asserting 400 uniformly would have been asserting the wrong thing. test_ent126_dry_run_preview.py (27) — permission_edges across all three presets, explicit, `explicit: {}` and no-permissions, asserted at the RESPONSE level so the preview cannot silently disagree with the writer it describes; schedules_preview incl. enabled-defaults-True; the shipped counters staying 0 on a dry run; bad cpu/memory as `invalid` while template-supplied resources correctly override a bad manifest value (no false blocker); #1841's unresolvable-local-template blocker still firing; and the three error shapes the frontend normalizer must handle (400 string detail, 422 list detail). Full unit suite: 5779 passed, 1 failed — test_agent_analytics.py TestTimelineGapFill::test_day_stacks_present_in_by_type, which reproduces identically on pristine origin/dev in a throwaway worktree (a UTC-vs-local date boundary; it was run near midnight local). Pre-existing, unrelated to this branch. Refs trinity-enterprise#126 * feat(ui): install a system from a manifest — paste/upload/pick, preview, deploy The UI half of trinity-enterprise#126. `POST /api/systems/deploy` has existed for a while but was reachable only by curl or MCP. Home is a `?tab=`-driven catalog on the existing Templates page (`?tab=agents` | `?tab=systems`) rather than a 7th NavBar entry — the bar already has 6, and "install an agent template" and "install a system" belong in one hub. ent#15's agent-import wizard and ent#108's registry slot in as further tabs, which is the reconciliation the issue asks for. The existing Agents content moves under its tab unchanged, including its raw-axios fetch (Rule #2 — that Invariant #7 drift is real but not this PR's business). stores/systems.js is a new domain store (Invariant #6), deliberately not bolted onto systemViews.js: a "System" is a manifest-deployed set of agents sharing a name prefix, a "System View" is a saved tag filter. Different domains that share a word. Goes through the single `api` instance (Invariant #7). Two things drove the design, both of them traps in the backend contract: 1. `normalizeError` collapses SIX outcomes into one renderable shape, switching on `status` and never on the HTTP code. `partial` and `invalid` arrive as HTTP 200 (a naive .then() renders a degraded outcome as clean success), and `failed` arrives as HTTP 500 WITH THE FULL REPORT AS THE BODY — so a naive catch throws away exactly the `failed[]` list AC #3 has to render. It is returned as a result, not an error. The remaining shapes are a 400 string detail (the commonest outcome for a paste UI), a 422 LIST detail, a bare 5xx, and no response at all. 2. `preview` is bound to `previewedText`, the exact string it was produced from, and Deploy is gated on them matching. Without that a user previews manifest A, edits to B, and deploys B while reading A's preview. Any source change — keystroke, file, or bundled card — invalidates it. Honesty rules the components follow, because each corresponds to a real way the backend can mislead: * Deploy result is headed "agents created", never "success". `status` describes agent creation ONLY — folder, permission, schedule, tag and start failures all land in `warnings[]` while `status` stays "deployed", so a fleet where every schedule failed and nothing started still reports "deployed". Warnings therefore get their own prominent panel, not a footnote. * The preview never says a manifest "will deploy": `github:` templates are not probed, and the topology is resolved against ALL agents while a partial deploy wires up only those created. Both are stated in the UI. * Deploying a manifest that sets `prompt:` or carries enabled schedules is gated behind an explicit acknowledgement checkbox, not a banner. It replaces the platform-wide prompt for every agent on the instance and/or starts recurring autonomous executions that spend budget — a banner is not consent for that. * An `_N`-duplicate warning is a confirm-grade panel, since on a fresh install re-installing a bundled manifest hits it by default and recovery is manual. * A timeout or a bare 5xx renders "outcome unknown — may still be running" and deliberately does NOT offer retry: cancelling the request does not cancel the server, and re-deploying duplicates every agent that succeeded. It offers the agent list instead. AC #5 (no dead empty state): deploy always tags every created agent with the system name, so `/?tags=<system>` is a fallback that always works, with `/?view=<id>` preferred when the manifest declared a system_view and it was created. Dashboard.vue gains a small additive reader for both, mirroring its existing `?onboarding=1` handling and yielding to an active system view. Plain textarea, not the orphaned monaco YamlEditor.vue: monaco is a declared dep but unreachable (that component has had zero consumers since the Process Engine was decommissioned), and prod CSP is `script-src 'self'` with no unsafe-eval and no worker-src, while the dev CSP allows unsafe-eval — so `npm run dev` cannot prove prod. Every AC is satisfiable without it. Deferred with that reason recorded so it is not re-litigated blind. Systems tab gated on `hasMinRole('creator')` mirroring the endpoint (AC #6), with an explanatory empty state rather than a blank panel for lower roles. Note hasMinRole is a plain function — the composable's own docstring says `hasMinRole.value(...)` and is stale. All manifest-derived text (descriptions, failure reasons, warnings) renders as plain text, never v-html (H-005): `reason` is credential-sanitized server-side but NOT HTML-sanitized. Verified with a real production build (`npm run build`) since /verify-local is blind to src/frontend — clean, and all three components plus the store are present in the Templates chunk rather than silently tree-shaken. Refs trinity-enterprise#126 * test(e2e): system-install surface — tab, preview, and both transport traps Playwright coverage for the ent#126 install surface, driving the real stack: ?tab= deep-linking and reload survival, a bundled card loading into the editor, the preview's agents/topology/schedules tables, the acknowledgement gate for a manifest with enabled schedules, edit-after-preview disabling Deploy, and named error messages for both a 400 validation failure and malformed YAML (AC #4 — asserting the absence of "[object Object]" and "Traceback", the two shapes a naive normalizer produces). Both backend transport traps are exercised, since each is a distinct way a store can be wrong: * `status: "invalid"` arrives at HTTP 200, so a store switching on the HTTP code would render a blocked manifest as a clean, deployable preview; * `status: "failed"` arrives at HTTP 500 with the full report AS THE BODY, so a naive catch discards exactly the failed[] list AC #3 has to render. No test deploys for real by default. A deploy creates containers and there is no un-deploy — re-running a manifest creates `_N`-suffixed duplicates rather than converging — so an automated deploy would litter whatever stack it runs on. The one deploy assertion is behind SYSTEM_INSTALL_DEPLOY=1 and uses a manifest that cannot create anything (an unresolvable local: id), so even opted in it has no side effects. Advisory, not a required gate: frontend-e2e auto-runs on any PR touching src/frontend/** since #1526, and its known failure class is modal/overlay flake on a fresh zero-agent stack. Refs trinity-enterprise#126 * docs(systems): record the UI manifest install surface (ent#126) Rule #1 deltas for trinity-enterprise#126. feature-flows/system-manifest.md is the highest-signal edit: it told every reader "### UI — Status: Not yet implemented" and "## Frontend Layer — No UI implementation yet (API-only feature)", listing SystemManifestEditor.vue / SystemsList.vue / SystemDetail.vue as planned. Rewritten to what actually ships (three components + the store + the Templates tab host), with the six-shape error contract as a table, the honesty constraints and why each exists, and an explicit "still not built" section — SystemDetail.vue and a deployed-systems browser stay unbuilt and unowned, and the two retired component names are retired rather than left standing as a promise the doc keeps making. roadmap.md: new §16.5.2, and two corrections to §16.5 itself — it called `status` "tri-state ... plus valid", omitting `invalid` (added by #1841), and never recorded that `status` covers AGENT CREATION only, so a consumer rendering `status` without `warnings` can report a fleet as deployed when every schedule failed and nothing started. The trailing "prerequisite for ... UI manifest install" pointer now resolves to §16.5.2. architecture.md: the router and service catalog lines (kept to the ≤2-line catalog rule, detail in the flow doc), a Frontend note for the Templates tabs + stores/systems.js, and a System Manifests endpoint table carrying the Invariant #4 warning for BOTH collisions plus the `/api/systems/manifests` vs `/api/systems/{name}/manifest` naming adjacency. feature-flows.md: a Recent Updates index row, added by hand — /sync-feature-flows reliably forgets it. user-docs: an "Installing a system from the UI" section written for an operator, not a reader of the source. It leads with what the confirmation gates mean (a top-level `prompt:` replaces the global prompt for every agent; a schedule is enabled unless you say otherwise, so the fleet starts spending budget on a timer), how to read each of the five outcomes, why "agents created" is not "success", and why an "outcome unknown" must be checked rather than retried. Also states the two deliberate preview limits: `github:` templates are unverified until deploy, and agent names are provisional. Refs trinity-enterprise#126 * test(systems): guard the manifest-catalog route order in the assembled app /update-tests coverage review found the one gap the ent#126 suite structurally could not cover. `test_ent126_manifest_catalog.py` mounts `routers/systems.py` alone on a bare FastAPI app, which proves ordering WITHIN the router but says nothing about the real application, where 60+ routers are mounted and the handler is decided by the first FULL match across all of them. This is the #1069 class the test-runner catalog already calls out for the brain-orb routes. So this imports the assembled `main.app` and asserts the first FULL match for both Invariant #4 collisions — `/api/systems/manifests` vs `GET /{system_name}`, and `/api/systems/manifests/manifest` vs `GET /{system_name}/manifest` — plus that all three shadowed siblings (`get_system`, `get_system_manifest`, `deploy_system`) still resolve, so `manifests` is a genuine static-before-param precedence rather than a total shadow. OpenAPI is an order-independent path set and is therefore blind to this, so a schema check cannot catch it; a match-order assertion is the only guard. Mirrors `test_1483_route_order.py`, including its self-sufficient env setup and its loud-skip guard for the whole-directory sweep (an earlier module binds sys.modules['utils'] to tests/utils, so `import main` fails there — the assertions run standalone). Confirmed to fail on the bug rather than merely passing: moving the two routes below `/{system_name}` turns both collision tests red with "resolved to get_system" and "resolved to get_system_manifest" respectively. Note: /update-tests also updates `.claude/agents/test-runner.md`, which lives in the private trinity-dev submodule — that edit is deliberately NOT committed here, since bumping the gitlink would point this public branch at an unpushed private commit. Refs trinity-enterprise#126 * docs(tags): record the ?tags=/?view= deep link as a Dashboard filter entry point /sync-feature-flows gap: `views/Dashboard.vue` changed on this branch, and `agent-tags.md` — not `system-manifest.md` — is the doc that owns the Dashboard quick-tags / activeFilterTags mechanism in detail. It described two entry points into that state (a quick-tag click and a System View selection); ent#126 added a third (`applyDeepLinkFilters()` in onMounted), and a reader of that doc had no way to know a URL can seed the filter. Documents the precedence (`?view=` wins because a view carries its own filter tags; `?tags=` yields entirely when a view is already active) and why it exists — manifest deploy always tags every created agent with the system name, so `/?tags=<system>` is the always-works fallback that keeps a fresh install off an unfiltered dashboard. Refs trinity-enterprise#126 * fix(ui): the deploy acknowledgement must not survive a manifest edit Self-review of the ent#126 diff found the consent gate had the exact hole the preview/previewedText binding was built to close, one field over. `acknowledged` was reset when picking a bundled card, choosing a file, or starting over — but NOT when the user typed in the textarea. So: preview a manifest with enabled schedules, tick "I understand and want to continue", edit the YAML, preview again → the box is still ticked and Deploy re-enables. The user consented to manifest A's consequences (replacing the platform-wide prompt, starting recurring autonomous executions) and deployed manifest B's. Consent is per-manifest, so it now dies with the text it was given for: a watcher on `store.manifestText` clears it. That covers every source, because typing, file upload and bundled-card selection all funnel through `setManifestText`. Pinned by a new e2e case that ticks the box, edits to a different manifest with the same hazard shape, re-previews, and asserts the box is clear and Deploy is blocked. Also drops `duplicateWarnings` from the store: it was exported but never consumed (ManifestPreview.vue computes its own split, since it needs both halves — the duplicates get a confirm-grade panel and everything else a notes list), so it was a second copy of the same heuristic with nothing to keep it in step. Rebuilt clean. Refs trinity-enterprise#126 * fix(systems): stop the schedule preview claiming it validates cron Self-review caught a code comment that promised more than the code delivers. The plan this was built from called it a "cheap completeness win — build a throwaway ScheduleCreate inside the resolver purely to borrow its validation, so a bad cron surfaces in the preview instead of degrading to a post-deploy warning", and that premise is simply false: `ScheduleCreate` declares `cron_expression: str` with **zero** validators (verified — the model has no field_validator/model_validator at all), and `validate_manifest` only checks that the `cron` KEY is present. Nothing parses the expression. A comment that overstates a guard is worse than no comment: the next reader trusts it and stops looking. So the docstring now states what the mechanism actually catches (a schedule entry whose field TYPES the model rejects — reachable, because validate_manifest's checks are presence-only, so a non-string `name` passes validation and then fails construction) and states the gap explicitly: a syntactically invalid cron previews clean, deploys clean, and surfaces only when the scheduler tries to arm it. Left as a documented gap rather than silently half-fixed, because validating cron here would change a shipped path — manifests with a bad cron deploy today. Both halves are now pinned, including the gap: `test_a_syntactically_invalid_cron_is_NOT_caught` asserts the current contract, so if cron validation is ever added that test is the one that must change, deliberately. Also adds coverage for the model-rejects-a-schedule branch, which was written but untested. Refs trinity-enterprise#126 * fix(config): wire TRINITY_MANIFESTS_DIR into both compose files + .env.example /validate-pr's Config Packaging gate (the #1056 / trinity-enterprise#31 class): a backend `os.getenv()` that is not in `backend.environment:` of BOTH compose files is an inert lever on deploy. `TRINITY_MANIFESTS_DIR` was in 0 of the 3 files while its sibling `TRINITY_DEFAULT_SYSTEM_MANIFEST` — same feature area, same shape — is in all 3. Prod compose launches standalone with no base-compose merge and no `env_file:`, so dev-only wiring would not have carried over anyway. Worth noting the gate's own grep did NOT catch this: it matches literal `os.getenv("X")`, and this call site reads `os.getenv(MANIFESTS_DIR_ENV)` through a module constant. Found by diffing against the sibling variable instead. Verified by RENDERING the container environment (`docker compose config`) rather than grepping the source — both files now emit `TRINITY_MANIFESTS_DIR` into the backend env. That render also surfaced a real consequence: with `${TRINITY_MANIFESTS_DIR:-}` every deployment now sets the var to the EMPTY STRING unless an operator overrides it. `_manifests_dir()` uses `os.getenv(...) or default` so empty falls back correctly — but had it used `os.getenv(name, default)`, `""` would have won, `Path("")` is the CWD, and the catalog would have listed nothing on every single install while looking perfectly configured. That is the #1759 trap one seam over (an empty `HOST_TEMPLATES_PATH` making `Path("") / name` an empty named volume), so it is now pinned by a test rather than left as a lucky choice of operator. Docs state the operator contract honestly: the env var alone is not enough, since the directory must also be bind-mounted, and an unreadable path yields an EMPTY catalog rather than an error. Refs trinity-enterprise#126 * fix(systems): harden the manifest read path against its own error reporting Four review findings, each a case where a guard could fail on the input it was guarding. - The unknown-top-level-key warning (added so a `trinity_prompt:`-for-`prompt:` typo stops being silently dropped) sorted raw YAML keys. PyYAML is YAML 1.1: bare `on`/`off`/`yes`/`no` parse as booleans and `2:` as an int, so a mixed-type key set made `sorted` raise TypeError and the catch-all turned it into a raw 500 -- on a manifest that deployed fine before the check existed. Coerce with `str()`. A hygiene check whose purpose is better error reporting must not be able to raise on the input it reports about. - `max_length` counts characters; the stated limit is bytes. Kept as a cheap necessary pre-check and added a byte-exact validator, so the request cap, the bundled reader's `st.st_size` and the UI's `file.size` cannot disagree on a multibyte manifest. - Catalog `reason`s went out as raw `str(e)`. PyYAML parse errors echo the offending source line and `validate_manifest` interpolates manifest values, so route them through `_failure_reason` -- the same credential-sanitizing, userinfo-redacting, length-capping exit the deploy report already uses. The join of N capped reasons needed its own cap. - `_resolve_manifest_path` refused only symlinks escaping the directory, while the listing skips symlinks outright. A symlink pointing *inside* was therefore invisible in the catalog yet readable by id -- "not listed" stopped meaning "not served". Checked pre-`resolve()`, which has already erased the link. Co-Authored-By: Claude Opus 5 <[email protected]> * fix(ui): keep the stale-preview hint reachable and let ?tags= win Two dead paths in the install surface. `invalidatePreview` cleared `previewedText` alongside the preview payload, so the "manifest changed -- preview again" branch could never be true: editing after a successful preview told the user to "Preview first", as if they never had. The marker exists precisely to tell "never previewed" apart from "preview is stale", so it now outlives the payload; only `reset()` (start over) drops it, where "Preview first" is honest again. It cannot re-enable Deploy on its own -- `previewIsCurrent` also requires a non-null `preview`, and that IS cleared. The hint was additionally keyed on `preview` rather than the marker, which made the branch unreachable a second time. `applyDeepLinkFilters` bailed out whenever a system view was active, deferring to it. But `initialize()` restores that selection from localStorage before this runs, so the post-deploy "View this fleet" link silently no-opped for anyone carrying a view from a previous session -- and the `activeFilterTags` watcher would overwrite the tags anyway once views loaded. An explicit `?tags=` now clears the selection, exactly as picking a tag chip does. That is AC #5's whole point: the deploy must not end in a dead end. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(systems): document the bundled-manifest catalog surface The two catalog endpoints shipped without reaching the feature flow at all -- absent from Entry Points, absent from the Router Layer, and their security properties undocumented. Adds both, plus a table of the layered path confinement stating what each layer actually guards against (the character allowlist does NOT reject `..` -- `.` is inside its class -- and the symlink check must precede `resolve()`), the fail-soft contract, and the naming adjacency with `/api/systems/{name}/manifest`, which reads alike and is unrelated. Also reconciles requirements + architecture with this branch's review fixes: the byte-exact manifest cap, the YAML 1.1 key coercion, the sanitized catalog reasons, and the symlink parity check. Adds the missing ent#126 Revision History row, and records the "a hygiene check became the 500 it existed to prevent" pitfall in learnings.md. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Aug 10, 2026
…ore (ent#356) (#2084) * feat(workspace): move client_portal from the entitled seam into OSS core (ent#356) The workspace is the main surface a non-operator uses to work with agents, and it was gated behind the paid tier: `register_module("client_portal")` plus `requires_entitlement("client_portal")` on the router, so a community build mounted the code and 404'd every endpoint. That capped adoption at exactly the population we most want using it (Intelligence Design Weekly, 2026-08-07). WHAT MOVED `src/backend/client_portal/` — router, service, db, models, portal_auth — moved wholesale from the private submodule. It imports only OSS modules (db.engine, db.tables, dependencies, models, services.platform_audit_service, utils.helpers), so the move is self-contained; no enterprise sibling comes with it. Kept as a package rather than split across routers/services/db so the diff reads as the move it is; aligning it with Invariants #1/#2/#14 is a separate refactor if the team wants one. Mounted unconditionally in main.py. The entitlement dependency is gone, and the seven test files that covered it move to tests/unit/ as test_ent*_*.py. WHAT DELIBERATELY DID NOT MOVE The `/api/enterprise/client-portal` prefix and the `enterprise_portal_sessions` / `enterprise_portal_messages` / `enterprise_client_blocks` table names stay. ent#83 shipped that prefix as the documented integration surface for API-only clients, and renaming the tables would force a data migration on every entitled install — "no data migration, no re-auth for signed-in clients" is an acceptance criterion. Both names are retained history, not licensing, and both are commented as such where a reader will hit them. TABLES: ADOPTED, NOT CREATED DDL now lives in db/schema.py and is versioned on the OSS two-track runner (`client_portal_tables_to_oss` for SQLite, Alembic `0036_client_portal_oss`) — Invariant #9. Every CREATE TABLE/INDEX on both tracks is IF NOT EXISTS, so on an install where the enterprise runner already made them this is a no-op; it does real work only on a fresh or community build. The Alembic downgrade is deliberately empty: this revision adopted tables holding live client conversations, and dropping data it never created is the one outcome the move promised could not happen. A LATENT BUG THE MOVE FIXES `test_agent_cleanup_parity` failed the moment the DDL landed in db/schema.py: the portal tables were never in AGENT_REFS, because the enterprise track sits outside that registry. So an agent rename left portal history keyed to the old name — the client's thread simply emptied, with nothing logged — and a purge orphaned the rows. Both `agent_name` columns are now registered CASCADE, and the rename path re-keys them (verified against a real SQLite file). COUPLED SURFACES, MOVED IN THE SAME CHANGE * `enterprise_features` no longer advertises `client_portal` (verified: an OSS-only build reports `[]` and still mounts all 16 routes). * Frontend de-gated: the enterprise module catalog no longer lists it, and PortalClientsPanel's `isEntitled('client_portal')` is gone. * `.github/workflows/enterprise-docs-guard.yml` — its PATTERN forbade the token `client_portal` in main.py and public docs, which this change necessarily introduces. The token is removed and `enterprise_portal_*` / `enterprise_client_blocks` are exempted, each with the reason inline. * architecture.md documents the surface, now that it is legitimately public. VERIFIED TRINITY_OSS_ONLY=1, submodule absent: 16 client-portal routes mounted, enterprise_features == [] migrated portal suites: 156 passed, 1 skipped new OSS-core guards: 11 passed cleanup-parity / entitlement-seam: 118 passed Enterprise-side removal (deleting the module + its `_register_module` call) is a separate PR in the private repo. Order is safe either way: while both exist the OSS route is registered first and wins, which is the intended end state anyway. Related to Abilityai/trinity-enterprise#356 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(ci): ship client_portal in the prod image, wire its tables, de-fang the email regex (ent#356) Three CI failures on #2084, three different classes. 1. prod-image-smoke — THE REAL ONE. ModuleNotFoundError: No module named 'client_portal' `docker/backend/Dockerfile` copies module directories one by one, and a new top-level backend package that is not listed builds a perfectly good image whose app dies at import. That is #1033's class exactly, and source-only CI cannot see it because the source tree always has the directory. Added the COPY, with a comment saying why the line exists. Verified by reproducing the image's filesystem: copy only what the Dockerfile copies, then `import main` — 16 client-portal routes mount. 2. regression diff — 34 HEAD-only failures, all rename/volume tests, all mine. KeyError: 'enterprise_portal_messages' `db/agent_cleanup.py` resolves every AGENT_REFS entry through the `db/tables.py` MetaData, and the portal tables were never in it — the enterprise module used raw `text()` SQL precisely because they were not OSS tables. So registering the refs (which the cleanup-parity guard correctly demanded) made rename raise. The three tables are now declared in tables.py, which is what makes them first-class OSS tables rather than half-adopted ones. 38 rename tests pass. 3. CodeQL — one new HIGH, py/polynomial-redos, in the email validator. "New" only because the move made the file visible to CodeQL; the private submodule is not scanned, so the finding is as old as the code. The regex was `^[^@\s]+@[^@\s]+\.[^@\s]+$`, and since `[^@\s]` matches a dot, the two domain atoms compete for the same characters — ambiguous by construction. Now `^[^@\s]+@[^@\s.]+(?:\.[^@\s.]+)+$`. Reported honestly: I could not measure a blowup. The old pattern handles CodeQL's own witness shape in 0.26 ms at 20k chars, and this function caps input at 320 characters BEFORE the regex runs (0.004 ms there). The new pattern is actually slower on long inputs. So this removes a latent ambiguity and a CI blocker, not an observed performance bug — the cap is what bounds the cost, and a test now pins that the cap is evaluated first, because that ordering is the only thing making the bound real. Accept/reject parity checked on real addresses; the new form additionally rejects empty domain labels (`[email protected]`), which were accepted before. 4 tests added (regex shape, cap ordering, accept, reject) — 23 in the file. Related to Abilityai/trinity-enterprise#356 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(tests): patch where the portal code resolves, not where it lives (ent#356) The regression diff reported 8 HEAD-only failures. Three separate causes. 1. test_ent196 — my own collateral damage. A blind `enterprise.backend` -> `client_portal` rename hit an unrelated static guard and rewrote the string it searches for. main.py still legitimately does `from enterprise.backend import register_enterprise` (line 1089) — the guard was pointed at a substring that no longer exists, so `.index()` raised. Reverted the file to origin/dev. 2+3. The other seven — module-identity divergence. These tests came over verbatim from the enterprise repo, where they always passed, and failed the moment they ran under tests/conftest.py. Every one failed on the REAL dependency's behaviour: patch.object(ds, "get_agent_container", return_value=object()) # in scope -> ClientPortalError: The agent is not available. Try again later. monkeypatch.setattr(pas.platform_audit_service, "log", ...) # in scope -> sqlite3.OperationalError: no such table: audit_log `import services.docker_service as ds` compiles to `getattr(services, "docker_service")` — the PACKAGE ATTRIBUTE. `client_portal.service`'s function-local `from services.docker_service import get_agent_container` resolves `sys.modules["services.docker_service"]` at call time. Normally the same object. But services.docker_service, services.settings_service and services.platform_audit_service are all on conftest's #762 _SYS_MODULES_INVARIANT_KEYS list, whose autouse fixture rewrites those sys.modules entries back to a baseline captured at conftest import. Once any earlier test in the run replaces one, the package attribute and the sys.modules entry are two different module objects for the same file, each carrying its own singletons — and the alias-form patch targets the one the code never calls. Proven by staging the divergence by hand rather than by argument: alias resolves to : STALE OLD patch.object(ds, ...) -> LIVE (patch missed) NEW patch("services.docker_service....") -> PATCHED So the fix follows the resolution path, per site: - function-local `from X import y` -> string target, which importlib resolves through sys.modules exactly as the code does; - module-level `from X import y` (router.platform_audit_service) -> patch the CONSUMING module's attribute. The test holds the same router object it calls into, so that is correct by construction whatever sys.modules says. Two properties worth naming, because they argue against trusting this fix cheaply: - A missed patch does not error. It lets the real dependency run, so the test fails on product behaviour — two of these read exactly like "upload is broken" and "logout forgot to audit", not like a harness problem. - It does not reproduce small. All six passed in every 2-4 file selection tried, and in the enterprise repo; only the full ~9,100-test unit run builds the polluting predecessor, and bisecting the eleven files that touch those keys did not find it. A green targeted re-run proves nothing here — the full tier does. Guard added: test_ent356 scans the seven portal test files for `patch.object(<alias>, ...)` / `monkeypatch.setattr(<alias>, ...)` where <alias> came from `import services.… as <alias>`. Verified to go red on an injected offender — and it found a seventh live site (services.task_execution_service) that had not failed yet. Learning recorded in docs/memory/learnings.md. Related to Abilityai/trinity-enterprise#356 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(tests): mock.patch and monkeypatch resolve a string target differently (ent#356) The previous commit took 8 regression-diff failures to 1, and the survivor is the interesting part: it says the fix was expressed as the wrong rule. That commit converted alias-form patches to "the string target form" as one uniform change. But `mock.patch` and `monkeypatch.setattr` accept the same string and resolve it by different algorithms. Staged against a deliberate divergence (sys.modules and the package attribute holding different module objects for one file — the state conftest's #762 invariant-restore produces): the product's `from services.x import f` -> LIVE (sys.modules) unittest.mock _get_target("services.x.f") -> LIVE (sys.modules) pytest monkeypatch resolve("services.x") -> STALE (package attribute) `_pytest.monkeypatch.resolve()` reduces the dotted path with `getattr`, so it lands on the package attribute — the stale object. The six `mock.patch` sites were therefore genuinely fixed and the four `monkeypatch` ones stayed broken in exactly the same way, behind a tidier-looking diff. One test kept failing for a reason the stated rule could not explain, which is what gave it away. Those four now go through `_services_module(name)`, which reads sys.modules directly — provably the object `from services.<name> import <attr>` resolves, since IMPORT_NAME with a non-empty fromlist returns the sys.modules entry. Three guards, because a rule this easy to misapply needs to fail loudly: - `monkeypatch.setattr("services.…")` is now forbidden alongside the alias form. Both mutation-tested: each goes red on an injected offender. - `test_the_two_resolvers_really_do_disagree` stages the divergence and asserts what each resolver returns. If a future pytest changes `resolve()` to read sys.modules, that test fails and says to delete the guard — rather than the guard silently degrading into cargo cult. - `_is_prose()` skips RST literals and comment lines, because both guards were flagging their own explanations: a text-scanning guard must name the pattern it forbids, so it matches itself. Re-verified after filtering that both still catch real call sites. Verification, since a targeted run already misled me once here: full unit tier, 9132 passed / 16 skipped / 0 failed. CI's 3-seed regression diff independently reproduced the same 8 -> 1 narrowing before this change, so the one remaining failure is the one addressed above. Learnings entry corrected: it had claimed the alias form was "the only one that can silently miss", which this disproves. The durable lesson is that a fix expressed as a style rule ("always use X form") is not verified until each distinct API behind that form is measured separately — the shared spelling is what hides the divergence. Related to Abilityai/trinity-enterprise#356 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(tests): stage the resolver probe with monkeypatch.setitem (ent#356) `lint (sys.modules pollution check)` flagged 4 new violations, all in the resolver-divergence probe added last commit: it wrote `sys.modules[...]` directly and restored in a `finally`. The lint is right, and the irony is the point. That probe exists to prove a bug caused by sys.modules being mutated across a test session, and it mutated sys.modules by hand to do it. A `finally` restores on the happy path and on a raise — but `monkeypatch.setitem` records the prior value INCLUDING absence (undone by deleting the key), so it is correct even if the test is interrupted somewhere the finally cannot reach, and it needs no restore code to review. Two synthetic modules leaking into a 9,000-test session is exactly the kind of cross-file pollution this file is about, one level up. No behaviour change: same divergence staged, same two assertions. Verified: tests/lint_sys_modules.py -> "OK: 194 violation(s) in 59 file(s); baseline allows 240 — no new violations". Portal + guard files: 122 passed. Not re-running the full 24-minute tier for a fixture-mechanics swap confined to one probe — the previous commit's tier was clean (9132 passed) and CI's 3-seed regression diff re-checks it anyway. Related to Abilityai/trinity-enterprise#356 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(workspace): wire the six PORTAL_* env vars into both composes (ent#356) The move brought six `os.getenv("PORTAL_*")` reads into the OSS backend, none of which were declared in `docker-compose.yml`, `docker-compose.prod.yml` or `.env.example`. Neither compose gives the backend an `env_file:`, so a bare `.env` entry never reaches the container — the #1056/#1039 packaging class the comments two lines above these insertions already warn about. Narrower than the usual instance of that class, and stated as such: every one of the six has a sane default (20/300 chat, 20/100 upload, haiku, 15s), so the feature works and the rate limits are enforced at the secure end regardless. What was unreachable was the *tuning*, not the capability — an operator could not change a portal rate limit or the thread-title model without editing compose. Wiring them is additive and changes no default. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[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 16, 2026
…2217) (#2229) * docs(canary): requirements for run-state observability (#2217) Rule #1 — requirements before implementation. Adds infrastructure.md §31.2: the /api/canary/status surface + canary_enabled feature flag, the enabled/stale/unknown contract, the shared-cursor collection-start semantics and one-cycle lag, the _max_failover + _MAX_CYCLE_LEASE threshold rationale, the H-01-one-level-up gap, and backend-agnostic-since-#1540. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(canary): CanaryStatusResponse model (#2217) Plain-field response for GET /api/canary/status — no canary-lib symbols, so it lives in models.py (Invariant #14) rather than following RunCycleRequest's in-router exception. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(canary): get_run_status + is_enabled + status cursor helper (#2217) CanaryService.get_run_status() derives enabled/healthy/stale/unknown from the SHARED canary:last_cycle_at cursor (not per-worker counters — #1881 leader lease means only one worker cycles). Fail-open: disabled never reads Redis; any read/parse failure is unknown, never stale. _read_last_cycle_for_status distinguishes Redis-down (redis_available=False) from just-booted (None, True), which _read_prev_cycle_at deliberately collapses. Threshold = _max_failover_seconds + _MAX_CYCLE_LEASE_SECONDS, both file constants, provably above the failover window AND a maxed-healthy cycle. is_enabled() is the public wrapper for the feature-flags surface. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(canary): GET /api/canary/status + canary_enabled feature flag (#2217) Admin-only /status is a thin pass-through to CanaryService.get_run_status() (Invariant #1); a distinct root literal, no Invariant #4 collision with /violations/{id}. canary_enabled joins the observability-only flag home on GET /api/settings/feature-flags (boolean only; detail stays admin-only), lazy-importing canary_service so the settings router doesn't pull the whole canary package at load. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(canary): architecture — run-state surface + /status endpoint (#2217) Adds the run-state paragraph to the Canary section (the H-01 gap one level up, shared cursor, fail-open, threshold rationale, alert_sink separateness), GET /api/canary/status to the Canary API table, and canary_enabled to the feature-flags row. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(canary): feature-flows index row + PG backend-agnostic note (#2217) feature-flows.md Recent Updates row (→ architecture.md; no dedicated flow doc). POSTGRESQL_SETUP.md §6 + SQLITE_TO_POSTGRES.md verify section: the harness is backend-agnostic since #1540, safe to keep CANARY_ENABLED=1 on PostgreSQL — so the next operator does not re-derive the retired SQLite-only constraint (AC#4). Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(canary): run-state observability guards (#2217) 20 unit-level guards under tests/unit/ (the tests/test_canary_* root suite runs in no CI workflow, #1880/#2037): disabled-never-alarms + never-reads-Redis, healthy/stale derivation, the failover (780s) and maxed-healthy-cycle (1199s) NOT-stale properties, the strict-> boundary, threshold-derived-from-constants, missing-vs-error cursor (redis_available True vs False), unparseable->unknown, future-cursor clamp, alert-sink-on-every-path, the _read_last_cycle_for_status (value, ok) contract, is_enabled env reflection, the /status handler field round-trip, and canary_enabled on feature-flags. All 20 green (also under randomized order and alongside the sibling canary suites). Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(canary): assert /status route registered + admin-gated (#2217) The pure-handler test round-trips the model with auth bypassed (None), so it cannot catch a dropped @router.get or a dropped Depends(require_admin). Add a guard that asserts GET /api/canary/status is mounted at the literal path AND carries require_admin in its dependency tree — the one wiring fact the handler-only test structurally can't see. Resolves require_admin from the router's own namespace (module-identity gotcha) and walks the dependency tree recursively (avoids the drifty get_flat_dependant). Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: trinity-ability <[email protected]>
vybe
added a commit
that referenced
this pull request
Aug 17, 2026
* test(e2e): List-mode spec + five specs adjusted for the retired Agents page (ent#260) NEW dashboard-list-view.spec.js: system-row render (data-agent hooks, SYSTEM badge, detail link; deliberately no toggle-visibility assertions — CI's only agent is the guarded system agent), AC-4 mode persistence, AC-2 redirect (param stripped, saved mode NOT rewritten), ?onboarding=1 survives the redirect + opens the wizard, name-filter narrowing + filtered-empty Clear-all recovery, three-mode round-trip. smoke.spec.js: Agents nav-link assertion dropped (nav list comment updated); 'agents page loads' becomes the redirect assertion. browser-tab-titles: the Agents hop removed from the SPA chain (Dashboard → Templates still proves the client-side repaint); /agents → 'Trinity — Dashboard' joins the redirect-title test. dashboard-grid-view: header comment (three modes; exact-name toggle selectors unaffected). dashboard-stats-overflow: 'list' added to MODES — the third toggle + chassis Create button widen the controls cluster in every mode. navbar-overflow test 3: the 640px squeeze branch is now conditional on the MEASURED overflow (4-link OSS bar may fit where 5 links overflowed; an entitled build still exercises the scroll-recovery branch) — sm=640 is the floor, below it the link row hides, so narrowing further was not an option. Full e2e run defers to CI (frontend-e2e on the ui label) — the live local stack is not exercised from this worktree. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: Dashboard List view — architecture block, new feature flow, index + superseded banner (ent#260) architecture.md: Grid-view paragraph reworded to three modes; new Dashboard List view block (AgentListPanel extraction, visibleAgents seam ownership, N+1 deletion, redirect + NavBar consolidation, zero backend change). NEW feature-flows/dashboard-list-view.md (overview, data-flow diagram, decisions D1/D2/D7/D8/D11 + the two flagged plumbing calls, teardown state-loss note, testing). dashboard-grid-view.md mode-count wording. agents-page-ui-improvements.md superseded banner (kept as history). feature-flows.md: List-view index row, Agents-page row → superseded pointer, changelog entry. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): repoint cross-cutting flow docs off the retired Agents page (ent#260) /sync-feature-flows coverage pass over the full branch diff: eleven flow docs carried live current-state claims about views/Agents.vue (avatar/toggle/meter usage tables, sync-health dot renderer, system-agent display, tag bulk-ops entry points, skills-on-start entry, dark-mode coverage row, timeline-view mode-toggle description). Live references now point at components/AgentListPanel.vue / the Dashboard chassis; dated changelog entries and explicitly-labelled historical sections are left as history. Also fixes dashboard-timeline-view.md's pre-existing stale '[Graph] [Timeline]' toggle claim to the current three-mode set. Touched: agent-avatars, agent-lifecycle, agent-tags, autonomy-mode, autonomy-toggle-component, dark-mode-theme, dashboard-timeline-view, git-sync-health, internal-system-agent, parallel-capacity, read-only-mode, skills-on-agent-start. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(dashboard): review fixes — Create-button icon-only degrade + gated fetch write-through (ent#260) Two review-stage fixes on the ent#260 branch: 1. Create Agent label degrades to icon-only below `md` (title + aria-label kept). The controls cluster is flex-shrink-0; measured against the #1830 stats-ladder constants (agents-only floor 71px), the full label at 640px in grid mode (+ the third mode button) leaves ~47px — the stats-overflow spec's clip assertion would fire. This is the plan's pre-decided degrade, applied ahead of CI. 2. The fetchAgents → agentsStore.agents write-through is now gated on no active quick-tag filter (params.tags narrows the response server-side; a filtered subset must not clobber the full-fleet list agentsStore consumers read — the Executions dropdown's cold-start self-heal is length===0-gated and never recovers from a non-empty wrong value) and writes a shallow copy (array identity per store, shared row objects so in-place status/label patches still propagate). Docs synced (architecture block, flow doc, agents.js contract comment) + a learnings.md entry for the write-through class. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): §9.9 seam wording matches the implemented deviation (ent#260) The plan's D8 wired both convertAgentsToNodes call sites through the visibleAgents computed; the implementation deliberately deferred the timeline wiring to ent#261 (ReplayTimeline :agents prop switch — rewiring the node paths was rejected as timeline-mutation risk) and the code comment + flow doc + architecture all record that. §9.9 still claimed the node-rebuild call sites consume the seam — align it. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(frontend): rename Templates.vue to Library.vue (pure move) (ent#263) Byte-pure git mv with zero content edits so git rename detection holds and a parallel edit to Templates.vue (ent#260) resolves as a content merge inside Library.vue rather than a modify/delete conflict. All content changes land in follow-up commits. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(frontend): Library page + route/nav rename with /templates redirect (ent#263) - Library.vue: h1 'Library', new subtitle, templates content wrapped in an 'Agent Templates' section (own loading/error/empty states; inner headings demoted h2->h3); fetch migrated to the shared api client (Invariant #7) - router: /library route (meta.title Library) + /templates function-form redirect carrying query AND hash; route name Templates->Library (no named pushes exist) - NavBar: label Library, to=/library, active via startsWith('/library') - CreateAgentModal: its single raw-axios /api/templates call migrated to the shared api client so no half-migrated consumer of the endpoint remains Page-identity naming only (AC#4 reading): the asset-kind noun 'template' survives inside the Library (Starter/GitHub Templates sections, Use Template). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(frontend): Library skills section — fleet browse over the skills library (ent#263) - stores/skillsLibrary.js (new): fleet-scoped store, deliberately separate from stores/skills.js (KeepAlive-cached AgentDetail means SkillsPanel's clear() never fires on nav-away — shared refs would poison the cached tab); imports nothing from stores/skills.js. 4-state emptyReason discriminator (unconfigured/not_cloned/empty + error carried separately); sync() with a 180s timeout and ECONNABORTED -> status-refetch (a first clone can outlive the 30s api.js default; client timeout != server failure) - components/LibrarySkillsSection.vue (new): sync-state header leads with commit_sha + skill_count (disk-derived; last_sync is per-worker in-memory and renders only when truthy); repo URL admin-only, userinfo-stripped, labeled 'Primary source', hidden when status.sources reports >1 (#1901 forward-compat); admin Sync now; per-kind empty states teaching the next action; dormant source_name/shadowed_by slots; interpolation only - components/skills/{SkillContractChips.vue,contract.js} (new): the #183 contract-chips seam extracted from SkillsPanel so both the per-agent tab and the Library browse render package facts from one seam - SkillsPanel.vue: consumes the shared seam (local SkillMeta/formatBytes/deps removed); stores/skills.js untouched - Library.vue: skills section wired in + header jump anchors (no ?kind=) Co-Authored-By: Claude Fable 5 <[email protected]> * test: Library e2e anchors + remove dead template-endpoint tests (ent#263) - smoke.spec.js: '@smoke library page loads' asserts chrome-only getByRole headings (h1 Library + both section headings — the old getByText(/template/i) passed on the un-renamed page and proved nothing); new '@smoke templates path redirects to library'; stale nav comment fixed (Health/Ops merged in #1109) - browser-tab-titles.spec.js: nav click asserts 'Trinity — Library'; redirect test also covers /templates -> /library title resolution - tests/test_templates.py: remove TestEnvTemplate + TestTemplateRefresh — GET /api/templates/env-template and POST /api/templates/refresh no longer exist (router has exactly 2 GET routes; live-stack probe returns 404); test_get_template_by_id now exercises the REAL detail endpoint instead of the dead env-template detour that always skipped. 5 remaining tests pass against the live stack. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: Library page — requirements, architecture, feature flow, stale-endpoint rot sweep (ent#263) - requirements/core-agent.md: new §4.5 Library Page — unified /library surface (agent templates + fleet skills browse), query+hash-preserving /templates redirect, stacked sections, per-kind empty states, the AC#4 page-identity naming rule; fleet assignment visibility named as Not Built - requirements/skills.md (surgical — §21.3/§22.2/new §22.3 only, avoiding PR #1901's §21.1/§21.5 hunks): §21.3 stale 'Skills tab is hidden' note corrected (visible since ent#235/PR #1877); §22.2 rewritten as visible/rebuilt; new §22.3 Library Page fleet skills browse — browse-only over the existing /api/skills/library reads, own skillsLibrary store + the KeepAlive rationale, admin-only URL/Sync, #1901 forward-compat, assignment read = Not Built - architecture.md: 'Top-nav IA — Library (ent#263)' paragraph beside the #1109 Operations one; stale 'Templates (4 endpoints)' table corrected to the 2 real routes (POST /refresh AND GET /env-template both verified absent) - feature-flows: templates-page.md git-mv'd to library-page.md + full rewrite (the old file was deeply stale — AgentSubNav, dead endpoints); index row + platform-settings.md Related-Flows link repointed - template-processing.md + CREDENTIAL_MANAGEMENT.md: dead env-template endpoint references removed/replaced (same rot class as the architecture table); Templates.vue references repointed at Library.vue - user docs (creating-agents.md, faq/agents.md): Templates page → Library (+ redirect note) Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): TGRAM-PROGRESS — Telegram in-progress status indicator (ent#264) New §15.1h: reaction ack + elapsed-time placeholder + channel-agnostic start/progress/resolve seam, group gating (mention/reply OR all-mode; observe stays silent), degradation ladder, default-ON per-binding toggle, GET /telegram access hardening. §15.1c/§15.1e touch-ups. Requirements-first per Rules of Engagement #1. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(channels): in-flight progress indicator seam + Telegram reaction ack and elapsed-time placeholder (ent#264) Channel-agnostic start/progress/resolve seam (Invariant #9): - base.py: default-no-op indicate_progress hook + progress_threshold_seconds/ progress_interval_seconds capability attrs (None => the router never arms a driver, so Slack/WhatsApp/VoIP behave byte-identically). - message_router.py: router-owned per-turn driver — _arm_progress_driver after step 8 (call + arm wrapped so a raising hook can never abort the turn), _progress_loop (elapsed origin captured BEFORE the threshold sleep; per-tick try/except), _resolve_indicator at all three terminals (cancels AND awaits the driver dead, settles the shielded in-flight placeholder send, THEN indicate_done — closes the tick-after-resolve and resolve-vs-first-send races by construction; carries success for the adapter's neutral fallback line), and an idempotent try/finally _cancel_progress_driver backstop. - telegram_adapter.py: indicate_processing upgraded (single binding read, per-turn cfg stash, typing preserved verbatim, 👀 reaction ack — gated on the default-ON per-binding toggle and ack-eligibility; whole body never raises); NEW indicate_progress (placeholder send-then-edit, message_id recorded INSIDE the shielded helper, disable_notification, explicit HTML, 2-consecutive-failure degraded flag over sends/edits/timeouts alike) and indicate_done (clear reaction at every terminal — no success-👍 swap; delete placeholder, neutral edit-to-done fallback); fail-soft primitives _set_message_reaction/_edit_message_text/_delete_message/ _send_placeholder_message mirroring _send_message's shape (429 retry_after capped 30s; never log the token-bearing URL). - parse_message stashes progress_ack_eligible: DMs, @mention/reply group turns, and `all`-trigger-mode groups; observe mode stays typing-only. - All per-turn state on NormalizedMessage.metadata (the adapter is a shared singleton); decrypt_telegram_bot_token facade passthrough so the hook decrypts from the row already in hand. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(telegram): per-binding progress-indicator toggle — dual-track migration, API, UI (ent#264) Default-ON toggle for the in-progress indicator, per-agent == per-binding: - Dual-track migration (Invariant #3 / Rule #9), all six touch points: SQLite `telegram_progress_indicator` in db/migrations.py + Alembic 0031_telegram_progress_indicator (down_revision 0030; renumber-at-rebase rule vs ent#265 applies to whichever PR merges second) + schema.py + tables.py DDL + _BINDING_COLUMNS + _row_to_binding. No backfill UPDATE: ADD COLUMN ... DEFAULT 1 populates existing rows (default ON is the AC). - Read predicate evaluated in Python, never SQL (`NULL != 0` is NULL): enabled ⇔ `v is None or v != 0` — only an explicit 0 disables. - db: set_progress_indicator_enabled + set_telegram_progress_indicator facade. - API: GET /api/agents/{name}/telegram surfaces progress_indicator_enabled (pinned in the hand-built response, #1809 lesson — configure PUT too) and is access-hardened get_current_user → AuthorizedAgentByName (the response carries webhook_url, which embeds the webhook secret — previously readable by ANY authenticated user; uniform-404 accessor, Invariant #8). New PUT /api/agents/{name}/telegram/progress-indicator — OwnedAgentByName + reject_agent_principal (behavior toggles are human-only, ent#223 lesson), 404 when no binding; dedicated route so toggling never re-sends the token. - models.py: TelegramProgressIndicatorRequest + response field (Invariant #14). - UI: TelegramChannelPanel.vue switch (SlackChannelPanel allow_proactive precedent), optimistic flip with revert-on-error, dark-mode aware. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(architecture): channel-adapter progress-indicator seam deltas (ent#264) base.py indicate_progress hook + capability attrs; message_router.py per-turn driver (arm/tick/resolve + backstop, inline-sync coupling named for #1081 pickers); telegram_adapter.py reaction ack + elapsed placeholder + default-ON per-binding toggle. Co-Authored-By: Claude Fable 5 <[email protected]> * test(telegram): progress-indicator unit suite — adapter, router driver, toggle (ent#264) 61 tests, no backend required. Highlights per the plan's scrutiny list: resolve-vs-first-send race (shielded id recording → delete finds it), cancel-and-await ordering at both terminal flavors, 429-backoff cancel promptness, [NO_REPLY]-still-resolves, step-8 wrap regression guard, singleton metadata isolation, degraded-quiesce after 2 consecutive failures, static-template-only egress pin (ent#224 class), live-select column test (4-file schema rule), real-DB facade round-trip (#1533 no-MagicMock), legacy-table SQLite migration + renumber-safe Alembic-twin existence, GET JSON field pinning (#1809) + AuthorizedAgentByName hardening pin, PUT reject_agent_principal 403. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(feature-flows): telegram in-progress status indicator section (ent#264) New section in telegram-integration.md: three fail-soft layers, the channel-agnostic start/progress/resolve seam, race closures (tick-after- resolve, resolve-vs-first-send, singleton concurrency), gating matrix (incl. `all`-mode groups; observe stays typing-only), toggle surface, degradation ladder / Bot API constraints, restart residual + the inline-sync coupling named for #1081/#1083 pickers, test inventory. Index unchanged (existing flow). Revision-history row added. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(telegram): access-harden the groups GET; document the bounded settle residual (ent#264) Review-stage fixes: - GET /api/agents/{name}/telegram/groups moves from bare get_current_user to the uniform-404 AuthorizedAgentByName accessor — the sibling read of the panel flow this PR already hardened. Group chat ids/titles/welcome text are tenant data; the only follow-up action (the group-message POST) was already OwnedAgentByName, so the read tier is strictly broader than every usable consumer and no flow narrows (incl. the MCP list_channel_groups path, whose paired send is owner-gated). - Route-dependency test pinning the groups-GET accessor (mirrors the binding-GET hardening pin). - Docs honesty: the resolve-path in-flight settle is bounded at 10s — a first placeholder send slower than that (429 retry_after >= 10s) is abandoned and can strand a self-dating placeholder. Named in the feature flow Residuals + requirements Known residuals instead of implying the race is closed unconditionally. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(db): source_channel_agent + telegram allow_proactive columns (ent#265) Dual-track migration (Invariant #3 / #1183): SQLite entry channel_report_back_columns + Alembic 0031_channel_report_back (single linear head off 0030), plus db/schema.py + db/tables.py so fresh builds stay correct. - schedule_executions.source_channel_agent (nullable TEXT): the agent whose channel binding owns the execution's INHERITED context (D1 Option A). Written only at the /task row-creation point; NULL for direct rows (reporter falls back to the executing agent). - telegram_group_configs.allow_proactive INTEGER DEFAULT 1: per-group completion-report consent, default ALLOW for existing AND new groups (opt-out mute; no backfill UPDATE needed). - create_task_execution accepts + inserts source_channel_agent; row mapper + ScheduleExecution model surface it. - AgentRef(schedule_executions.source_channel_agent, KEEP) so cascade_rename re-keys the binding agent (D1a); parity-test locks consciously updated (_AGENT_ID_COLUMNS + KEEP set). - Telegram group-config ops carry the flag (columns tuple, row mapper default-allow on NULL, update_group_config arm, explicit insert); database.py facade adds get_telegram_chat_link and converts the group-config passthrough to keyword args (eng M3). - TelegramGroupConfigResponse/UpdateRequest carry allow_proactive (Invariant #14; the response model IS the GET field allowlist). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(chat): persist inherited channel context at /task row creation (ent#265 D0) The ent#224 inheritance wire was severed: run_async_task threaded _inherited_channel_context's values into execute_task(source_channel=...), but execute_task writes channel columns ONLY in its no-execution_id creation branch — and the /task path always pre-creates the row in create_task_execution_and_activities. Every delegated row carried NULL channel context at terminal time, so the shipped Slack delegated report-back was latent dead code on its flagship path. - Resolve inheritance at the single row-creation point both the async and sync /task branches route through (the fork to _dispatch_async/_dispatch_sync happens AFTER creation), and persist all four fields on the row itself via db.create_task_execution. - _inherited_channel_context returns a 4-tuple: + source_channel_agent (D1 Option A — parent's own binding agent, else the parent's agent name; transitive across A→B→C; all-None when the parent lacks source_channel, so a channel-less child never carries a dangling agent pointer). - Provenance guard (security): db.get_execution(parent_id) is a global lookup; the inherited identity now also resolves a bot token. Agent caller (x_source_agent, already past the SELF-EXEC-001 spoof guard in derive_source_and_trigger) must BE the parent's executing agent; human caller must have access to the parent's agent. Failure → no inheritance, info log — fail-open to no-context, never to someone else's chat. - Remove the dead source_channel* threading from run_async_task (execute_task keeps its channel params — message_router uses them for direct turns). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(channels): Telegram completion report-back + failure-applier hook (ent#265) Telegram edition of the ent#224 Slack report-back: a Telegram-triggered long/delegated task posts its terminal back to the originating chat, threaded to the triggering message. channel_completion_report.py rework: - D10 resolver dispatch map (_CHANNEL_RESOLVERS: slack + telegram); SUPPORTED_CHANNELS derives from the map keys, so WhatsApp is additive. - D1 binding-agent resolution for BOTH channels: consent + bot token evaluate against binding_agent = row.source_channel_agent or row.agent_name — the bot the user actually addressed delivers (on Telegram no other bot even CAN deliver the DM). NULL column = legacy fallback, byte-identical pre-#265 behavior. Also fixes Slack's delegated case (previously suppressed whenever worker B wasn't bound to the originating channel); narrowing direction (channel consented to B but not to originating A → now suppressed) is intentional. - D2 Telegram consent: known group → is_active AND allow_proactive (default allow, opt-out mute); known DM chat link → consent-by-construction (the user cold-started the bot; a block is a 403 the send handles gracefully); unknown destination → suppress+log. - D5 rendering: pre-escape &/</> before _markdown_to_html (unescaped `<class 'ValueError'>` trips "can't parse entities" and the strip-HTML fallback deletes the substring), then post-conversion re-cap to 4096 ("message too long" is a 400 the parse-fallback does not catch). - D6 threading: reply_to_message_id when thread is numeric, DMs too; allow_sending_without_reply makes a deleted original safe. - D1c attribution: Telegram has no per-message sender name — when binding_agent != executing agent the head line names the worker. Slack keeps username=executing agent (unchanged). - D9 pin: effect_guard keeps agent_name = the EXECUTING agent (row.agent_name), never binding_agent — resolve_and_validate_execution fail-opens on mismatch, silently disarming dedup for exactly the delegated rows this feature exists for. - D4: failed send returns False INSIDE the guard (claim completes) — at-most-once bias, never blind-retry an ambiguous send. task_execution_service.py (D3, channel-agnostic — fixes Slack AC#2 too): the failure applier's CAS-won block emitted the #1578 event but never the channel report — the path agent-reported failure envelopes take. Sibling spawn added; CANCELLED envelopes report too (uniform with _write_terminal_and_gate). routers/telegram.py: PUT group-config passes allow_proactive through; the allow_proactive arm ONLY is human-only (reject_agent_principal — an agent-scoped key resolves to the owner and could self-grant consent, ent#223's own post-ship pitfall). TelegramChannelPanel.vue: per-group "Completion reports" opt-out checkbox in the panel's house idiom (updateGroup passthrough). Co-Authored-By: Claude Fable 5 <[email protected]> * test(channels): ent#265 suite + facade passthrough fix caught by it New tests/unit/test_265_telegram_completion_report.py (41 tests): - Wired-mock layer: Telegram delivery/consent/rendering decisions — delegated group report + threading, DM consent-by-construction, muted/inactive/unknown-destination suppression, graceful bot-cannot-post, inline-trigger no-double-post, D5 escape+cap, D1c attribution, D1 binding-agent resolution (telegram + slack) incl. the intentional Slack consent-narrowing pin (D1b). - Chokepoint layer: apply_result failure branch spawns the report on CAS-win only (D3), success-branch pin, CANCELLED-envelope report. - Real-DB layer (db_harness): D0 row READ-BACK inheritance tests (a SimpleNamespace mock row cannot see a severed write path — the exact reason ent#224 shipped broken), both provenance-guard arms, channel-less parent all-NULL, two-hop transitive root binding agent; REAL effect_guard replay with source_channel_agent != agent_name (D9/M1 — a binding_agent passthrough fail-opens resolution and posts twice → red); fan-out one-report-per-child (G3); live column SELECTs through db/tables.py metadata; group-config default-allow + kwargs round-trip (eng M3); router PUT round-trip incl. agent-principal 403 and the surgical-gate proof that trigger_mode stays agent-callable. Conscious test_224 edits: non-slack scope test → whatsapp-only (telegram grew a leg); consent fixture keyed on the binding agent. The read-back tests immediately caught a REAL gap: database.py's create_task_execution facade passthrough was missing source_channel_agent (the ops layer had it) — every /task dispatch would have raised TypeError. Fixed here; the exact severed-wire class D0 exists to kill. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): Dashboard type-to-filter — new §9.10, §9.9 seam note updated (ent#261) Trinity Rule #1: requirements before implementation. §9.10 specifies the / hotkey filter across Timeline/Grid/List — store-seam predicate, pre-query node invariant, pill honesty, Esc layering, chassis query-empty overlay, kbd hint, list-mode composition, and the deliberate timeline owner-filter behavior change. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(dashboard): / type-to-filter across timeline, grid, and list (ent#261) Store seam (network.js): non-persisted filterQuery + setFilterQuery; the visibleAgents seam splits into ownerFilteredAgents (tag ∘ owner, pre-query) and the query-aware visibleAgents (slug + display label via agentDisplayName, #1642). ALL THREE convertAgentsToNodes call sites now read the pre-query ownerFilteredAgents — incl. the 30s poll that previously rebuilt from the RAW list (nodes must never be query-filtered: timeline row enrichment would degrade after Esc). Dashboard chassis: document / keydown with guards (defaultPrevented/repeat, chords, IME, editable targets, open modals) + Firefox quick-find preventDefault; floating filter pill (open OR active — an applied-but-hidden filter is the dishonest state) with live 'X of Y match', Esc hint, x button; input-scoped Esc + gated document Esc backstop (tag-dropdown layered dismissal, native select skip); Enter blurs and keeps the filter; header kbd / toggle button (mouse/touch parity); ONE chassis query-empty overlay with panes MOUNTED underneath; true-empty onboarding CTA branches guarded && !filterActive; timeline :agents switched to the visibleAgents seam (owner filter now applies to timeline rows too — deliberate, release-noted); query cleared on unmount. AgentListPanel: N/M badge suppressed while the chassis query is active (two disagreeing denominators never render simultaneously). ReplayTimeline: data-agent test hook on row labels (no logic change). Co-Authored-By: Claude Fable 5 <[email protected]> * test(e2e): dashboard type-to-filter spec — 8 tests across all three modes (ent#261) Covers: grid live-filter + query-empty with the pane MOUNTED + Esc restore (@smoke); timeline row hiding via the :agents seam; list query-empty preceding the onboarding CTA + pill-x clear; editable-target guard + literal '/' inside the pill; kbd-hint toggle; non-persistence across reload; cross-mode filter survival + the document-Esc backstop after focus wanders; Enter blur-and-keep. Spec rules per plan: focus-wait before keyboard.type (nextTick focus race); regex count assertions (/^1 of \d+ match$/ — X is the claim, Y is environment). Full run defers to CI via the ui label. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): type-to-filter folded into the three dashboard flows + architecture note (ent#261) architecture.md: Grid-view block gains the type-to-filter seam sentence; the List-view block's seam description now covers all three panes. Flow deltas: grid — filter rides the absence-as-filtering layout path (pane stays mounted under the query-empty overlay); timeline — FILTER-001 gains a deliberately NOT-persisted row + a new ':agents = visibleAgents seam' section naming the owner-filter behavior change and the pre-query node invariant; list — D8 seam updated to landed state + the chassis-query ∘ panel-filter composition rules (badge suppression, overlay precedence). feature-flows.md changelog entry (no standalone flow doc, per plan D11). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(dashboard): review fixes — modal z-order, dual empty-state CTA, Esc scope, structural e2e backstop (ent#261) Four review findings on the type-to-filter, fixed in place: - CreateAgentModal was fixed z-10 — UNDER the new z-30 filter pill and z-20 query-empty overlay, so chassis chrome floated above the open modal. Raised to z-50, the house modal tier (SystemViewEditor / OnboardingWizard). Safe in all three mounts (wizard renders it v-if-exclusive with its own z-50 chrome). - AgentListPanel's filtered-empty card assumed the panel never mounts with a zero-agent prop — no longer true under a chassis query zero-match, so it rendered a second contradicting CTA under the query-empty overlay. Gated on a non-empty prop; the chassis overlay owns query-zero messaging (the behavior the list-view flow doc already described). e2e test 3 now pins it. - Document-Esc backstop generalized from the select-only guard to all editable targets: Esc inside the list panel's search box (or any other input/textarea/contenteditable) belongs to that control — it must not clear the chassis filter. Pill input unaffected (own handler stops). §9.10 wording updated to match. - e2e test 7's coordinate click (400,250) on the timeline pane could land on an agent row/toggle on seeded fleets — replaced with a structural pillInput.blur(). npm run build green; spec collects 8 tests. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): overlay-chrome z-order re-pricing + mount-invariant comments (ent#261 review) Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): sibling-route access-hardening class from the ent#264 review Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): sync pass — seam note in skill-assignment, Recent Updates row, dead skills-management link purge (ent#263) /sync-feature-flows verification pass over the branch diff: - skill-assignment.md: note that SkillsPanel's package-fact chips now render via the shared components/skills/ contract seam (extracted in ent#263) - feature-flows.md: Recent Updates row for ent#263; removed the stale 'Skills Management UI' index row — skills-management.md was split/archived long ago (the archive table records it) and the live row pointed at a missing file - library-page.md: repointed its two skills-management.md links (propagated from the stale index row) at skill-assignment.md Co-Authored-By: Claude Fable 5 <[email protected]> * fix(library): harden stripUserinfo against silent-no-op and non-parseable URL shapes; share it with SkillsPanel (ent#263 review) Adversarial testing of the display-layer credential scrubber proved five leak shapes. Two families: the regex fallback under-matched what new URL() rejects (git+ssh:// schemes, protocol-relative //user:token@host, leading whitespace), and — worse — schemeless/scp user:token@host shapes PARSE as a WHATWG URL with an opaque hostless path where .username/.password assignment is a silent no-op, so the credential sailed through the success lane untouched. - move stripUserinfo to the shared components/skills/contract.js seam - trust the parsed lane only when host is present AND the strip verifiably took (post-assignment username/password empty); otherwise fall through to a widened textual scrub (scheme charset [A-Za-z][\w+.-]*, protocol- relative, schemeless colon-user, trim) - variant analysis: SkillsPanel's library_empty state rendered the RAW stored URL to any agent accessor — now scrubbed through the same helper - verified by an executed 26-case suite (23 adversarial leak shapes ALL PASS + 3 must-survive-unmangled regressions: plain https, scp git@host:path, path-@ preserved) - durable class captured in docs/memory/learnings.md Co-Authored-By: Claude Fable 5 <[email protected]> * docs: purge the second dead skills-management link; cso --diff report (ent#263 review) - feature-flows.md Archived Flows table pointed at archive/skills-management.md, which does not exist (the archive/ dir never received it) — same dead-link class d23005af purged from the skills index; row now says 'document not preserved' and names the dedicated flows it split into - add the /cso --diff report for the ent#263 review: zero backend surface delta; one MEDIUM display-layer scrubber finding (proven, remediated in 820895bf with variant coverage); secrets/enterprise- disclosure/XSS/supply-chain/CI categories clean Co-Authored-By: Claude Fable 5 <[email protected]> * docs(channels): channel report-back flow + requirements — pays the ent#224 debt (ent#265) - requirements/public-access.md: NEW §15.1h "Channel Completion Report-Back (CHANNEL-REPORT — ent#224 Slack, ent#265 Telegram)" — generic mechanism (inherited-context-only, D0 row-creation persistence + provenance guard, binding-agent resolution, chokepoints incl. D3, effect-guard at-most-once, sanitize-before-truncate), per-channel consent units, the two-DM-consent- regimes rationale (F6), known v1 limits, the deliberate ungated proactive-send scope cut. (§15.1f was already taken by WHATSAPP-001 — plan's placement kept, id shifted to h.) - feature-flows/channel-completion-report.md: NEW flow doc — entry points, D0/D3 fixes, chokepoint coverage table with the v1 boundaries (lease-reaper, bulk sweeps, pull sink, operator-terminate, restart mid-inline-turn, FAILED→SUCCESS resurrection, fan-out per-child, pre-migration NULL rows), destination/consent resolution per channel, D1 identity design with every rejected alternative, failure modes, Testing. Pays the #1763 flow-doc debt (ent#224 shipped undocumented). - feature-flows.md: Recent Updates row + Collaboration-table entry. - telegram-integration.md: ent#265 section (column + toggle + pointer) + revision row. - task-completion-events.md: sibling-spawn paragraph (report rides beside the #1578 emit at the same CAS-won chokepoints incl. the failure applier). - architecture.md: services-catalog entry for channel_completion_report.py, schedule_executions DDL line for source_channel_agent, telegram DB-module line mentions allow_proactive. - learnings.md: the D0 class — a threaded parameter only one callee branch consumes is a severed wire; mock-row suites are blind to it AND to its facade-passthrough sibling (caught pre-merge by the row-read-back tests). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(channels): key the inheritance provenance guard on the principal, not the header (ent#265) The D0 provenance guard selected its arm from the raw `X-Source-Agent` header. The SELF-EXEC-001 spoof guard in `derive_source_and_trigger` only fires when `current_user.agent_name` is set, so for a human caller that header is unvalidated client input (routers/chat.py documents the identical trap for the resume-session IDOR). Setting it to the parent execution's own agent name — a value the row itself discloses — satisfied the agent arm trivially and skipped the human arm entirely: any user with access to ANY agent could POST /task with someone else's `parent_execution_id` and have that task's terminal reported into the parent agent's Telegram DM or Slack thread, delivered by a bot binding they do not own. Second, narrower issue in the same guard: the human arm used `can_user_access_agent`, which admits share recipients. Posting into a channel chat is a proactive-send capability and every other proactive surface is owner-gated (`OwnedAgentByName` for group sends) or per-recipient-consented (#321); a share recipient can already read the owner's execution ids (`GET /api/executions` is accessor-scoped), so an accessor arm let them push a report into the owner's chat. Fix: arms are selected by the authenticated principal — - agent-scoped key must BE the parent's executing agent, - human must OWN the parent agent (`can_user_share_agent`) or be admin, - connector key (consumption-only, ent#46) never inherits, - no principal at all refuses. `x_source_agent` is still passed, now for logging only. Three regression tests, each verified red against the pre-fix guard. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): header-selected auth-guard arms collapse to the weakest arm (ent#265) Second instance of a class the codebase already warned about: routers/chat.py documents the same X-Source-Agent trap for the resume-session IDOR, and the ent#265 provenance guard reproduced it a few hundred lines away. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design-system): system of record, builder contract, reference page + raw-color scanner & ratchet baseline Stands up the frontend design system's written layer per #1430: - docs/memory/design-system.md — system of record: token taxonomy, both-theme rules incl. the dark ink ladder, type/spacing/radius scales, 10-primitive catalog with exact token recipes, the data-loading motion standard (scanline beam + wipe reveal; first load animates, background refresh is invisible), and 28 UI Construction Principles - docs/memory/design-system-contract.md — condensed binding contract to load before any src/frontend change - docs/memory/design-system-reference.html — approved visual spec (self- contained; both themes; live motion demo) - src/frontend/scripts/scan-raw-colors.mjs — raw-color scanner aligned with check-design-tokens.mjs token families - src/frontend/raw-color-baseline.json — ratchet seed at dev@5b28999: 753 raw non-gray / 383 hardcoded colors; counts may only shrink - CLAUDE.md — Rule of Engagement #10 + Memory Files row making the design system the mandatory reference for frontend work Refs #1430 Co-Authored-By: Claude Fable 5 <[email protected]> * fix: fleet restart adopts rebuilt base images through the canonical lifecycle path (#1860) (#1912) * fix: route fleet restart through the canonical lifecycle path so agents adopt rebuilt base images (#1860) POST /api/ops/fleet/restart stopped/started agents with raw Docker calls, bypassing start_agent_internal — no config-drift predicate ran and a rebuilt trinity-agent-base was never adopted on "Restart All" (#1809's cold-start gate never fired). - lifecycle.restart_agent_internal(): the canonical stop→cold-start helper (explicit stop is load-bearing for the #1809 image predicate; future home of #1817's per-agent start lock) - restart_fleet routes through it; per-agent recreated/recreate_reason surfaced via explicit allowlist copy, summary.recreated count - skips ephemeral ghosts (config predicates aren't ephemeral-gated — a recreate would destroy a volume-less ghost workspace, ent#69) - reject_agent_principal beside assert_admin (the endpoint now replaces containers — Invariant #8 escalation rule, #1816 precedent) - single-flight Redis SETNX lock ops:fleet_restart (409 on contention, own-lease refresh, compare-and-delete release, fail-open) — guards the client-timeout→retry overlap (#799/#1817 wedge class) - partial-safe fleet_restart audit entry with a per-agent recreate map (restores the entry dropped in 0ec3a7fc); sync cleanup ordered before the awaited audit so a shutdown CancelledError can't leave the lock held - actionable containerless-recovery errors (#1559), context-stats cache invalidation, 16 mocked unit tests, flow/architecture docs, learnings, CSO diff report (PASS) Fixes #1860 Co-Authored-By: Claude Fable 5 <[email protected]> * fix: never flow a raw exception message into fleet-restart results (CodeQL py/stack-trace-exposure) Per-agent failure rows now carry HTTPException .detail (platform-authored) or the exception class name only; the full message + traceback go to the backend log (exc_info). The #1559 containerless recovery hint is preserved. Tests strengthened into leak regression guards (raw message asserted absent); flow-doc line refs re-verified. Refs #1860 Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> * feat(auth): bulk portal-session revocation primitive + operator client panel (#1902) * feat(auth): bulk portal-session revocation primitive + operator client panel The OSS half of an operator kill switch for signed-in portal clients. A client who signs in through sharing holds a 12-hour portal session with no way to end it short of a backend restart, which logs out everyone. `revoke_portal_sessions_for_email(email)` is the edition-agnostic primitive: OSS owns the mint, the decode and this bulk revoke; the entitled module that mints portal sessions decides WHEN to call it (the same split as the delegated mint). Mechanism is a per-email CUTOFF, not a jti list. `jti` is random per token and nothing indexes email -> issued jtis, so answering "which tokens does this address hold?" would need a write-side index maintained at every mint. One timestamp per email is O(1) to write and read, self-expiring at the max session lifetime (same bounded-growth property as the #187 blacklist, no sweep), and — the property that matters — covers every mint path by construction, since they all go through `create_portal_session_token`. That is the failure mode a hand-maintained index has and this does not. `create_portal_session_token` now stamps an explicit `iat` so tokens can be dated against the cutoff; set there rather than in `create_access_token` so no other token type's claim set changes. `decode_portal_session` rejects `iat <= cutoff`. Rounding toward revoking is deliberate: for a kill switch, a token minted in the same second as the revoke must die. A token with NO `iat` is treated as revoked — fail closed. Only sessions minted before this shipped lack one (all expired within PORTAL_SESSION_EXPIRE_HOURS of the upgrade), and only for an email an operator actively revoked; letting an undatable token survive an explicit kill switch is the worse failure. The Redis read stays fail-OPEN, matching #187 and the platform posture. That is why revocation is not the whole feature: the durable half lives in the entitled module and keeps working with Redis down. `revoke_...` returns a bool so a caller can report honestly instead of claiming a success the operator would act on. Frontend: `PortalClientsPanel.vue` on the Sharing tab — per-client log out / block / unblock with current state. Entitlement-gated (`client_portal`), so an OSS build renders nothing. Block is hidden for non-admins rather than offered and 403'd, and the panel reports a failed revoke as a failure rather than "signed out". It deliberately shows no live-session count: portal sessions are stateless JWTs with no server-side store, so any number would be a guess. Related to trinity-enterprise#281 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(ui): use the real status-danger design token in the portal clients panel `status-error-*` does not exist — the token family is success/warning/danger/info/urgent (tailwind.config.js), and `npm run check:tokens` caught every reference. No visual change intended: danger is the red alias the invented name was reaching for. Related to trinity-enterprise#281 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> * feat(skills): library lifecycle automation — auto-sync, fleet re-inject, removal-on-unassign (abilityai/trinity-enterprise#236) (#1883) * feat(skills): library lifecycle automation — auto-sync, fleet re-inject, removal-on-unassign Closes the three "Not Built" gaps in the skills lifecycle (requirements §21.1/§21.4). All three default OFF/no-op, so a zero-config install is unchanged. Removal-on-unassign - `compute_removal` is `compute_prune` against an empty new manifest, so path confinement, `..` rejection, and the cap live in one place and cannot drift. - `remove_skills` takes the SAME per-agent lock as injection (both mutate ~/.claude/skills and read-modify-write CLAUDE.md). Only manifest paths are deleted, so agent-authored files and runtime artifacts survive; a directory the removal empties is reaped via os.rmdir, which refuses a non-empty dir. - Wired into BOTH the single DELETE and the bulk PUT — the bulk PUT is the primary UI/MCP path and drops skills far more often. - The DB unassign is authoritative and always succeeds; a stopped agent, busy lock, or dead transport degrades to a named `removal_deferred:*`. - A partially-failed removal keeps the meta AND the .gitignore line: dropping the meta strands survivors as unmanaged orphans, and dropping the ignore line lets the 15-min auto-sync commit leftover injected files (#1595/#1596 class). Start-path reconciliation - The assignment row is gone by the time a stopped agent starts, so removal is reconciled, not replayed: the agent's platform-managed skill dirs are diffed against the assignment set. No tombstone table, no migration, and every removal route converges. Runs after injection and also at zero assigned skills — that is exactly the "unassigned the last skill" case. - Blast-radius guard: >10 removals for one agent refuses wholesale and alarms. A wiped agent_skills table is indistinguishable from a mass-unassign, and keeping files is the recoverable direction (#1638/#1644). Scheduled auto-sync + fleet re-inject - New leader-locked backend service (skills:sync:leader). Backend-hosted because the sweep must reach agent containers and the scheduler is platform-network-only. - Sweeps only when the library commit actually changed; running non-ghost agents; force=False so the ent#183 tree-SHA skip makes unchanged skills free; bounded concurrency; inject-lock contention is skip-and-report. - Honest aggregate report in Settings + operator alarm only when an agent failed. - Config re-read each cycle, so an interval change needs no restart. Durable sync status - `_last_sync`/`_last_commit_sha` were per-process; under `--workers 2` the worker answering /status was usually not the one that synced, so the panel showed a stale timestamp and could never show an error at all. Now mirrored to system_settings on both the success and failure branches, and the commit-changed comparison reads the durable row (the in-memory field would make every restart look like a change). Hardening found by /review and /cso on this branch - The persisted sync error is PAT-scrubbed: sync_library's outer handler passed a raw str(e), and the authenticated remote URL is an argument in the subprocess command list, so an OSError could carry a token into system_settings and the admin panel. - Cross-worker lock around the shared clone: scheduled + manual sync both run `git fetch` + `git reset --hard` on /data/skills-library. Contention returns 409 and writes no status row, so a contended click cannot paint "Last sync failed". - remove_skills re-reads assignments inside the lock and refuses a still-assigned skill, closing the bulk-PUT check-then-act race (#1445 pattern). - PUT /api/settings/skills-library is human-only (reject_agent_principal): it is the on-switch for an unattended fleet-wide write of SKILL.md files, which Claude executes as instructions. assert_admin answers "what role", never "is this a human" — third occurrence of the trinity-ops-agent#232 class. The remaining half of that chain (skills_library_url writable by an agent key via the generic settings PUT) is pre-existing and filed as abilityai/trinity-enterprise#293. Dedicated range-validated GET/PUT /api/settings/skills-library; the three keys are blocked on the unvalidated generic PUT. 58 new tests. Fixes abilityai/trinity-enterprise#236 * fix(skills): wire ent#236 tuning vars into both compose files + .env.example `SKILLS_RECONCILE_MAX_REMOVALS` and `SKILLS_FLEET_INJECT_CONCURRENCY` were read via os.getenv() but never reached the container — the #1056 / trinity-enterprise#31 packaging class. The reconcile-refusal alarm names the first var in its own remediation text ("raise SKILLS_RECONCILE_MAX_REMOVALS"), so on a deployed stack the operator was told to turn a lever that does not exist, leaving a legitimate mass-unassign permanently blocked at the default cap of 10. Found by /validate-pr on PR #1883. * fix(ui): agent tab panel polish — card borders, section spacing, and an honest Sync-now affordance Three cosmetic fixes plus one UX gap on the agent detail tabs. - SkillsPanel had no card wrapper, so its content sat flush against the tab bar unlike every sibling tab. Wrapped in the same card the other panels use. - FoldersPanel and InfoPanel each had a `v-else` content wrapper with no spacing class, so the root `space-y-6` never reached the cards inside and they rendered touching. Same bug in both files. - SkillsPanel: saving assignments writes the DB rows, but the files only reach the container on a sync or the next agent start. That was stated in muted text above the button, which is easy to miss — an operator can save, message the agent, and be told the skill doesn't exist, because it isn't there yet. "Sync now" now goes prominent while that gap is open, and only while the agent is running (shouting at a disabled control helps nobody). A failed or 409-busy sync keeps it lit, since the gap is still open. * fix(ui): inset the Settings and Skills tab content like every other tab 8 of the agent-detail tab wrappers use p-6 (overview, info, brain, dashboard, schedules, playbooks, git, folders). Settings and Skills had none, so their cards ran flush into the enclosing panel's left and right edges instead of sitting inset like the rest. * fix(skills): re-clone a library path that is not a repository, and make the panel's failures actionable Three fixes found while testing this PR on a live instance. All pre-existing on dev, but each is sharpened by putting sync on an unattended timer. 1. sync_library() chose pull-vs-clone on `library_path.exists()` — directory existence, not repo-ness. A path holding no `.git` (clone interrupted by a full disk, a stray mkdir, a restored backup) failed `git pull` with "not a git repository" on every attempt, with nothing able to re-clone: permanent, and recoverable only by shell access. Now tests for `.git` and re-clones. Detecting it is only half a fix, since `git clone` refuses a non-empty destination — so a non-repo directory is moved aside first. Renamed, never deleted: the platform owns the path exclusively so removal would probably be safe, but "probably safe" is not the standard for an unattended timer deleting a directory derived from an operator-supplied setting (#1638/#1644). One quarantine is kept, so a recurring fault cannot grow without bound. 2. syncSkillsLibrary() saves settings first (setting showSuccess), then syncs; the catch set `error` without clearing it, so a failed sync showed "Settings saved successfully!" and "Clone failed" together. Both true, which is precisely what makes the pair untrustworthy. 3. The panel never said a private library needs a GitHub PAT — it is in two internal docs only, and what an operator hits is raw git ("could not read Username"), which names no remedy and does not hint that the PAT field is one section above. Added that line. The error-string mapping is deliberately NOT done: matching git stderr is brittle across versions and locales, and the raw error is at least surfaced rather than swallowed. Tests: 5 new (4 fail without the fix). Also fixes 7 existing tests that created the library path without `.git` — under the corrected predicate they took the clone path and reached for the network; the suite drops 5.01s -> 0.62s. * fix: ownership-checked fleet-restart lease with loss detection + acquire inside try/finally (#1919) (#1928) The per-iteration refresh was a bare EXPIRE gated on a local flag — after a TTL lapse it extended a concurrent caller's lease while both loops ran. The refresh is now a pre-action ownership gate (GET-compare via the shared redis_breaker_util.lock_token_matches): a foreign token stops the run with honest partial accounting (summary/audit gain processed + stopped_early), an absent token is re-acquired via SETNX so an unraced run completes instead of aborting, EXPIRE→0 routes to the absent path, and refresh Redis errors stay fail-open with one throttled warning per run. list_all_agents_fast() moved inside the try/finally so nothing can ever leak the lock between acquire and release; an abnormal exit audits as stopped_early="error" + exception class name only. TTL 900→2100, sized above the slowest single agent (skill injection alone is bounded at 1800s) so a mid-agent lapse is no longer arithmetically guaranteed. Release stays compare-and-delete, attempted even after detected loss (foreign-safe by construction). +11 unit tests (27 total in the file); live-validated on the local stack (foreign takeover mid-run, absent re-acquire to completion, 409 concurrency, TTL 2098 observed, release verified). Sibling hand-rolled lock sites and the system_seed_service unconditional release → #1920. Fixes #1919 Co-authored-by: Claude Fable 5 <[email protected]> * fix(templates): contain local: template ids and stop deriving credential paths from name: (#1900) (#1935) * fix(templates): contain local: template id resolution on the read path (#1900) `GET /api/templates/{template_id:path}` handed `local:<name>` straight to `get_local_template`, which joined `<name>` onto the templates root with no validation. The `:path` converter permits `/`, so `local:../<x>`, `local:/<abs>/<x>` and a root-escaping symlink each read `<escaped-dir>/template.yaml` and echoed its contents in an authenticated 200. Reachable by any authenticated principal of any role — including an agent-scoped MCP key, so a prompt-injected agent qualifies. In a container the reachable set includes `/data/deployed-templates/<victim>`, where every user's uploaded template archive lands: a cross-tenant read. Two corrections to the issue's framing, both verified here: * it is NOT arbitrary file read — the filename is fixed (`template.yaml`), it must parse as a YAML mapping, and only a fixed key set is echoed. But those keys' VALUES are arbitrary YAML subtrees, not just strings. * `local:..` alone is not an existence oracle: a directory with no `template.yaml` returns the same 404 as an unknown id. Fix: `contained_template_dir(name, root)` — the two-step barrier the CREATE path has had since #950 (`crud._safe_local_template_path`), brought to the read path. A name allowlist runs BEFORE any path math (this is also what CodeQL recognises as a `py/path-injection` barrier; resolve-only was flagged high-severity twice on this codebase), then `resolve()` on BOTH sides plus `is_relative_to`. `str.startswith` is not equivalent — it passes the sibling escape `<root>-evil`. An escaping id returns `None`, so the router's 404 stays byte-identical to an unknown template: no error code, no path, no root name. A distinct error would be a NEW enumeration oracle, which is what #1759's single-sentence 404 exists to close. Rejections log at DEBUG, sanitized — the endpoint has no rate limit, so a per-rejection WARNING would be an authenticated log-flood primitive. The helper is public: the remote-template-registry work (trinity-enterprise#14) edits this same resolver family in this same module and should import it rather than copy it. Tests: every rejection test PLANTS a real `template.yaml` at the escaped location, because unpatched code returns `None` for any id whose target simply does not exist — a rejection test with nothing planted is green before and after and proves nothing. Each is labelled REPRO (verified red pre-fix) or HYGIENE (cannot be made red; contract only). The router guard lives in `tests/unit/` because no gating CI job collects `tests/test_templates.py`. `test_1900_containment_survives_a_symlinked_root` is the landmine guard for resolving both sides: a half-resolved variant passes all 130 pre-existing tests and only that test catches it. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(templates): stage .mcp.json from the validated template dir, not template name: (#1900) The second traversal sink, found by this issue's own AC #4 audit ("audit the by-name create path for the same join"). It is NOT the create path's `local:` id resolution — that has been contained since #950/#1759 via `crud._safe_local_template_path`, applied at both seams #1759 named. It is the create path's CREDENTIAL STAGING, which threw that validated path away and re-derived a directory from scratch: template_name = template_data.get("name", "") # untrusted mcp_template_path = templates_dir / template_name / ".mcp.json" `name:` comes from an uploaded template.yaml, so any `creator` reaches it via `deploy_local_agent`. `name: ../../data/deployed-templates/<victim>` read another tenant's `.mcp.json` — a credential-bearing file type under Invariant #12 — into the attacker's OWN agent, where they read it at leisure. A victim who hardcoded a token rather than a `${VAR}` placeholder leaks it. Assessed on its own axes, NOT inherited from the read sink: different trigger (`creator` role + an upload + an agent create, vs a bare authenticated GET) and a higher impact ceiling (credential values, not template metadata). Also P2, for different reasons. The derivation was also simply wrong. `name:` is not a directory name — 5 shipped templates declare a display string there ("Test Echo Agent"), so `local:test-echo` resolved to `<curated>/Test Echo Agent/.mcp.json`, which does not exist. That kills the "validate the name" framing: the value should not resolve paths at all. Fix is root-cause, not another guard: `_stage_config_files` already calls `_safe_local_template_path` itself for the `/template` bind decision, so the validated directory is available in the same function. Extract the two-root ladder as `_resolve_local_template_dir` and pass its result as `template_base_path`. The untrusted join is gone from the live path, and the #1759 "seams must agree" property becomes structural across all THREE seams (resolver, bind decision, credential stager) instead of two. Deliberately NOT threaded through `_TemplateResolution` or the return tuple: `_resolve_local_template` returns a 2-tuple that three existing tests depend on, two as monkeypatched `lambda config: ({}, None)` doubles — widening it breaks the test doubles, not just the callers. Its signature, its return arity, `_safe_local_template_path`, `_LOCAL_TEMPLATE_ROOTS`, and everything inside the CodeQL-sensitive `if template_yaml.exists():` block are untouched (#1793 had to revert exactly that reshape). The residual `template_base_path is None` arm is kept and made fail-closed: it is a public function with a `template_base_path=None` default, so a future caller can still reach it. It now contains through the same barrier as the id, which also absorbs a non-string `name:` — `Path(root) / 123` raised TypeError, i.e. an uncaught HTTP 500 during agent creation (the ent#128 bug class, one seam over). One disclosed behaviour change: a deploy-local template that BOTH declares `credentials.mcp_servers` AND ships a `.mcp.json` now gets `${VAR}` substitution, where the old curated-root lookup always missed. Verified no collision with `deploy._prepopulate_workspace_from_template`, which writes the archive's raw copy into the workspace volume: `startup.sh` copies `/generated-creds/.mcp.json` unconditionally (gated only on the directory existing) and AFTER the template-copy block (gated on `.trinity-initialized`), so the substituted file deterministically wins — which is the intended behaviour, the raw copy still carrying unsubstituted placeholders. Not one of the 26 shipped curated templates contains a `.mcp.json`, so the curated rows are provably unchanged. The crud seam tests are mandatory, not decorative: every service-level test calls `generate_credential_files` directly, so an "extracted but never wired" mistake leaves all of them green while deploy-local resolution silently regresses into the fallback arm. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: record the #1900 containment contracts for template id + credential staging Rule #1 (requirements before implementation) — `core-agent.md`: * §4.1 gains the **read-path resolution contract** as a sibling to the existing create-time contract: `GET /api/templates/{id}` resolves `local:<name>` through the same two-step barrier the create path has had since #950, and a failing name returns a 404 byte-identical to an unknown template (the #1759 non-disclosure rule). Records the deliberate, known asymmetry that `get_local_templates()` still enumerates by `iterdir()` and so could LIST a root-escaping symlink that detail and create both refuse — the listing is the outlier, and planting one needs local filesystem write access, not a request. * §4.3 records that the `credentials.mcp_servers` template lookup now resolves from the validated path rather than the template's own untrusted `name:` field, including the one disclosed behaviour change (deploy-local templates now get `${VAR}` substitution) and why the substituted file wins over the archive's raw copy. `architecture.md` gets one clause on the `templates.py` router catalog entry (the catalog rule caps entries at 2 lines, and no Cross-Cutting Subsystems block is warranted). A bug fix would normally be commit-message-only under the tiered-docs rule; the exception is that this ships a public, importable containment primitive in the exact module and resolver family the remote template registry (trinity-enterprise#14) will edit, and one catalog clause is the cheapest way that author finds it instead of copying the flaw. Not updated, deliberately: no feature-flow doc (no new vertical slice), no user docs (no user-visible change for honest callers), no schema/migration (no DB change, so the dual-track SQLite/Alembic rule does not apply). Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(feature-flows): sync template-processing + local-agent-deploy for #1900 `/sync-feature-flows` was NOT a no-op here — three concrete staleness points in `template-processing.md`, which owns the `local:` resolution surface: * The inlined two-root ladder is now `_resolve_local_template_dir`; the code block showed the pre-extraction form. * "**Two** seams read `_LOCAL_TEMPLATE_ROOTS` and must stay in agreement" was the #1759 claim and is now wrong in the direction that matters: there was always a third seam (the credential-file stager) which did NOT agree — it re-derived the directory from the template's untrusted `name:`. Corrected to three, with the extraction as the structural guarantee. * `generate_credential_files` was cited by stale line range (`:228-299`) and documented none of where the `.mcp.json` template is actually located. Replaced the fragile line-range citation with a symbol reference and added the provenance, the residual fail-closed arm, and the disclosed deploy-local substitution delta. Also documents the read-path containment (`get_local_template` → `contained_template_dir`) beside the existing #1513 catalog-curation note, including the deliberate list-vs-detail asymmetry for a planted symlink. `local-agent-deploy.md` gets one line at the credential-merge step: a deploy-local template's `.mcp.json` now resolves from the deploy-local directory, so a hostile `name:` cannot read another tenant's file and `${VAR}` substitution finally applies to that template. `credential-injection.md` was checked and NOT touched — its `.mcp.json` references are unrelated (credential inject/export/import), and the template lookup live…
This was referenced Sep 2, 2026
Merged
dolho
added a commit
that referenced
this pull request
Sep 9, 2026
Addresses the `/validate-pr` CHANGES_REQUESTED on #2487. Every item is about a guard that is present and inert, which is why the refactor landed green. **C1 — the 60/60 route-set proof never ran in CI.** It read the pre-split module out of git, and every checkout in `backend-unit-test.yml` is `fetch-depth: 1`, so `git show dd91056:…` failed on every run and the test skipped — leaving "no route lost or invented" across a 3,529 → 10 module split proven nowhere. The fork-point set is now a frozen 60-tuple literal (a fork point is a historical fact, so freezing it costs no maintenance; a route added since goes in `_ADDED_SINCE_SPLIT`, one reviewed line at a time). The git read survives as a separate test that re-derives the literal wherever history is deep enough, so the transcription cannot drift. Its temp module is written under `tmp_path`, not `src/backend/` — an interrupted run there left a top-level module `Dockerfile:131` would bake into the image. **C2 — the integration suite broke at collection**, in FOUR files, not three: `test_monitoring_service.py` too. All of them `spec_from_file_location` on `services/agent_client.py`, which is now a package, so they raised FileNotFoundError before any test ran; this only stayed green because integration runs nightly rather than per-PR. Replaced with plain imports: the loaders existed to bypass `services/__init__.py`, and that has not been true since the module started importing `services.agent_auth` at import time (it is on `dev` too). Privates come from the module that owns them (`circuit._CIRCUIT_HASH_PREFIX`, `http_pool._client_pool`), per the package's own no-mirrored-collaborators rule, and the caplog assertions key on the parent logger name so they still capture from every submodule. Collection is back to 83 = `dev`'s 83. **Two invariant guards went blind on 3,529 lines.** `routers/settings/` is the first subdirectory ever created under `routers/`, and both `test_1310_auth_wiring.py` (Invariant #8) and `test_models_centralized.py` (Invariant #14) globbed one level deep — all ten modules escaped, and it fails open, so nothing showed. `rglob`, keyed by path relative to `routers/` so two packages cannot share an allowlist key (a top-level file's relative path is its bare name, so neither allowlist changes). 73 → 84 files scanned. **A dead constant with a live test guarding it.** `routers/public.py` still declared `MAX_CHAT_MESSAGES_PER_IP`/`_PER_TOKEN` while enforcement reads `public_chat_service`'s copy, so `test_ip_rate_limit_fix.py` was asserting a constant nothing enforces — equal values today, so only the guard had broken. Now re-exported from the enforcing module. **Split-detachment in `public.py`.** The two #311 gates were from-imported under private aliases while the service called its own module-locals: one function, two monkeypatch targets. Now called through the sibling module object, which is the rule both package `__init__` docstrings state; the two tests that patch or read it are repointed, and the `files.py` guard now bans both spellings so the retired alias cannot let a re-import through. Docs: `architecture.md` Invariant #1 gains the package paragraph (re-export the public surface only; reach siblings through the module object; guards use `rglob`), and the four stale `.py` references in the shards are corrected. Also: nine modules carried a duplicated module-level `logger`; and `fleet_ops_service` renames the fleet-restart log channel from `routers.ops`, which is now stated in the code rather than left for an operator to discover. Verified: unit suite 6269 passed, 1 failure — the pre-existing `::ffff:` IPv4-mapped parsing case (local 3.12 vs the repo's 3.13 target), byte-identical on clean `dev`. Related to #1028 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP
vybe
pushed a commit
that referenced
this pull request
Sep 16, 2026
…2487) * refactor(settings): routers/settings.py becomes a ten-module package (#1028) 3,529 lines — the largest file in the backend, 4.4x the 800-line critical threshold — split into ten domain modules composed onto ONE router, so the mounted API is byte-identical and `from routers.settings import router` is unchanged. Largest resulting module: credentials.py at 778 lines. Inclusion order is load-bearing (Invariant #4): `generic` owns the GET/PUT/DELETE /{key} catch-alls, which match any single segment, so it is included LAST — before its siblings it would swallow /ops/config, /brain-orb, /api-keys/anthropic and answer 'setting not found' for routes that exist. test_1028_settings_package.py pins: - the mounted route SET equals the pre-split module's, compared against the real blob out of git (60/60, none lost, none invented) - no route is shadowed by an earlier registration (the property that actually matters — literal order is deliberately NOT pinned, since regrouping specific routes relative to each other is inert) - the catch-all include stays last, named at the include line a human edits - every module stays under the 800-line threshold - the import surface callers depend on still resolves (resolve_mcp_url, the key sets, _REPO_PATTERN) Collaborators (db, platform_audit_service, settings_service) are deliberately NOT re-exported on the package __init__: ~20 tests patch them as module attributes, and after a move such a patch would apply cleanly to a module nobody reads — a test asserting nothing while hitting the real accessor. Absent attributes make every stale patch raise AttributeError instead, which is exactly how the 14 affected test files were found and repointed to the modules that own their handlers. GET '' (the root listing) is registered on the parent router because a prefix-less sub-router cannot carry an empty path (FastAPI refuses). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01NLfHNPtB5UCMk4LonZiJux * refactor(git): services/git_service.py becomes a six-module package (#1028) 2,322 lines split by responsibility — conflicts, gitignore, remotes, trinity_files, sync, provisioning — with the full public surface re-exported from the package __init__, so `from services.git_service import sync_to_github` and `git_service.<name>` callers are unchanged. Largest resulting module: gitignore.py at 649 lines. Cross-module calls go THROUGH the sibling module object (`gitignore._detect_git_dir(...)`), never a from-import of the function: a from-import freezes the binding, so a test patching the owning module would silently stop reaching the caller. Pinned structurally by test_1028_git_service_package.py, alongside the size threshold and the import surface. Private names are re-exported ONLY where another backend module imports them or a test reads them as data. A private function mirrored on both the package and its owning module can be monkeypatched on the wrong one and silently detach — which is exactly what happened to test_2069's readiness probes mid-split (the multiline setattr sites patched the package's re-exported copies while merge_gitignore_after_clone read the module's own), so the collaborator-shaped names are deliberately not mirrored: a stale patch raises AttributeError instead of testing nothing. ~15 test files repointed to the modules that own their handlers, including the three sys.modules-isolated file loaders and test_github_init_push, whose exec fake must now land on every module binding the driven function awaits through (provisioning + gitignore + remotes — patched via the loaded package instance, since its harness purges and reloads the package). The #2069 merge-caller guard now walks the whole package and matches qualified calls, so a caller cannot fall out of its census by moving between modules. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01NLfHNPtB5UCMk4LonZiJux * refactor(client): services/agent_client.py becomes a three-module package (#1028) 1,294 lines split by responsibility — circuit (the #631 transport breaker: constants, Lua, CircuitState, dormant alerting, admin read/reset), http_pool (the per-agent httpx pool + drop-grace stamps), client (AgentClient, typed errors, get_agent_client) — public surface re-exported from the package __init__, so every existing import is unchanged. Largest module: client.py at 698 lines. Same discipline as the git_service split, pinned by test_1028_agent_client_package.py: cross-module calls go through the sibling module object, collaborators are not mirrored on the package, and no module may from-import a sibling's function (a frozen binding silently detaches monkeypatches on the owning module). test_circuit_breaker.py's direct file-load gains package plumbing (submodule_search_locations + a sys.modules registration before exec — the __init__'s relative imports cannot resolve their parent otherwise), and its patches land on the owning modules. The #1677 caller-parity allowlist entry for _emit_dormant_alert follows the file to services/agent_client/circuit.py — that guard firing on the move is exactly what it is for. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01NLfHNPtB5UCMk4LonZiJux * refactor(ops,public): the heavyweight handlers move behind their routes (#1028) The last two ACs. `public_chat` — 289 lines of session identity, access gating, rate accounting, upload decoding, memory injection and dispatch, inside routers/public.py — moves to services/public_chat_service.py in the #1483 shape (service raises PublicChatError, the thin route maps it 1:1); client-IP extraction, the per-IP limit and token resolution stay router-side because they are HTTP concerns. agent_requires_email / agent_allows_open_access move with it and the router re-imports them — one definition, not a copy. public.py: 1,239 → 901 lines. routers/ops.py's five heavyweights — fleet health, the #1860 locked fleet restart, fleet stop, emergency stop, the cost rollup — move to services/fleet_ops_service.py (704) and services/ops_costs_service.py (208). The auth gates stay IN the router deliberately: the #2389 fence-vs-gate scans read live handler source there, and a gate that moved with the body would satisfy auth while blinding the scan. ops.py: 1,304 → 506 lines. test_1028_extracted_services.py pins the thinness, the gates' location, the size class — and an unresolved-module-scope-name walk, added because the move surfaced exactly that class twice: PublicChatResponse was unresolved in the chat service while 623 tests passed (nothing drives the sync-success return), and utc_now_iso the same in the costs service. py_compile cannot see this; the walk can. test_1860 / test_1917 fixtures now hand back the SERVICE module with the route entry points attached, so collaborator patches land on the bindings the moved bodies actually read while the gate patch stays on the router. The #894 override-wiring census follows public_chat's two execute_task call sites to their new file. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01NLfHNPtB5UCMk4LonZiJux * test(1028): repoint the settings source-guards at the package; satisfy the sys.modules lint Four guards read routers/settings.py as SOURCE TEXT (the ent#12 consent AuditEventType pin + generic-PUT block, the ent#434 catch-all window) and went FileNotFoundError when the module became a package — repointed at the package glob (or generic.py where the guard scopes a specific handler window). The new test files' own sys.modules registrations move onto monkeypatch.setitem / the _restore_sys_modules precedent, and the lint baseline is regenerated DOWNWARD (140 across 49 files — the patch migrations in the split commits removed ~66 stale entries). Related to #1028 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NLfHNPtB5UCMk4LonZiJux * test(1028): the size guard counts blank lines out, comments in Self-review finding, and the more serious of the two: my previous commit changed the guard's METRIC so that my own edit would pass. That is the re-baselining this file exists to make hard, wearing a docstring as cover. Measured rather than argued. `credentials.py`: at 6d8c93a raw 778 non-blank 687 after raw 806 non-blank 687 (blank-line restoration only) non-blank-non-comment 643 Excluding blanks is exactly invariant under the change that prompted it. Excluding comments as well moves the calibration: these files carry 110-208 comment lines each, so a comment-blind count hands `credentials.py` ~160 lines of headroom the 800 ceiling never gave it, and `generic.py` 208. So the metric now excludes blank separators and nothing else. Restoring a PEP-8 blank line between two defs still does not read as a module growing, and the ceiling still means what it meant when these files were authored against it. Related to #1028 * test(1028): name the size metric for what it counts Re-review of my own fix. The metric was corrected to exclude blank lines only, and left named `_logical_lines` — which in Python means the opposite, since a logical line excludes comments. That is not a cosmetic mismatch. Reading the phrase "logical lines" in this test's docstring is precisely what talked the previous pass into excluding comments and re-baselining the guard by 160 lines. Leaving the name in place leaves the same trap armed, one identifier along, for the next reader who "corrects" the body to match it. `_non_blank_lines`, and the AC's docstring says "800 non-blank lines" in its own words rather than delegating the definition to a helper name. Related to #1028 * fix(1028): make the split's own safety nets actually run Addresses the `/validate-pr` CHANGES_REQUESTED on #2487. Every item is about a guard that is present and inert, which is why the refactor landed green. **C1 — the 60/60 route-set proof never ran in CI.** It read the pre-split module out of git, and every checkout in `backend-unit-test.yml` is `fetch-depth: 1`, so `git show dd91056:…` failed on every run and the test skipped — leaving "no route lost or invented" across a 3,529 → 10 module split proven nowhere. The fork-point set is now a frozen 60-tuple literal (a fork point is a historical fact, so freezing it costs no maintenance; a route added since goes in `_ADDED_SINCE_SPLIT`, one reviewed line at a time). The git read survives as a separate test that re-derives the literal wherever history is deep enough, so the transcription cannot drift. Its temp module is written under `tmp_path`, not `src/backend/` — an interrupted run there left a top-level module `Dockerfile:131` would bake into the image. **C2 — the integration suite broke at collection**, in FOUR files, not three: `test_monitoring_service.py` too. All of them `spec_from_file_location` on `services/agent_client.py`, which is now a package, so they raised FileNotFoundError before any test ran; this only stayed green because integration runs nightly rather than per-PR. Replaced with plain imports: the loaders existed to bypass `services/__init__.py`, and that has not been true since the module started importing `services.agent_auth` at import time (it is on `dev` too). Privates come from the module that owns them (`circuit._CIRCUIT_HASH_PREFIX`, `http_pool._client_pool`), per the package's own no-mirrored-collaborators rule, and the caplog assertions key on the parent logger name so they still capture from every submodule. Collection is back to 83 = `dev`'s 83. **Two invariant guards went blind on 3,529 lines.** `routers/settings/` is the first subdirectory ever created under `routers/`, and both `test_1310_auth_wiring.py` (Invariant #8) and `test_models_centralized.py` (Invariant #14) globbed one level deep — all ten modules escaped, and it fails open, so nothing showed. `rglob`, keyed by path relative to `routers/` so two packages cannot share an allowlist key (a top-level file's relative path is its bare name, so neither allowlist changes). 73 → 84 files scanned. **A dead constant with a live test guarding it.** `routers/public.py` still declared `MAX_CHAT_MESSAGES_PER_IP`/`_PER_TOKEN` while enforcement reads `public_chat_service`'s copy, so `test_ip_rate_limit_fix.py` was asserting a constant nothing enforces — equal values today, so only the guard had broken. Now re-exported from the enforcing module. **Split-detachment in `public.py`.** The two #311 gates were from-imported under private aliases while the service called its own module-locals: one function, two monkeypatch targets. Now called through the sibling module object, which is the rule both package `__init__` docstrings state; the two tests that patch or read it are repointed, and the `files.py` guard now bans both spellings so the retired alias cannot let a re-import through. Docs: `architecture.md` Invariant #1 gains the package paragraph (re-export the public surface only; reach siblings through the module object; guards use `rglob`), and the four stale `.py` references in the shards are corrected. Also: nine modules carried a duplicated module-level `logger`; and `fleet_ops_service` renames the fleet-restart log channel from `routers.ops`, which is now stated in the code rather than left for an operator to discover. Verified: unit suite 6269 passed, 1 failure — the pre-existing `::ffff:` IPv4-mapped parsing case (local 3.12 vs the repo's 3.13 target), byte-identical on clean `dev`. Related to #1028 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * refactor(1028): split gitignore.py three ways after the dev merge The dev merge brought #2529's ~715 lines into `services/git_service/gitignore.py`, taking it to 1305 raw lines — past the 800-line threshold this PR exists to enforce, and its own guard (`test_1028_git_service_package::test_every_module_is_under_the_critical_threshold`) said so. Re-baselining the guard under cover of a fix is precisely what the settings-test docstring in this PR warns against, so the module is split instead: gitignore.py 686 the patterns, the regions, the command builders gitignore_sweep.py 418 what a sweep DID — tags, parse, alert, report gitignore_clone.py 273 the once-per-agent merge after clone The seam is "what the file CONTAINS" vs "what did that just do" vs "the one-shot at creation". Cross-module references go through the module object (`gitignore.<name>`, `gitignore_sweep.<name>`), never a from-import: a from-import freezes the binding and a monkeypatch then lands on a detached copy — which is how test_2069's readiness probes went dark mid-split. Three real defects surfaced while wiring it and are fixed here, not carried: - `_gitignore_merge_semaphore` and `_inflight_gitignore_merge_tasks` were referenced bare in `gitignore_clone` with no such globals — a NameError on the live clone-time merge path. The five merge constants + the semaphore + the in-flight set now live in `gitignore_clone`, their sole consumer. - `_shadowed_negations` read `_GITIGNORE_MANAGED_LINES` bare after the move. It now reads it off `gitignore` through a deliberately function-local import — `gitignore` imports this module at its top level, so a module-level one would close the cycle at import time. - `datetime` was left behind by `_augment_commit_message`. The sibling suites are repointed at the module that OWNS each name, so every symbol still has exactly one monkeypatch target: test_2529's sweep names to `gitignore_sweep` (new `_sweep()` accessor beside `_gs()`), and test_2069's readiness/merge collaborators to `gitignore_clone`. 741 passed, 3 skipped across the git/gitignore/1028/1310/models families. Related to #1028 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP * test: dev's post-fork tests reach the split modules the way every earlier one does (#1028) Five files landed on dev after the fork with patch targets and source reads on the monoliths. Re-pointed the same way the split re-pointed the rest: - test_ent582_platform_keys: `is_claude_auth_configured` / `connect_agents_to_first_credential` on `settings.credentials`, `platform_keys_service.check_resend_key` on `settings.provider_keys` - test_2695_stt_capability_probe: `_elevenlabs_settings_state_with_capability` on `settings.integrations` - test_2691_public_url_reachability: the save-path source read on `settings/generic.py`, the flag-surface read on `settings/flags.py`, `update_setting`/`db`/`platform_audit_service` on `generic` - test_github_init_push: the exec recorder also installed on `git_service.token_scrub`, which the ent#615 seed now runs through - routers/settings/generic.py: the #2572 hook reaches `credentials` through an absolute function-local import — `test_2216_backup_observability` and `test_2572` load this module in isolation via `spec_from_file_location`, where a module-level relative import raises at collection Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VpvcfgWkmQPD7DrDLmATTf * test: dev's two new settings tests reach the split modules (#1028) `test_workspace_flag_retired` patches `settings_service`, `telemetry_sharing_service` and `db` on the module it calls `get_public_feature_flags` from, and `test_2696_stt_provider_errors` calls `_elevenlabs_settings_state_with_capability`. Both imported the flat `routers.settings`. Now they import the `flags` and `integrations` submodules, like the earlier re-points in 9c34662, so the patches land on the globals the handlers actually read. Full unit suite on this tree: 16468 passed, 32 skipped, 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test: patch the modules that own the moved globals, and let #1917 follow the moved ops code (#1028) merge-train validation findings. Collection was fixed earlier; these are the runtime half. - `tests/integration/test_circuit_breaker.py`: 19 `monkeypatch.setattr(agent_client, ...)` calls and 34 `agent_client.CIRCUIT_*` reads now target `services.agent_client.circuit`, which reads its own globals. Patching the package re-export changed nothing, and `_get_circuit_redis` is not re-exported, so it raised AttributeError. Against a fakeredis server: 8 failed / 26 passed before, 34 passed after (dev: 34 passed). - `tests/git_sync/test_s5_conflict_classifier.py` loads `git_service/conflicts.py`, because the flat `git_service.py` no longer exists. - `tests/git_sync/test_s7_reserve_instance_id.py` patches `check_remote_branch_exists` and `db` on `git_service.provisioning`, where `reserve_and_generate_instance_id` looks them up. Both git_sync files: 33 passed. - `tests/unit/test_1917_stack_trace_exposure.py`: the raw `str(e)` ban now also scans `services/fleet_ops_service.py` and `services/ops_costs_service.py`, where the ops handler bodies moved. Neither file has any hits today. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: sim <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Sep 18, 2026
Lands the trinity-dev backlog merged on 2026-09-18: 13 PRs (#6, #7, #8, #11, #14, #16, #17, #21, #22, #24, #26, #28, #29), plus the /release lessons from the v0.9.5 cut — the DigitalOcean installer tag moves with VERSION (#24), and the headline commit count comes from the previous release PR's head, not the tag. Private submodule: OSS clones skip it (update = none), so nothing changes for external contributors. Co-authored-by: sim <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
5 of 7 tasks
vybe
pushed a commit
that referenced
this pull request
Oct 28, 2026
…nstead of suffixing `_N` (Abilityai/trinity-enterprise#695) (#4033) * docs(requirements): apply mode for system manifests (Abilityai/trinity-enterprise#695) Requirement first (Rule #1). roadmap.md gains 16.5.4: POST /api/systems/apply reconciles a live system to its manifest instead of suffixing _N copies, persons only, dry_run true by default, with the write boundary, the verdicts, the blocker and report codes, the literal weak-evidence rule and the three stated differences from create mode. The converge/on_conflict "deferred" notes in 16.5, 16.5.2 and 16.5.3 now point at it. scheduling.md 10.16 states the apply exception on the manifest path: same-named schedules are updated in their declared fields, never enabled, never deleted, matched by name because no identity column exists. * feat(models): SystemApply request and response models (Abilityai/trinity-enterprise#695) A separate request/response pair for the apply verb, in models.py (Invariant #14). SystemApplyRequest forbids unknown keys, so a stray `mode` or `strict` is a 422 rather than silently dropped, and defaults dry_run to true. SystemApplyResponse carries per-member verdicts and changes, drift, blockers, the prompt and view verdicts and failed writes, with its own six-valued status; SystemDeployRequest/Response are untouched. * feat(redis): atomic ownership-checked renew and release on SingleFlightLock (Abilityai/trinity-enterprise#695) refresh_if_owned / release_if_owned are GET-then-EXPIRE and GET-then-DELETE: a holder whose lease lapses between the two calls extends or deletes a successor's lease. Apply mode holds its lock for a whole run and renews it on a timer, so it needs the compare and the mutation in one Lua call, the canary leader lease's scripts. A lapsed lease is LOST, never re-taken. New methods only; the existing ones and their callers (ops loop, seeder) are untouched. The key travels as a script argument because the leaf module's guard refuses the keyspace-scan spelling the declared-key table shares. Tested against a register_script emulator that executes the compare semantics and injects a successor inside a client-side GET. * feat(systems): apply snapshot and membership gates (Abilityai/trinity-enterprise#695) read_apply_snapshot reads what apply plans over, and nothing else. A failed read is a retryable blocker, never an empty value: create fails open, apply fails closed. - Roster: the tri-state container list union the live ownership rows, filtered by can_user_access_agent; never get_accessible_agents, which reads [] on a Docker fault and would let the evidence gate pass. - Membership through the one predicate, system_membership; unreadable tags and unreadable Docker refuse (retryable). - Weak evidence, literally: any member, declared or not, matched by name only is refused by name, with a remedy for each kind (the additive tag call, never the PUT that replaces the set). - Each declared name classified globally: taken and manageable (the deploy-local predicate) -> the system/ephemeral/no-container/claimed gates or reconcile; taken and not manageable -> one uniform member_name_unavailable that never names an owner; free -> create. - A label read that returns nothing for a name the roster showed is a read failure, not a missing container. restart_pending comes from the platform's own start-path drift predicates. * feat(systems): schedule match policy and declared schedule actions (Abilityai/trinity-enterprise#695) The seam schedule identity (trinity-enterprise#694, #1198) plugs into. schedule_match_policy(declared_entry, live_rows) -> matched | missing | unlinked | ambiguous; the default matches by exact name, unique on both sides, because no identity column exists. resolve_declared_schedule_actions turns matches into actions the writers consume (they never match): - matched: update only the declared fields that differ (cron and message always, timezone and description only when declared), else in_sync; enabled is never written, a difference is reported; - a live row no entry names is reported and left (so a rename is a create plus the old row reported, still armed as it was); - two live rows with one name, or one name declared twice: blockers. A policy over the declaration and the rows rather than a scalar key, so an id-first, then same-name-unlinked search replaces it without touching a writer (pinned by a test that plugs one in). * feat(systems): apply plan and field reconcilers (Abilityai/trinity-enterprise#695) resolve_apply_plan turns the snapshot into per-member verdicts, drift, blockers and the ordered write-set; one function for the dry run and the real run. What it does per field on an existing member: - tags: added, compared lower/stripped as stored; extras untouched; - edges: resolve_permission_edges over the full map, self-edges dropped as set_permissions drops them; missing ones added, an intra-system edge the manifest does not want reported, never removed; - folders: only the declared keys, validated as booleans; - resources: a declared key that differs from the effective value (override, label, default) becomes a per-agent override, keeping the stored value for the key the manifest omits; never restarted; - template: reported; schedules: the matcher's actions, validated with the scheduler's own parser, created as the agent's owner, updates refused up front where update_schedule's owner-or-admin gate would silently no-op; - prompt: written by an admin only; view: found among own or shared views. A member to create gets create mode's semantics, with its template- dependent fields marked pending_template_resolution. Drift is every tagged undeclared member, a _N copy noted as such. APPLY_FIELD_CLASSIFICATION classifies every manifest field and schedule key, pinned by a census test. * feat(systems): apply executor under an atomic lease keeper (Abilityai/trinity-enterprise#695) apply_manifest: parse + validate (create's own named 400s, agents: {} included) -> lock-free snapshot + plan -> a dry run returns here; blockers refuse with no lock key written -> SingleFlightLock("system_apply:<name>", 900 s), never fail-open -> snapshot + plan again under the lock -> confirm ownership -> execute -> atomic release. The lease keeper starts at acquisition and renews every TTL/3 with the atomic compare-and-expire; any result but OWNED (lost, degraded) raises a stop flag checked before every write and every start, so later writes are reported lock_lost. execute_apply_plan writes only, counting each outcome from the writer's return value: create each absent member and tag it with the system tag at once; keep only writes naming members that exist; tags, edges, folders, resource overrides (a created member's compared with its template's values, before its start), schedules (a created member's against a fresh post-create read, never an unfiltered create), prompt, view; then start the created members one at a time, never an existing one. No exception escapes after the first write. restart_required is re-read from the platform's predicates after the writes. Tests cover AC1-AC5 end to end with a SQL statement witness, table dumps, the lock's Redis log, Docker recorders and a filesystem witness; the fresh-install and empty-manifest shapes; and the real start path's recreate keeping the member's volumes. * feat(systems): POST /api/systems/apply route and guard pins (Abilityai/trinity-enterprise#695) A sibling of POST /deploy, not a mode field on it: the create route and its models keep a zero-line diff, and a build without this route answers 405 for the path instead of silently running create. - Gates: require_role("creator") plus require_person. Persons only: on existing agents apply reaches permission grants, other agents' schedules and the platform prompt, so deploy's agent-callable capability fence would be a back door to all three. - Status: 200 valid/invalid/applied/partial; 409 refused with any non-retryable blocker, 503 with only retryable ones, 500 failed, each carrying the full report; 400 parse/validate with create's text. - A run that reached execution writes one CONFIGURATION/system_apply audit row (a failure is a warning, never a 500) and emits the tags router's thin agent_tags_changed trigger for every member whose tags it wrote, created or existing; a refused run writes none. Pins: the route-order guard resolves POST /api/systems/apply to apply_system; the creator-gate guard covers it. HTTP tests run through the real get_current_user with a seeded user-scoped key: a body without dry_run writes nothing but the key's usage counter, a stray mode/strict is a 422, weak evidence is a 409 with nothing written, an agent key is a 403 before any read. * docs(systems): architecture and feature flow for apply mode (Abilityai/trinity-enterprise#695) backend.md: the systems.py and system_service.py entries name POST /apply, its gates and status mapping, and apply_manifest's four parts (snapshot, plan, executor, lease keeper). api-endpoints.md: the System Manifests table gains POST /api/systems/apply. feature-flows/system-manifest.md: the Apply entry point under Deployment, a Service Layer table of the four functions and the field rules, the Router Layer handler, a Request Flow "Phase 4: Apply" diagram, and in Conflict Resolution that apply never suffixes and reports earlier _N copies as drift. The MCP sections are not touched. * test(systems): an added edge keeps a hand-granted edge and its skill grant (Abilityai/trinity-enterprise#695) The existing H2 case covers the report path (preset none). This one makes apply ADD an edge while a hand-granted edge to a non-member and its peer skill grant exist, so swapping add_agent_permission for the full-replacement set_agent_permissions (which also deletes grants on dropped edges) fails. * test(systems): close two gaps the apply mutations found (Abilityai/trinity-enterprise#695) Two section-9 mutations stayed green: - Building the roster from get_accessible_agents: the world made list_all_agents_fast raise on docker_service only, while get_accessible_agents reaches it through a by-name import in agent_service.helpers, so that path kept working and read [] as "no containers". The world now patches that binding too, and a roster test pins that an unreadable Docker is seen only through the tri-state reader. - Swapping add_agent_tag for the full-replacement set_agent_tags: no executor test added a tag beside an operator's tag. One does now. * fix(systems): unreadable Docker refuses apply with a 503, never a false 409 (Abilityai/trinity-enterprise#695) When agent_container_states() could not be asked, the snapshot replaced the roster with {} and still ran the per-member gates, so every existing member read as "has an ownership row but no container" and got the non-retryable member_container_missing. The router answers 503 only when every blocker is retryable, so a live system got a 409 telling the operator to start containers that exist, and a caller that retries on 503 stopped for good during a Docker blip. "No container" is unknown, not absent, when Docker cannot be asked: the member is held without a container conclusion and roster_unreadable is the only blocker. The tests now assert the exact blocker list with an existing member seeded, and an HTTP case pins the 503. * fix(systems): the apply lease stops writes at a local deadline, not only on a renewal result (Abilityai/trinity-enterprise#695) The keeper renews on the event loop while the writes are synchronous. A write that blocked the loop past the 900 s TTL let the lease lapse in Redis (and a successor take it) before the keeper ran again, and the writes after it still saw lease.ok == True. The keeper now keeps a conservative deadline: the time the acquisition or the last successful renewal was ISSUED, plus the TTL, minus a margin (min(30 s, TTL/10)). Past it every later write and start is lock_lost, whether or not the keeper got to run. A test blocks the loop inside a write past a 2 s TTL while a successor takes the key, with the keeper never running: the in-flight write finishes, the next one is refused, and the successor's lease is left alone. * fix(systems): nothing in apply's executor can raise past a write (Abilityai/trinity-enterprise#695) Preparing a member's AgentConfig ran outside the per-write attempt and read the fleet default resources (a settings read) after earlier members had already been created and tagged. A failure there escaped the executor as a bare 500, losing the partial report and the audit row. The default is now read once by the snapshot, where a failure is a retryable member_reads_unavailable blocker before any write (create mode reads the same setting per member, so bootstrap equivalence holds). The config is built inside the create's own attempt, and the per-op dispatch is guarded so an unexpected error becomes a failed[] row. * fix(systems): restart_required reads the mount predicate strictly, for every existing member (Abilityai/trinity-enterprise#695) Two ways apply's restart_required could be wrong: - check_shared_folder_mounts_match keeps whatever mount is there when a source-volume inspect fails for a reason other than NotFound. That is right for the start path (an unknown must not trigger a recreate) and wrong for apply, which reported the unknown as "mounts match". The helper gains a keyword-only strict=False; apply passes strict=True, so the failure is a retryable member_reads_unavailable. The start path is unchanged. - After the writes, only members with their own folder/resource writes were re-read. A new edge into an exposing peer (or a peer's expose flipping) changes the mounts a consuming member must have, so every existing member is now re-read once anything landed; a member whose read fails keeps the plan's prediction, with a warning. The dry run predicts it for a consuming member that gains an edge or sees an expose flip. * fix(systems): a malformed schedule entry is a named blocker, never a 500 (Abilityai/trinity-enterprise#695) validate_manifest checks only that a schedule's name, cron and message are present, so `{name: [daily], ...}` reached the schedule matcher, which keys a dict on the name and raised TypeError: an unnamed 500 on both the dry run and the real run. Every declared entry now goes through the writer's own ScheduleCreate first; a rejected one is schedule_definition_invalid and is left out of matching. Create mode is unchanged. * test(systems): the lease fakes run the production Lua text, not a copy of its logic (Abilityai/trinity-enterprise#695) Both Redis fakes (the lease unit tests and the apply world) implemented the compare-and-expire / compare-and-delete in Python and ignored the script body, so a mutated script (the token compare dropped, == flipped to ~=) stayed green; the compare is the whole point of the atomic methods. fakeredis here has no Lua and adding lupa would be a test-requirements change, so _ent695_lua.py executes the small Lua subset the scripts use (if/else/end, return, redis.call, ARGV/KEYS, ==/~=) with Redis semantics (a missing key's GET is false; arguments arrive as strings) and refuses any construct outside it. Dropping the refresh compare or flipping the release compare now turns four tests red each. * fix(systems): the system_apply audit row records what happened, not the plan (Abilityai/trinity-enterprise#695) The router built the audit details from the response's members: every planned create was listed as created and every planned write counted, so a run whose creates all failed still recorded them as done. The executor now counts the writes that landed per member, and the response carries the actually created members and those counts as private attributes the router logs. * fix(systems): a failed read's blocker names the error class, never its SQL (Abilityai/trinity-enterprise#695) member_reads_unavailable and roster_unreadable put the exception message into the response detail. _failure_reason redacts credentials, not a database error's "[SQL: ...] [parameters: ...]" text. The detail now names the exception class and the message goes to the server log. The schedule and resource validators' messages (they echo the caller's own cron, timezone or cpu) now leave through _failure_reason like every other reason, for one exit point. * docs(systems): state the leftover-volume residual; correct the enumeration note (Abilityai/trinity-enterprise#695) roadmap.md 16.5.4 states the one dry-run vs real-run difference left: a free name whose workspace volume is an unclaimed leftover (#1667) is planned as a create, and the real run's create refuses it (409) into failed[], never suffixed. The member_name_unavailable comment cited create mode's _2 warning as the reason the refusal adds no existence oracle; the stronger baseline is POST /api/agents, which already answers 409 to any creator for a taken, soft-deleted or volume-reserved name. * test(systems): exempt apply's two schedule writers in the fleet-reach db guard, with their gates (Abilityai/trinity-enterprise#695) test_every_db_predicate_call_sits_behind_a_narrowed_gate scans each function that calls a db method running can_user_access_agent / can_user_share_agent on a username it is handed (here db.create_schedule) and requires a narrowed gate in the same function. Apply's executor calls it from _run_op (an existing member's new schedule, as the member's owner) and _apply_created_schedules (a member this run created, as its creator). Both sit behind gates the function cannot see: the route is require_person, and read_apply_snapshot classifies every written member through can_user_share_agent + agent_may_reach(manage=True) before any plan exists. The guard's _DB_EXEMPT table is the mechanism for that case (deploy's create_schedules is exempted the same way), so each entry states its gates. Found by the batch run of all three slices on one integration branch: red there and on this branch alone, green on dev and on the other two slices. Removing either entry turns the guard red naming exactly that function. * fix(systems): apply's roster is the agents the caller may manage, not merely see (Abilityai/trinity-enterprise#695) An independent review found that the roster, filtered by access, held agents shared with the caller that the caller cannot manage. Another user's untagged `acme-notes`, shared with Alice, refused her apply of `acme` with a 409 whose remedy (tag it) only its owner may perform, and a tagged one showed as her drift. The roster now uses the manage predicate the name classification already uses (can_user_share_agent + agent_may_reach(manage=True)): such an agent never blocks, is never drift, and is never named in the response. The same review's smaller points, fixed here: - a created member with `folders: {}` keeps its template's shared-folder settings, as in create mode (it was written expose=false, consume=false); - with Docker unreadable, a declared name that reads as free is `blocked` in the dry run, never `create` (a container-only name cannot be seen); - `failed[].step` uses one name per writer whether the write was attempted or skipped (create, tag, permissions, folders, resources, schedules, start); the phase order is now derived from that one table; - tests: a 503 only when every blocker is retryable (a mixed set is a 409), and a declared member owned by another user is a 409 over the real authenticated path with nothing written and the owner never named. Each fix's test goes red with the fix reverted. * fix(systems): apply's roster needs a live owner row, as the name classification does (Abilityai/trinity-enterprise#695) The second reviewer of the previous fix found the case it left open: can_user_share_agent is True for any admin, so a container with no live owner row (nobody owns it, its tag route answers 404) still entered an admin's roster: untagged, it refused the run with a remedy no one can follow; tagged, it showed as drift. The roster is now the live ownership rows the caller may manage, the same live-owner condition the name classification already applies. Containers are still read for the taken check, the member reads and the unreadable-Docker refusal, and a recovered agent with a live row and no container is still a member. The new test turns red with the roster built from containers again. * chore(systems): apply's comments say what they mean, without outside labels (Abilityai/trinity-enterprise#695) Comments, docstrings and twelve test class names in the apply engine carried short labels that resolve only in a document outside this repository. They now state the point directly; the P-A..P-F principles, defined in requirements roadmap.md section 16.5.4, stay. Also separates the two import groups in the snapshot's local imports (ruff I001); the module's other import findings predate this branch. No behaviour change: with docstrings masked and the class renames mapped, the module and test ASTs are identical to the previous commit.
This was referenced Nov 9, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Add internal health endpoint, without which the application didn't start locally