Repository navigation
Fix git pushing bug - #9
Merged
Merged
Conversation
This was referenced Apr 12, 2026
dolho
added a commit
that referenced
this pull request
Jun 15, 2026
Add CLAUDE.md Rule #9: every schema change needs both a SQLite entry in db/migrations.py and a Postgres Alembic revision under migrations/versions/, plus DDL in schema.py/tables.py. SQLite stays supported; PG-only is eventual, not near-term. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Jun 15, 2026
…1186) * feat(db): adopt Alembic for PostgreSQL migrations — Phase 1 (#1183) The PostgreSQL backend's schema is now owned by Alembic instead of the fresh-build-from-schema.py path. SQLite keeps its bespoke db/migrations.py runner — the two coexist during the Postgres transition (SQLite is being retired). - migrations/ (env.py targets db/tables.py MetaData), alembic.ini, and a 0001_baseline revision that reuses the exact init_schema_postgres head DDL (tables + indexes + triggers) so a fresh PG DB built by `alembic upgrade head` is identical to the old fresh build. - db/alembic_runner.upgrade_to_head(): fresh DB -> upgrade head; pre-Alembic PG DB (no alembic_version) -> stamp baseline then upgrade (not rebuilt); managed DB -> apply pending revisions. - init_database() non-SQLite branch calls the runner (was init_schema_postgres). - alembic==1.18.4 in the backend image (scheduler doesn't run migrations). - Postgres-gated integration tests (TEST_POSTGRES_URL): fresh build, idempotency, downgrade-to-base, pre-Alembic stamp path, and schema parity vs the legacy init_schema_postgres build. All 5 pass against postgres:16. Verified end-to-end against a throwaway postgres:16. SQLite init path unchanged. Deferred: enterprise Alembic domain ships in the private enterprise repo (Phase 2); autogenerate-from-metadata + SQLite retirement (Phase 3, with #746). Related to #1183. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs: require dual SQLite+Postgres migrations for schema changes (#1183) Add CLAUDE.md Rule #9: every schema change needs both a SQLite entry in db/migrations.py and a Postgres Alembic revision under migrations/versions/, plus DDL in schema.py/tables.py. SQLite stays supported; PG-only is eventual, not near-term. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(docker): ship migrations/ + alembic.ini in the backend image (#1183) db/alembic_runner.py sets Alembic's script_location to /app/migrations at runtime, but the Dockerfile only globbed top-level *.py plus named subdirs — the new migrations/ dir and alembic.ini were dropped from the prod image. A PostgreSQL deploy would crash-loop in init_database() -> upgrade_to_head() because the script directory is absent (same #1033 packaging-gap class; CI missed it since schema-parity/integration tests run against source and the prod smoke boots SQLite). COPY both into the image and include migrations/ in the readability chmod step. alembic.ini isn't needed at runtime (the runner builds its Config programmatically) but is copied so the alembic CLI works in-container for ops. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
7 tasks done
1 task
dolho
added a commit
that referenced
this pull request
Jun 19, 2026
…ed helper Applies the six code-review findings on the #1265 dashboard perf PR: 1. [high] Add Alembic revision 0002_activities_created_index so EXISTING Postgres deployments (stamped at 0001_baseline, never re-running baseline) pick up idx_activities_created. Fresh PG builds already get it via 0001_baseline iterating db/schema.py:INDEXES. CLAUDE.md Rule #9 (dual-track). 2. [med] get_latest_execution_per_schedule now projects only the 6 dashboard fields instead of select(*) — no longer streams response/execution_log (100KB+)/tool_calls/message it never uses. Returns slim dicts (timestamps ISO-normalised to match the prior .isoformat() output); ops.py updated. 3. [med] Document that the admin timeline's unfiltered scope (full audit history incl. deleted agents) is intentional, not an accidental widening. 4. [low] Cap the context-stats HTTP connect timeout at 0.5s so a stale-`running` agent (container gone) fails fast instead of eating the full 2s read timeout — without reintroducing the per-agent Docker lookup that was the bottleneck. 5. [low] Extract the duplicated ROW_NUMBER window into a shared db/query_helpers.py:latest_per_group, reused by both bulk methods. 6. [low] get_latest_activity_for_agents maps rows by NAME via _mapping_to_activity (the helper drops the rn column), removing the fragile positional slice that would silently misalign if _ACTIVITY_COLUMNS were reordered. Tests: test_1265_dashboard_perf updated for the slim dict shape (+ asserts the narrow projection); 9 pass. 93 pass across affected suites. Alembic graph validated: single head 0002 -> 0001 -> base. Related to #1265 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Jun 19, 2026
…#1269) * fix(perf): kill Dashboard/timeline N+1 fan-out at fleet scale (#1265) The Dashboard + timeline took 20s+ to paint metrics on a 10+ agent fleet. Root cause was not the listed endpoints but blocking work serializing the event loop and several per-agent/per-schedule N+1 query patterns: - context-stats: `_fetch_single_agent_context` was `async` but ran a blocking Docker container lookup + a blocking per-agent DB query on the event-loop thread, so the `asyncio.gather` fan-out was effectively serial (10 agents x ~1-2s = the 20s). Now each coroutine does only the async HTTP call: the container host is derived as `agent-{name}` (Docker DNS) with no Docker call, and the latest activity is fetched once via a new bulk `get_latest_activity_for_agents` window query. - /api/agents/slots: replaced the per-agent Redis ZCARD loop with one pipelined round-trip (mirrors heartbeat_status_bulk). - /api/ops/schedules: replaced the per-schedule `get_schedule_executions` loop with one `get_latest_execution_per_schedule` window query. - /api/activities/timeline: pushed the per-user access filter into SQL (agent_name IN ...) and dropped the limit*2 Python-side over-fetch; added a standalone idx_activities_created index (schema.py + migration) so the fleet-wide ORDER BY created_at DESC stops scan+sorting. - Invariant #16: get_agent_health_history now uses iso_cutoff() instead of datetime.utcnow(); same in context-stats activity cutoff. No new cache layer, so no freshness/invalidation risk. New bulk methods are covered by tests/unit/test_1265_dashboard_perf.py (SQLite + Postgres via the #300 harness); window-function constructs verified on SQLite. Related to #1265 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(perf): address #1269 review — PG migration, slim projection, shared helper Applies the six code-review findings on the #1265 dashboard perf PR: 1. [high] Add Alembic revision 0002_activities_created_index so EXISTING Postgres deployments (stamped at 0001_baseline, never re-running baseline) pick up idx_activities_created. Fresh PG builds already get it via 0001_baseline iterating db/schema.py:INDEXES. CLAUDE.md Rule #9 (dual-track). 2. [med] get_latest_execution_per_schedule now projects only the 6 dashboard fields instead of select(*) — no longer streams response/execution_log (100KB+)/tool_calls/message it never uses. Returns slim dicts (timestamps ISO-normalised to match the prior .isoformat() output); ops.py updated. 3. [med] Document that the admin timeline's unfiltered scope (full audit history incl. deleted agents) is intentional, not an accidental widening. 4. [low] Cap the context-stats HTTP connect timeout at 0.5s so a stale-`running` agent (container gone) fails fast instead of eating the full 2s read timeout — without reintroducing the per-agent Docker lookup that was the bottleneck. 5. [low] Extract the duplicated ROW_NUMBER window into a shared db/query_helpers.py:latest_per_group, reused by both bulk methods. 6. [low] get_latest_activity_for_agents maps rows by NAME via _mapping_to_activity (the helper drops the rn column), removing the fragile positional slice that would silently misalign if _ACTIVITY_COLUMNS were reordered. Tests: test_1265_dashboard_perf updated for the slim dict shape (+ asserts the narrow projection); 9 pass. 93 pass across affected suites. Alembic graph validated: single head 0002 -> 0001 -> base. Related to #1265 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
7 tasks done
This was referenced Jun 28, 2026
vybe
pushed a commit
that referenced
this pull request
Jun 28, 2026
…ntical responses (#1157) (#1368) * feat(loops): add no_progress_threshold column (dual-track migration) Adds the nullable `agent_loops.no_progress_threshold INTEGER` column for doom-loop detection. NULL = disabled (back-compat for in-flight loops). Dual-track per Invariant #9: SQLite `_migrate_agent_loops_no_progress` (idempotent `_safe_add_column`) + Alembic `0007_agent_loops_no_progress` (`ADD COLUMN IF NOT EXISTS`, chained after `0006_agent_reports`). DDL in both `schema.py` (SQLite) and `tables.py` (MetaData). `_loop_row_to_dict` + `LoopOperations.create_loop` carry the field through. Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(loops): detect no-progress doom loops in the runner The runner fingerprints each successful run's full response (`_fingerprint = sha256(" ".join(text.split()))` — collapses whitespace, preserves word boundaries, empty/whitespace-only fold to one fingerprint) and tracks consecutive identical results in a runner-local `last_fingerprint`/`repeat_count` (no persistence). Once K consecutive runs match, the loop stops with status `stopped` / `stop_reason="no_progress"`. Precedence: `stop_signal_matched` is checked first and wins; a pending `user_stopped` or passed deadline also outranks `no_progress` (re-checked before the break) so an explicit stop is never relabeled. Exact-hash only — no fuzzy/semantic similarity. NULL/0 threshold disables. Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(loops): accept no_progress_threshold on the loop API `StartLoopRequest` gains `no_progress_threshold: Optional[int]` (default 3, ge=0) with a `field_validator` rejecting `1` → 422 ("repeated identical" needs ≥2). The router threads it into `loop_service.start_loop()`, and `LoopStatusResponse` / `_build_status_response` carry it back through `GET /api/loops/{id}`. Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(mcp): expose no_progress_threshold on run_agent_loop Adds the `no_progress_threshold` param to the `run_agent_loop` MCP tool with a zod `.int().min(0).refine(v !== 1)` validator mirroring the backend (0 disables, default 3, 1 rejected). Threaded through `TrinityClient.startAgentLoop`. Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(loops): no-progress threshold field in LoopsPanel Adds the "No-progress threshold" number input (default 3, 0 disables) with helper text to the Run-loop form. The `0` disable sentinel is sent explicitly — a truthy guard would drop it. `formatStopReason` maps the new `no_progress` reason to a readable label. Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(loops): cover no-progress doom-loop detection ~13 unit tests: stop-at-K, near-miss counter reset, response normalization (whitespace/empty collapse), precedence over stop_signal / user_stop / deadline, K > max_runs, the WS event contract, router default-on, K=1 → 422, and GET round-trip of the threshold. Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(loops): document no-progress detection (#1157) requirements §38.3, architecture (Sequential Agent Loops + agent_loops schema/stop_reason enum), the run-agent-loop feature flow, and a feature-flows index row. Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(security): CSO --diff report for #1157 (0 findings) Refs #1157 Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
12 tasks
6 tasks done
vybe
pushed a commit
that referenced
this pull request
Jul 9, 2026
#1533) (#1554) * fix(channels): count inbound client messages on the Sharing-tab roster (#1533) The roster showed `message_count = 0` for every external client, `last_active` was frozen at `/login` time, and clients who never ran `/login` never appeared at all. All three share one cause: `get_or_create_chat_link` and `increment_message_count` (Telegram + WhatsApp) had zero callers outside the `database.py` facade. The shared inbound path writes `public_chat_sessions`, a different table, so `*_chat_links` rows were only ever created by `set_*_verified_email` — the `/login` flow. Note: the issue's Context paragraph states that `last_active` "is touched on inbound traffic via `get_or_create_chat_link`". It is not — that function was dead, and returns early for an existing row without writing anything. Revive the write path behind a default-no-op `ChannelAdapter.record_inbound_activity` hook, called once per delivered DM from `ChannelMessageRouter._handle_message_inner` at step 5c: after the access gate, so an unauthenticated stranger who messages the bot cannot create unbounded chat-link rows, and skipped for groups, since a chat link is keyed by (binding, user) and counting group traffic would list members who never DM'd the agent. Telegram and WhatsApp override it; Slack and VoIP inherit the no-op (Invariant #9). The call is best-effort — a counter write never blocks message processing. Replace `get_or_create` + `increment` with one atomic `INSERT … ON CONFLICT DO UPDATE` (`record_inbound`), which removes a cross-worker SELECT-then-INSERT race under `--workers 2`, halves the writes per message, and refreshes a stale display name via `COALESCE(excluded, existing)`. Since `increment_message_count` was `last_active`'s only live writer, one call fixes the count and the timestamp together. Delete the now-dead methods, their facade delegations, and the `_row_to_chat_link` helper they alone called. Historical counts are not backfilled; the roster's "Messages" header says so. Tests: dual-backend (SQLite + PostgreSQL) roster read-back 0->1->2, `last_active` advance, username backfill, and `/login` interplay through the real `db_backend` harness; the real `_handle_message_inner` for the DM, group, access-denied and counter-failure paths; and the adapter override bodies executed for real — mutation-verified, a typo'd metadata key turns the suite red. A facade-delegation guard covers the wholesale-mock blindness recorded in docs/memory/learnings.md. Verified against a live instance: real Telegram webhook payloads through the real transport drive the roster 0->1->2; a group message reaches the router and is not counted; an access-denied message creates no row. Follow-up #1552 records the read-time-derivation reframe (deriving the roster from public_chat_messages) that this tactical fix deliberately defers. Fixes #1533 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(channels): use an example.com placeholder email in the #1533 access-denied case The public-repo rule in CLAUDE.md calls for `[email protected]`-style placeholders. `[email protected]` was copied from the neighbouring access-gate test and was also inconsistent with the rest of this file, which already uses `[email protected]`. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
3 of 4 tasks
AndriiPasternak31
added a commit
that referenced
this pull request
Jul 26, 2026
* chore(.claude): bump dev-methodology submodule — Product Quality Bar Points .claude at trinity-dev 57c8b5c: adds a canonical Product Quality Bar section to DEVELOPMENT_WORKFLOW.md (six adoption/ease-of-use principles) and hooks it into the dev pipeline — /create-issue (acceptance criteria), /autoplan (scope calibration → taste decisions), /implement (build-time checklist), and /review (new 4.15 catch-in-diff check). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(announcements): v0.8.0 announcement record (#1548) * chore(.claude): bump dev-methodology submodule — Product Quality Bar Points .claude at trinity-dev 57c8b5c: adds a canonical Product Quality Bar section to DEVELOPMENT_WORKFLOW.md (six adoption/ease-of-use principles) and hooks it into the dev pipeline — /create-issue (acceptance criteria), /autoplan (scope calibration → taste decisions), /implement (build-time checklist), and /review (new 4.15 catch-in-diff check). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(announcements): v0.8.0 release announcement record (all channels) --------- Co-authored-by: Eugene Vyborov <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * fix(avatar): prevent thinking-token truncation dropping the color-scheme block Avatar refinement runs each identity prompt through GEMINI_TEXT_MODEL to append a fixed technical block (background #1a1f2e/#111827, indigo rim #6366f1, head-and-shoulders framing, 85mm lens, 5600K key) — the sole source of avatar color scheme and cross-generation consistency. The refinement call capped maxOutputTokens at 512. Since #1130 the default model is gemini-3.5-flash, a *thinking* model whose reasoning phase draws from the output budget. Reasoning consumed ~491 of 512 tokens, truncating the refined prompt (finishReason=MAX_TOKENS) to a ~90-char fragment that dropped the entire technical block. Avatars were then generated from a bare subject description — wildly inconsistent and off-palette. Fix in _call_gemini_text: - Disable thinking (thinkingConfig.thinkingBudget=0) — refinement is a deterministic rewrite that needs no chain-of-thought. - Raise maxOutputTokens 512 -> 4096 as headroom even when thinking stays on. - Retry once WITHOUT thinkingConfig on HTTP 400: a thinking-mandatory model (e.g. gemini-2.5-pro) rejects budget=0, and refine_prompt silently falls back to the raw prompt on error, so an unhandled 400 would re-break avatars. Verified end-to-end against the live model: all 6 technical-block tokens now survive refinement (was 0/6). Adds 3 regression tests. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(channels): count inbound client messages on the Sharing-tab roster (#1533) (#1554) * fix(channels): count inbound client messages on the Sharing-tab roster (#1533) The roster showed `message_count = 0` for every external client, `last_active` was frozen at `/login` time, and clients who never ran `/login` never appeared at all. All three share one cause: `get_or_create_chat_link` and `increment_message_count` (Telegram + WhatsApp) had zero callers outside the `database.py` facade. The shared inbound path writes `public_chat_sessions`, a different table, so `*_chat_links` rows were only ever created by `set_*_verified_email` — the `/login` flow. Note: the issue's Context paragraph states that `last_active` "is touched on inbound traffic via `get_or_create_chat_link`". It is not — that function was dead, and returns early for an existing row without writing anything. Revive the write path behind a default-no-op `ChannelAdapter.record_inbound_activity` hook, called once per delivered DM from `ChannelMessageRouter._handle_message_inner` at step 5c: after the access gate, so an unauthenticated stranger who messages the bot cannot create unbounded chat-link rows, and skipped for groups, since a chat link is keyed by (binding, user) and counting group traffic would list members who never DM'd the agent. Telegram and WhatsApp override it; Slack and VoIP inherit the no-op (Invariant #9). The call is best-effort — a counter write never blocks message processing. Replace `get_or_create` + `increment` with one atomic `INSERT … ON CONFLICT DO UPDATE` (`record_inbound`), which removes a cross-worker SELECT-then-INSERT race under `--workers 2`, halves the writes per message, and refreshes a stale display name via `COALESCE(excluded, existing)`. Since `increment_message_count` was `last_active`'s only live writer, one call fixes the count and the timestamp together. Delete the now-dead methods, their facade delegations, and the `_row_to_chat_link` helper they alone called. Historical counts are not backfilled; the roster's "Messages" header says so. Tests: dual-backend (SQLite + PostgreSQL) roster read-back 0->1->2, `last_active` advance, username backfill, and `/login` interplay through the real `db_backend` harness; the real `_handle_message_inner` for the DM, group, access-denied and counter-failure paths; and the adapter override bodies executed for real — mutation-verified, a typo'd metadata key turns the suite red. A facade-delegation guard covers the wholesale-mock blindness recorded in docs/memory/learnings.md. Verified against a live instance: real Telegram webhook payloads through the real transport drive the roster 0->1->2; a group message reaches the router and is not counted; an access-denied message creates no row. Follow-up #1552 records the read-time-derivation reframe (deriving the roster from public_chat_messages) that this tactical fix deliberately defers. Fixes #1533 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * test(channels): use an example.com placeholder email in the #1533 access-denied case The public-repo rule in CLAUDE.md calls for `[email protected]`-style placeholders. `[email protected]` was copied from the neighbouring access-gate test and was also inconsistent with the rest of this file, which already uses `[email protected]`. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * test(ci): auto-trigger frontend-e2e (nightly + frontend paths), keep ui opt-in (#1526) (#1551) The frontend-e2e Playwright suite ran ONLY on `ui`-labeled PRs, so most PRs never triggered it and the suite rotted silently — specs broke against structural/UX changes and sat red on `dev` for weeks (four documented instances: #1134, #1508, #1378). The gate itself was the root cause. Add automatic triggers so a red suite is always visible: - Nightly `schedule` (07:00 UTC) on `dev` — the durable signal. A red nightly opens/updates a single tracking issue (new `report` job, label `frontend-e2e-nightly`), à la #1185; a green nightly closes it. - Auto-run on any PR that touches `src/frontend/**` (dependency-free `changes` job via `gh pr diff`), so frontend authors see their own breakage. - The `ui` label still works as a manual opt-in on non-frontend PRs and to force a run (preserved for the heavier @visual/@interactive tiers, #596). - `workflow_dispatch` for on-demand runs. DECISION (AC): advisory, NOT a required merge gate. The recurring failure class is modal/overlay flake on a fresh zero-user-agent stack, so a hard gate like #715's unit gate needs a flake budget first (#596). Recorded in the workflow header. Per-job least-privilege permissions; concurrency keyed per-PR (cancel) vs per-ref (schedule, no cancel). Only @smoke runs in CI, unchanged. Related to #1526 * feat(mcp): make per-agent MCP connector OSS-core (trinity-enterprise#118 Part A) (#1555) * feat(mcp): make per-agent MCP connector OSS-core (trinity-enterprise#118 Part A) Relocate the per-agent MCP connector (ent#46/#55/#51, shipped v0.8.0 entitlement- gated as `mcp_connector`) from the private enterprise submodule into OSS core, and drop the entitlement gate front and back. Decision (Eugene, 2026-07-09): sharing agents via individual MCP connectors is a platform-adoption surface, not a paid module. Backend (router → service → db, Invariants #1/#2/#14): - routers/connector.py — /api/agents/{name}/connector* (config, mint/regenerate/ revoke key, playbooks), mounted unconditionally in main.py; no requires_entitlement. - services/connector_service.py — snippet builder + playbook resolution. - db/connector.py (ConnectorOperations) — config CRUD + scoped-key mint/revoke into mcp_api_keys (scope='connector'); facade delegators on database.py. - models.py — ConnectorConfigUpdate/Status/KeySecret/Playbook/ClientSnippet. Schema: enterprise_connectors table re-homed onto OSS dual-track (db/tables.py, db/schema.py, db/migrations.py:enterprise_connectors_table + Alembic 0015_enterprise_connectors). Name kept so existing enterprise installs adopt their data with zero migration (CREATE TABLE IF NOT EXISTS, no duplicate-table drift). Delete/rename cascade via an enterprise_connectors AGENT_REF. Frontend: ConnectorChannelPanel un-gated in SharingPanel.vue (dropped the isEntitled('mcp_connector') v-if + the now-unused enterprise store wiring). The MCP proxy tools (connector.ts), the connector-scope auth fence (dependencies.py), and ExposedToolsPanel.vue were already OSS and edition-agnostic. `mcp_connector` is removed from the entitlement registry by the paired enterprise PR (deletes register_module). Docs: requirements mcp.md §7.5 + feature-flows/mcp-connector.md + architecture/index. Tests: tests/unit/test_118_mcp_connector_oss.py (11) — service helpers, config CRUD, key mint/regenerate/revoke, scope='connector' validate contract. Part B (email-auth onboarding, #848) deferred pending design sign-off. Related to trinity-enterprise#118 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * chore(submodule): bump enterprise to post-#121 so the connector isn't double-mounted (#118) #1555 makes the per-agent MCP connector OSS-core. The enterprise submodule was pinned at 630cca9e, which still ships backend/mcp_connector/ and registers it via register_enterprise() — so an enterprise build would double-mount the connector router alongside the new OSS-core one. Bump the pin to f5d69be6 (enterprise main post trinity-enterprise#121), where the private module is removed. This forward-integrates two already-on-enterprise-main commits into the pin: - trinity-enterprise#121 — removes backend/mcp_connector/ (the intended pair) - trinity-enterprise#120 — ENTERPRISE_LOCAL_DEV docs (docs only) - trinity-enterprise#106 — client-portal umbrella (already on enterprise main) OSS-only CI is unaffected (submodule is update=none / "boots without enterprise"). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]> * docs(enterprise): explain the private feature catalog + runtime verification ENTERPRISE.md documents the open-core seam mechanism (correct) but never said WHERE the feature-level OSS/enterprise split lives or WHY it isn't here. Add a short "Why there's no feature catalog here" note: the standing rule trinity-enterprise#45 (enforced by enterprise-docs-guard.yml) keeps the paid-feature catalog private, and entitled customers find it in the private enterprise repo. Point readers at the runtime source of truth for "what's enabled on this instance" (GET /api/version + feature-flags). Mechanism-only, no named features — enterprise-docs-guard grep verified green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * docs(announcements): webinar video announcement record 2026-07-10 Record of the "sovereign, isolated AI agents per client" webinar video announcement (https://youtu.be/8w98dA6hDew) sent via /announce to Discord, Slack, Telegram, Twitter/X (trinity + default), and GitHub Discussions. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * chore(deps-dev): bump @types/node (#1531) Bumps the patch-and-minor group in /src/mcp-server with 1 update: [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node). Updates `@types/node` from 26.1.0 to 26.1.1 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) --- updated-dependencies: - dependency-name: "@types/node" dependency-version: 26.1.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: patch-and-minor ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * fix(reliability): clear per-agent Redis runtime state across the agent lifecycle (#1560) (#1568) * fix(reliability): clear per-agent Redis runtime state across the agent lifecycle (#1560) `agent:circuit:{name}` (transport breaker) is keyed by agent NAME, not container identity, and carries no TTL. Nothing in the lifecycle cleared it, so a container replaced under the same name inherited its predecessor's `dormant` verdict and fast-failed every execution with "Agent circuit breaker open — agent is unhealthy" — without the backend ever contacting the agent. Adds `services/agent_runtime_state.py` as the single enumeration point for every name-keyed per-agent Redis keyspace (the Redis-side twin of the `AGENT_REFS` registry in `db/agent_cleanup.py`), with two entry points whose blast radii differ by whether a container is running: clear_agent_breakers heartbeat + transport circuit + dispatch breaker (safe on a live container) clear_agent_runtime_state the above + execution slots (teardown paths only — force_clear_slots would drop capacity accounting for an in-flight #1083 execution) Wired into six lifecycle points. The issue's acceptance criteria named delete, rename and create; none is the reachable path: * create is unreachable — `is_agent_name_reserved` sees soft-deleted rows and 409s, locking the name for the whole retention window; * the name only unlocks at the retention purge, which cleared no Redis state; * the reachable path is `start_agent_internal`, whose `needs_recreation` branch replaces the container on any config drift (subscription switch, resource change, auth-token rotation), so one fleet-wide rotation resurrects every stale verdict. So start/recreate, purge, and the `trinity-system` bootstrap were added beyond the written criteria. The start-path clear runs before the recreate, since `containers_run(detach=True)` brings the replacement up, and is guarded on `needs_recreation or not was_already_running` so a no-op start cannot reset a breaker protecting a wedged agent. Tests: a bidirectional parity guard fails CI when a new `agent:*` keyspace ships unregistered; wiring tests pin all six call sites and that lifecycle.py never clears slots; an integration test exercises the real Lua (fakeredis has no EVALSHA) plus an opt-in leg driving the full recreate path over HTTP. Both guards are mutation-tested. Complementary to #1561, which removes the source of breaker poisoning; this removes the inheritance. Both are needed. Fixes #1560 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * test(1560): stop bare sys.modules mutations in the new test files (#762) The `lint (sys.modules pollution check)` CI gate flagged 7 new violations. They were real, not a lint technicality: the integration test replaced `sys.modules["services"]` with a bare stub module and never restored it, so every later test in the same session that imported the real `services` package would have seen the stub — the exact cross-file pollution class #762 introduced this gate for. - Unit files: drop the `sys.modules[mod_name] = module` registration in `_load` entirely. `agent_runtime_state.py` is a stdlib-only leaf with no `@dataclass` needing `sys.modules[cls.__module__]` to resolve annotations, so the registration bought nothing and risked pollution. Per-test stubs already go through `monkeypatch.setitem`, which restores itself. - Integration file: keep the bindings (they are what makes the production lazy imports resolve to the real modules against real Redis — monkeypatch cannot reach an import performed inside the function under test) and add the sanctioned `_STUBBED_MODULE_NAMES` + autouse `_restore_sys_modules` snapshot/restore pair, per tests/unit/test_telegram_webhook_backfill.py. Verified: `python tests/lint_sys_modules.py` clean; running the integration file followed by a suite that imports the real `services` package passes. Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * fix(ui): prettify Agent Permissions Matrix — bigger labels, no grid jump (#1563) The fleet permissions matrix was hard to read (text-xs, 32px cells) and the grid jumped on every grant/revoke: the toast rendered inline between the toolbar and the grid, so it pushed the grid down on appear and snapped it back on the 3.5s auto-dismiss. - Bump base font (text-xs → text-sm), cells (w-8 h-8 → w-11 h-11), checkmark (text-base), row/column agent labels (font-medium), corner hints (10px → text-xs), and column-label headroom (8rem → 10rem). - Move the toast into a reserved min-h-[2.5rem] slot so appear/dismiss no longer reflows the grid. Presentation-only — grant/revoke logic and endpoints unchanged. Grant/revoke verified end-to-end via the backend API. Related to #1562 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * fix(sync-health): exclude soft-deleted agents from list_git_enabled_agents (#1561) (#1565) `list_git_enabled_agents()` selected from agent_git_config on sync_enabled alone, without joining agent_ownership or excluding deleted_at. Soft delete keeps the git_config row, so the 60s SyncHealthService poller kept issuing HTTP calls to removed containers forever — each httpx.ConnectError poisoned the transport circuit breaker, eventually driving it DORMANT and emitting a bogus circuit_breaker_dormant operator-queue alert for a nonexistent agent. GET /api/fleet/sync-audit (same accessor) also listed dead agents. - Join agent_ownership + filter deleted_at IS NULL, mirroring the #834 hardening on list_all_enabled_schedules(). Fixes both consumers at once. - git_service.get_git_status: bare print() → logger.warning (structured). - Regression tests: soft-deleted agent is excluded from the accessor and never polled (zero HTTP, no sync_state row, no operator-queue entry). Audit sweep (per AC): list_git_enabled_agents was the sole background-loop accessor missing the deleted_at filter. Other per-agent HTTP pollers (monitoring, operator-queue) enumerate from Docker, so removed containers are inherently excluded; scheduler already filters (#834); capacity drain is DB-only (no agent HTTP). Companion breaker-inheritance defect tracked in #1560. Related to #1561 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * feat(canary): execution-row integrity invariants E-03, G-03, E-04, G-04 (Phase 4) (#1497) * test(canary): unblock canary_invariants fixture broken by #1472 merge Two pre-existing breakages landed via #1472 (367a5e12, merged today) in root-level tests/test_canary_invariants.py — a file the CI unit job (tests/unit/ only) does not run, so they merged undetected: 1. Duplicate `CREATE TABLE agent_schedules` in the `canary_db` fixture DDL — the E-06 work added a second definition next to the pre-existing one, so `executescript` raised "table agent_schedules already exists" and every fixture-dependent canary test errored. Removed the older, unused block (its `message`/`owner_id` columns have no consumer; `_add_schedule` and the E-06/L-03 collectors use only the kept block's columns). 2. `test_run_invariants_all` expected registry set omitted "E-06" (added to the invariants registry by the same PR). Added E-06 to the expected set and asserted it is green on a clean platform. Restores a green baseline (92 passed) so the #1450 B-01 work can be verified. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(canary): B-01 queue-status coherence — backend-consistent Side B + confirm-re-read (#1450) B-01 compared two reads that were neither temporally atomic nor backend-consistent (both latent while the canary is default-OFF and SQLite makes the two reads hit one file): (a) Temporal non-atomicity — a concurrent enqueue/backlog-drain landing between the two reads produced a transient count mismatch → spurious critical + green→red Slack alert. (b) Backend divergence (#300/#1093) — Side A (`db.get_queued_count`) honors `get_engine()`/DATABASE_URL; Side B read raw sqlite3 at DB_PATH. On Postgres those are two different databases, so B-01 compared Postgres truth to a stale/absent SQLite file (fatal under the Postgres direction + SQLite EOL, #1278). Production-side residue of #1446 (PR #1452), which fixed only the test-harness `sys.modules` leak and deferred these two gaps. Fix (localized to B-01): - New `_collect_queued_ids_via_engine` reads B-01's Side B through the SAME `get_engine()` seam as the accessor, on a dedicated `queued_ids_via_engine` snapshot field. Independent code path (SELECT id/literal 'queued' vs COUNT(*)/the QUEUED enum) — shares a database, not a code path, so a cache/status-filter regression still surfaces (non-tautology, AC #3). No cache / second count of the queue (AC #4). - The collector performs one confirm-re-read on a mismatch: a transient race self-heals; a persistent drift survives and fires (AC #2). An engine-read or unconfirmable confirm degrades to a B-01 skip — it never compares an engine count against the raw-sqlite id-set (the blocker the reviews surfaced). - `queued_exec_ids` (raw sqlite) stays untouched for B-02/E-02, so blast radius is B-01-only and the sibling #1077 merge stays clean. The running-side / known-agents reads remain raw-sqlite (half-migrated collector); the collector-wide migration + a dark-canary tripwire are a filed follow-up. Tests (test_canary_invariants.py): retarget the synthetic B-01 tests at `queued_ids_via_engine`; add the AC #5 regression net — a diverged-backend proxy (raw ≠ engine temp files) that false-fires pre-fix and is green post-fix, a transient-race confirm-absorb + persistent-drift-still-fires pair, and an engine-read-failure→skip test. New split fixtures (`canary_db_split` / `reload_canary_split`) model the diverged backend without a live PG. Convert the file to the sanctioned `_STUBBED_MODULE_NAMES` + `_restore_sys_modules` escape hatch so its import-time stubs no longer leak (the #1446 mechanism) and the reimport `del`s are lint-clean. Docs: architecture.md Canary B-01 row updated for the engine-backed read path + confirm-re-read. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(feature-flows): add #1450 canary B-01 Recent Updates row Sync-feature-flows: canary-internal change, no dedicated flow doc (architecture.md is canonical); append one Recent Updates row. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(canary): fix duplicate agent_schedules DDL + reconcile E-06 in registry test The canary_db fixture had two `CREATE TABLE agent_schedules` statements in one executescript (a #1472 merge artifact), so it raised `table already exists` and reddened the whole file. Merge them into one definition carrying every column the canary reads (next_run_at/enabled/deleted_at + agent_name). Add duration_ms/queued_at/backlog_metadata to schedule_executions and extend _add_execution for the #1077 E-03/E-04 collector work. Reconcile E-06 (already registered) into test_run_invariants_all's expected key-set. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(canary): terminal-row collector for E-03/G-03 (#1077) Add _collect_terminal_rows(window_seconds) + Snapshot.terminal_rows. Windowed on started_at (not completed_at, so E-03 can see NULL-completed_at rows), scoped to success/failed/cancelled via a local _E03_TERMINAL_STATUSES subset that excludes skipped (which legitimately has no completed_at/duration_ms). PRAGMA guard skips the source entirely when completed_at/duration_ms are absent (column-absent != value-NULL) rather than false-firing. Window = max per-agent timeout + 300s; bounded ORDER BY started_at DESC LIMIT 5000 with a logged sampled flag (no (status,started_at) index over 90-day retention; tripwire, not backfill audit). Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(canary): register E-03 (completed_at populated) + G-03 (clock sanity) (#1077) E-03 (A/major): terminal rows must have completed_at NOT NULL. Predicate is completed_at-only — the catalog's + duration_ms clause false-fires on healthy queue-terminated rows (cancel/fail/expire set completed_at but never duration_ms). G-03 (A/minor): started_at <= completed_at with a ~1s cross-worker clock-skew tolerance, UTC-aware parsing (E-06 _to_utc shape) so a #1474 mixed naive/Z pair compares without raising. Both are leading-edge tripwires over the shared terminal-row collector and catch all producers incl. the standalone scheduler's raw-SQL writers a unit test never exercises. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(canary): E-03/G-03 synthetic + collector + end-to-end coverage (#1077) Per-invariant synthetic tests (holds-clean, fires-on-violation), collector tests (started_at window in/out, NULL-completed_at still collected, skipped-status excluded, column-absent DDL -> unavailable, LIMIT cap + sampled flag), and end-to-end collect_snapshot tests through the real collector: the C1 cancelled-from-queue holds-clean guard (completed_at set, duration_ms NULL -> zero E-03), half-written fires E-03, bad-clock fires G-03, sub-second skew does not, and the #1474 naive-vs-Z compare-without-raising case. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(canary): document E-03/G-03 Phase 4 invariants (#1077) architecture.md canary table gains E-03/G-03 rows + Phase 4 lookup-key line; requirements/infrastructure.md §31 gains a Phase 4 bullet (and reconciles the stale 'Phase 2 deferred' note now that #882/#1472 shipped); orchestration-invariant-catalog.md annotates E-03/G-03 as shipped with explicit registry-id mapping, notes the E-03 completed_at-only predicate deviation and G-03 started_at<=completed_at reduction, and flags the catalog-id vs registry-id E-06 drift (catalog #129 != registry #1472). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(feature-flows): index row for canary Phase 4 E-03/G-03 (#1077) Canary is an internal invariant harness (no user-facing flow / dedicated flow doc); follows the #1446 precedent of a Recent Updates row pointing at architecture.md. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(canary): queued-row metadata collector for E-04/G-04 (#1077) Capture queued_at + backlog_metadata for status='queued' rows in the existing _collect_executions query, keyed by execution_id in a new AgentSnapshot.queued_meta map. Both columns are PRAGMA-guarded (added by BACKLOG-001): when either is absent on an older/minimal DDL the map is left empty so E-04/G-04 skip those eids (older-image fail-open). Scoped STRICTLY to queued rows — never terminal — so #1449's deferred terminal-row backlog_metadata NULL-out cannot make E-04 false-fire. Co-Authored-By: Claude Opus 4.8 <[email protected]> * feat(canary): register E-04 (queued metadata) + G-04 (no creds in metadata) (#1077) E-04 (Tier A, major): every status='queued' row has queued_at NOT NULL AND a non-NULL, JSON-parseable backlog_metadata — the backlog_service.drain_next replay contract. A malformed blob raises JSONDecodeError and stalls the FIFO. Reports only the failed-predicate reason code + ids, never the raw metadata (may carry credentials; violations persist to canary_violations). G-04 (Tier A, critical): a queued row's backlog_metadata matches no known secret prefix (sk-/ghp_/gho_/ghs_/ghu_/github_pat_/xoxb-/xoxp-/ AKIA/AIza/sk_live_), word-boundary anchored so common substrings don't false-fire. Rides E-04's collected bytes. Reports only the matched pattern NAME + ids, one violation per row (stops at first match) — never the secret, surrounding bytes, or raw metadata. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(canary): E-04/G-04 synthetic + collector + end-to-end coverage (#1077) Collector test proves queued_meta is populated for queued rows only (a terminal row carrying backlog_metadata is excluded — #1449-safe). E-04: holds on valid rows; fires with the right reason code on NULL queued_at, NULL backlog_metadata, and non-JSON metadata; skips an eid absent from queued_meta (older-image fail-open); e2e over a real temp DB. G-04: holds on benign metadata (incl. "task-" substring that must not false-fire); fires on github_pat / openai / slack / aws exemplars; skips NULL metadata (E-04 owns it). Every G-04/E-04 test asserts the secret / raw metadata bytes appear NOWHERE in the persisted violation record. The runner test now expects E-04 + G-04 in the registered invariant set. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(canary): document E-04/G-04 Phase 4 invariants (#1077) architecture.md lookup-key table gains E-04 + G-04 rows and the Phase 4 line now lists all four (E-04/G-04 stacked on #1450). requirements infrastructure.md Phase 4 bullet expands to the full four-predicate set with the credential-safety note. Catalog flips E-04/G-04 from "gated on #1450" to SHIPPED, records the json.loads-vs-json_valid implementation note, the queued-only scope, older-image fail-open, and the report-reason/pattern-name-only security discipline; G-04 notes the implemented check covers the backlog half of the title (log-line scanning out of scope for #1077). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(feature-flows): index row for canary Phase 4 E-04/G-04 (#1077) Also corrects the header/separator ordering left malformed by the earlier E-03/G-03 index-row commit (a data row had slipped above the |---| separator). Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]> * fix(config): forward OPERATOR_INTAKE/DO_NOT_TRACK, DISPATCH_BREAKER_ENABLED, PUBLIC_ACCESS_REQUESTS_ENABLED through compose (#1485) (#1493) * fix(config): honor cross-tool DO_NOT_TRACK convention for operator intake (#1486) The operator-intake kill switch only disabled the outbound POST when DO_NOT_TRACK was one of {"1","true","True"}, so DO_NOT_TRACK=yes|on|2|TRUE leaked despite the obvious opt-out intent — breaking the very consoledonottrack.com convention config.py's own comment cites. Flip to a tracking-allowed whitelist: any value not in {0,"",false} (case/space-insensitive) disables intake. Unset -> "0" -> tracking allowed (unchanged). Add tests/unit/test_1486_do_not_track_truthiness.py so a revert to the exact-tuple check fails loudly. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(config): forward operator-intake, dispatch-breaker & public-access levers through compose (#1485) Same packaging-gap class as PR #1067 (VOIP vars): a lever read by src/backend/config.py that neither compose file forwards into the backend container, so setting it in .env silently no-ops (compose reads .env only for ${VAR} interpolation, and neither backend service uses env_file). Forward in both docker-compose.yml and docker-compose.prod.yml backend environment: blocks, mirroring the existing PUBLIC_CHAT_URL idiom: - PUBLIC_ACCESS_REQUESTS_ENABLED (#1488) — secure default false - OPERATOR_INTAKE_ENABLED / DO_NOT_TRACK / OPERATOR_INTAKE_URL (#1486) privacy kill switch. OPERATOR_INTAKE_URL keeps its FULL non-empty default — a bare :- would arrive set-but-empty and shadow the code default (#1076 set-but-empty class). - DISPATCH_BREAKER_ENABLED (#1487) — global gate for the #526 dispatch breaker; without it the owner-facing PUT .../circuit-breaker toggle silently no-ops (two-tier gating needs both flags on). .env.example: add the missing DISPATCH_BREAKER_ENABLED block (documenting the two-tier gate) and a settable DO_NOT_TRACK=0 line. Backend-only — src/scheduler reads none of these five vars. Fixes #1486 Fixes #1487 Fixes #1488 Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(feature-flows): note DISPATCH_BREAKER_ENABLED compose-forwarding fix (#1487/#1485) The dispatch-circuit-breaker flow already documented the DISPATCH_BREAKER_ENABLED env var, but before this PR that var never reached the container (the #1039/#1067 packaging-gap class), so a reader following the doc would set it and the owner toggle would silently no-op. Add a one-line Config-surface accuracy note + a Recent Updates index row. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]> * fix(scheduler): serialize timestamps as UTC 'Z' so non-UTC browsers show correct relative times (#1474) (#1496) * fix(scheduler): serialize timestamps as UTC with explicit 'Z' (#1474) The standalone scheduler wrote execution/schedule timestamps via datetime.utcnow().isoformat() (no 'Z'), while the backend writes through utc_now_iso() (Z-suffixed). In a non-UTC browser, JS new Date(naive) parses the naive string as local time, shifting schedule-triggered rows by the viewer's UTC offset. Data on disk was fine; only display was wrong. Vendor a byte-parity mirror of the backend timestamp helpers into src/scheduler/utils.py (same regenerate-from-backend discipline as failure_classifier.py): utc_now_iso / to_utc_iso emit 'Z'; parse_scheduler_ts reads tolerantly and returns naive UTC. Write + read land together (atomic): once writes emit 'Z', datetime.fromisoformat("...Z") returns a tz-aware value on 3.11+, and the duration math (datetime.utcnow() - started_at) would raise aware-naive. parse_scheduler_ts converts-then-strips so the historical naive model type is preserved and the subtraction stays naive-naive. All 24 read-parses route through it; every write site (started_at/completed_at/last_run_at/next_run_at/ retry_scheduled_at/validated_at + process-schedule variants) emits 'Z'. Updates the #1472 next_run_at comments to note the mapper now returns naive-UTC (instant preserved), so both compare branches stay correct. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(executions): normalize naive timestamps to UTC 'Z' at read boundary (#1474) The summary/list readers returned raw dict(row) values straight from the DB, so a scheduler-written naive started_at/completed_at serialized naive out of Pydantic and JS new Date(naive) parsed it as local time — the reported schedule-triggered relative-time shift. This fixes historical rows for all consumers at the source (unit-testable, unlike the frontend layer). Reuse the existing parse_iso_timestamp helper (assume-UTC for naive) + the Z-emitting to_utc_iso — the same normalization the already-correct sibling readers (_row_to_execution) apply — via a small _norm_ts shim: - db/schedules.py: get_agent_executions_summary (TasksPanel), get_fleet_executions (ExecutionsPanel), get_agent_schedules_summary last_run_at (Overview/Schedules). - db/activities.py: _row_to_activity / _mapping_to_activity (UnifiedActivity) started_at/completed_at/created_at. None passes through untouched. No data migration. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(ui): parse backend timestamps as UTC in the 5 execution panels (#1474) Defense-in-depth for the read side (covers WebSocket-pushed timestamps and any un-audited endpoint, alongside the backend read-boundary fix). Each panel hand-rolled `new Date(backendStr)`, which parses a naive (no-'Z') string as *local* time. Replace only the internal parse with the shared idempotent `parseUTC` (appends 'Z' when no tz indicator present → correct for legacy-naive, new-'Z', and '+00:00' alike); `new Date()` "now" calls are left untouched and per-panel display formats are unchanged. - TasksPanel: formatRelativeTime + inline log-detail timestamp - SchedulesPanel: formatRelativeTime, isOverdue, formatOverdue, formatDateTime - ExecutionsPanel: timeAgo - UnifiedActivityPanel: formatTime - OverviewPanel: fmtDateTime Established pattern (stores/network.js, ReplayTimeline.vue). Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs: record #1474 scheduler Z-suffix + read-boundary under Invariant #16 Extend Architectural Invariant #16 (the #476 ISO-Z rule) with its write-side/ read-boundary cousin: the scheduler vendors src/scheduler/utils.py (Z-suffixed writes, naive-UTC tolerant reads); the leaking backend read boundaries normalize via parse_iso_timestamp; the 5 panels parse via parseUTC. Notes honestly that next_run_at stays mixed-format across writers (safe — Python-compared only) and that main.py SchedulerStatus.last_check is out of scope. Update the #1472 learnings entry: the scheduler DB mapper now returns naive-UTC (convert-then-strip, instant preserved), so the "schedules store AWARE next_run_at" premise is true of the backend writer, not the scheduler read path. Co-Authored-By: Claude Opus 4.8 <[email protected]> * docs(feature-flows): document #1474 scheduler Z-suffix timestamp contract Add a "Timestamp serialization contract (#1474)" subsection to scheduler-service.md (vendored utils.py, Z writes, naive-UTC tolerant reads, backend read-boundary + panel normalization, next_run_at mixed-format caveat) plus a Revision History row; add the index Recent Updates row. Co-Authored-By: Claude Opus 4.8 <[email protected]> * test(scheduler): cover _update_business_status validated_at Z-suffix (#1474) The service-layer VALIDATE-001 write path (service.py::_update_business_status) is the one #1474 timestamp write site outside database.py. Add sibling-path coverage per the incomplete-fix rule: assert validated_at is stored 'Z'-suffixed. Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]> * docs(user-docs): add Trinity FAQ — 264 grounded Q&As across 14 topic pages One page per topic (getting started, agents, chat/sessions, credentials, scheduling, collaboration, channels, MCP/API, operations, sharing, deployment, security, advanced, troubleshooting) plus a generated question index. Answers derived from user docs and verified against code; .claude pointer picks up the generate-user-docs FAQ step. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(user-docs): clarify PAT scope — git transport vs gh CLI/REST API authentication Co-Authored-By: Claude Fable 5 <[email protected]> * feat(helper-mcp): standalone Trinity docs Q&A MCP server (#1459) New src/helper-mcp/ package (@abilityai/trinity-docs-mcp): an npx-runnable stdio MCP server exposing the public ask-trinity docs Q&A endpoint (DOCS-QA-001) to any MCP client — no Trinity instance or API key required. - Tools: ask_trinity (multi-turn; detects the endpoint's silent session reset and warns when context was lost) + get_agent_requirements (agent guide fetched live from GitHub, quick-reference fallback) - Guards: 4k question cap, 50s abort timeout, no auto-retry, redirect:"error", non-JSON guard, structured error text; session_id handled as opaque string (live values exceed 2^53) - Deps: official @modelcontextprotocol/sdk + zod only; console.error-only logging (stdout is the JSON-RPC channel); Node >=18 launcher guard - Tests: 26 unit (mocked fetch) + pack-and-run stdio smoke test asserting JSON-RPC stdout purity; CI workflow helper-mcp-test.yml - Publish: publish-helper-mcp.yml (npm provenance; documented one-time manual first-publish bootstrap for trusted publishing) - Corpus: sync-docs-to-vertex.yml now also indexes the agent guide; feature flow corrected (user-docs/FAQ were already indexed) and extended with the verified endpoint contract (no citations field, silent session expiry) - Docs: requirements/mcp.md entry, README + user-docs install blocks, package README Fixes #1459 Co-Authored-By: Claude Fable 5 <[email protected]> * feat(agents): ephemeral ghost agents — budgeted hard-discard lifecycle + spawn provenance (trinity-enterprise#69) Disposable "ghost" agents: created with a hard budget (max_executions and/or TTL — expiry ALWAYS stamped, ceiling 24h default), volume-less (container writable layer; ghosts never recreate), hard-discarded at budget with no soft-delete/retention/name-reservation. Creation is entitlement-gated (ephemeral_agents; fail-closed — inert until the enterprise module registers); all lifecycle mechanics are edition-agnostic OSS primitives. Lifecycle: - Schema: 5 additive agent_ownership columns (is_ephemeral, budget, expiry, spawned_by_agent/key_id); dual-track migration (SQLite + Alembic 0016) - Creation gates (crud.py): entitlement 403 → ephemeral-caller refusal (chain-spawn kill) → per-parent spawn rate limit → TTL ceiling 400 → server-suffixed name (hex8) → atomic per-owner Redis quota (INCR-with-cap, NX reseed, DB fallback); ghosts skip volume/avatar/cred-injection/auto-sync, default max_parallel_tasks=1 - Budget: gate at the TOP of CapacityManager.acquire (terminal+active >= max or expired ⇒ EphemeralBudgetExhausted → 410 Gone / FAILED ephemeral_exhausted; covers every admission surface); post-CAS-win apply_result hook (backgrounded, fail-open) triggers discard at budget - Hard discard (services/agent_service/ephemeral.py): SETNX-locked, crash-convergent — intent marker → CAS-fail non-terminal rows (ghost_discarded) → force-remove container → clear Redis state BEFORE purge → cascade purge (executions KEEP) → audit. DELETE routes ghosts here before the container lookup (half-discarded state force-discardable) - GC (cleanup_service._sweep_ephemeral_agents): DB pass + Docker-as-truth orphan pass with 15-min newborn grace; capped per cycle Part 2 — spawn provenance + parent control: - Any agent-spawned creation persists spawned_by_agent/key_id and auto-grants the agent_permissions parent→child edge (created_by="spawn:{parent}") so a parent can immediately chat/list/info the child it spawned - BEHAVIOR CHANGE: agent-scoped keys may start/stop/delete ONLY agents they spawned (name AND key-id match; interim until #948); sharing, permission grants, rename, and credential ops are now human-only (403 for agent keys) - Ghost-key containment fence at the single auth entry point: a ghost's own key reaches only heartbeat/result-callback/reports/notifications/self-info Fleet hygiene: heartbeat watch + fleet health exclude ghosts; operator-queue polling keeps them; exec/cost stats stay inclusive; schedules on ghosts → 400; AgentStatus.ephemeral surfaced + GHOST badge. Tests: tests/unit/test_69_ephemeral_agents.py (40, db_harness real-engine) — accessors, facade delegations, acquire-gate matrix, key-fence matrix, Part 2 guard matrix, budget hook, discard idempotency/crash-convergence, atomic quota. Full unit suite verified; residual order-dependent flakes reproduced on clean dev (pre-existing, documented in learnings.md). Refs abilityai/trinity-enterprise#69 (Phase 0 record on the issue; closed manually at release — cross-repo keywords don't auto-close). Co-Authored-By: Claude Fable 5 <[email protected]> * test(69): patch _REAL_MODULES objects directly, never string targets — fixes seed-12345 order flake CI's regression-diff (head seed 12345) caught the discard test flaking: string-form monkeypatch targets resolve through sys.modules at PATCH time, which under some pytest-randomly orderings is a sibling test's leaked stale entry — the patch lands on the wrong module object while discard's call-time import (under the _own_real_modules pin) resolves the real one, so get_agent_container fell through to the real function (container=None, removal skipped). Same hazard removed from the gated_capacity and ghost_fence fixtures (bare fixture-time imports), and the audit assertion moved to an instance-method patch on the pinned singleton. Verified: full suite green under all three CI seeds (12345/67890/99999), 3775 passed each. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): string-target monkeypatch resolves stale sys.modules entries — patch by object Co-Authored-By: Claude Fable 5 <[email protected]> * fix(tests): pin real modules in TestAcquireCeilingClamp to kill sys.modules-leak flake (#1582) (#1584) The trio (test_acquire_clamps_above_ceiling / test_get_slot_state_clamps / test_get_all_states_clamps_each) failed order-dependently under pytest-randomly on clean dev (5/7 observed runs), passed in isolation and under -p no:randomly. Root cause (the #762/#1446 family): `_patch_ceiling` patched `get_max_parallel_tasks_ceiling` on the settings_service resolved via `from services import settings_service`, but `capacity_manager.acquire` imports `clamp_to_ceiling` at call time from `services.settings_service`. When a sibling's module-level stub (e.g. test_fleet_status_resilience installing a fresh `services` package with a real `__path__`) leaves two module objects for `services.settings_service` in play, the patch lands on one and `clamp_to_ceiling.__globals__` reads the other — the patch is silently never hit and the clamp assertion sees the unpatched (default) ceiling. Fix (the pattern documented for this leak family): - Capture the real `services` / `services.settings_service` / `services.capacity_manager` at collection time (this file sorts before every known leaker, so the import is leak-free). - Autouse fixture re-pins them into sys.modules per test (monkeypatch auto-restores) so the code-under-test's call-time import and the test's patch target resolve to the SAME object — last-write-wins over any leak. - `_patch_ceiling` now patches the captured real module object directly, never a bare re-import that could resolve a leaked stub. Verification: 25/25 in the file; 4/4 trio; 32 passed across 6 random seeds with test_fleet_status_resilience co-resident; 111 passed / 0 ceiling failures across 5 full-unit randomized seeds. Related to #1582 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * fix(reliability): decouple agent autonomy from the circuit breaker (#1557) (#1571) Disabling autonomy called force_circuit_dormant, parking the transport circuit breaker dormant. The execute_task gate consults that breaker for every trigger, so a healthy paused agent fast-failed all inbound chat (manual/Telegram/Slack/public) with "circuit breaker open — agent is unhealthy" — never contacted. Autonomy governs proactive work only; it now acts solely via set_schedule_enabled and never touches the breaker. #631's flood protection is unaffected (the breaker's own failure-driven dormant path + #1464 leader lock + #1121 monitoring-default-off). Also splits the misleading fast-fail message to name the breaker that fired (transport = unreachable, dispatch = auth-dead). Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]> * feat(voice): voice replies v2 — per-message capability, agent-level config, runtime ElevenLabs key (trinity-enterprise#117) (#1549) * feat(voice): voice replies v2 — per-message capability, agent-level config, runtime ElevenLabs key (trinity-enterprise#117) Rework outbound voice replies (ElevenLabs TTS) along three lines: 1. Voice is a per-message capability, not a hard rule. Channel replies are text by default; a reply becomes a voice note only when the agent explicitly calls the new send_voice_reply MCP tool during the turn. The backend resolves the channel destination from the execution (new schedule_executions.source_channel* columns), gates on TTS availability + agent enable + per-channel flag, wraps delivery in effect_guard (#1084), and reuses each channel's send primitive. The always-voice adapter path (_maybe_send_voice) is removed. 2. Voice config moves to agent Settings (enable + voice selection, one place); channel panels keep only a per-channel on/off flag (agent_ownership.tts_voice_{telegram,slack,whatsapp}_enabled, default ON). GET/PUT /api/agents/{name}/voice-replies extended with channels + effective voice. 3. ElevenLabs API key + platform default voice are runtime-configurable in admin Settings (GET/PUT /api/settings/elevenlabs), key stored AES-256-GCM encrypted and surfaced as configured:bool only; resolved via settings_service.get_elevenlabs_api_key() (stored setting -> env), no restart. New tts_available feature flag. Dual-track migrations (SQLite + Alembic 0015/0016). New send_voice_reply MCP tool (voice.ts) + POST /api/agents/{name}/voice-reply + voice_reply_service. Capability advertised in the platform prompt only when voice is enabled for the agent and the current channel's flag is on. OSS-core. Related to trinity-enterprise#117 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(voice): forward source_channel* through the db facade create_task_execution (trinity-enterprise#117) DatabaseManager.create_task_execution (the `db` facade wrapper) didn't forward the new source_channel / source_channel_chat_id / source_channel_thread kwargs to ScheduleOperations, so a channel-triggered task raised "unexpected keyword argument 'source_channel'" → 500. Add the passthrough. Related to trinity-enterprise#117 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(voice): allow send_voice_reply on channel turns via --allowedTools (trinity-enterprise#117) Channel turns run headless with a restricted `--allowedTools` (default WebSearch,WebFetch), which blocks every MCP tool — so an agent could not call send_voice_reply even when the capability was advertised in its prompt. When the voice capability is advertised for a channel turn, also append `mcp__trinity__send_voice_reply` to the channel allowed-tools list so the agent can actually act on it. Related to trinity-enterprise#117 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(migrations): stage the Alembic re-chain — 0017/0018 revision ids + down_revision onto 0016_agent_ownership_ephemeral The dev-merge commit renamed the files but the id/down_revision edits were left unstaged, leaving two heads off 0015 (pg-migrations 'Multiple head revisions' failure). --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]> * chore(dev-skills): bump .claude — /cso v1.1 Trinity-shape refresh Pointer bump to trinity-dev 2bdd362: fixes stale audit checks (setup-token removal ent#49, Redis ACL model, dual-track DB / two-network stack facts) and adds checks for post-skill surfaces (agent-key self-boundaries #307/#1083/#918, backend→agent auth #1159, webhook HMAC ent#77, vendored parity Invariant #5, enumeration uniformity #186, MCP description leak #846, backlog_metadata G-04 class, enterprise-docs-guard ent#45). Co-Authored-By: Claude Fable 5 <[email protected]> * docs(security): add CSO full-codebase audit report (2026-07-13) Full-codebase Chief Security Officer audit (all phases, daily 8/10 gate). No CRITICAL or exploitable-HIGH findings; prior CRITICAL (unauthenticated agent-server, #1159) and both HIGH supply-chain items resolved. Ceiling is MEDIUM: shared-user privilege tier, npm-ci lockfile bypass, unenforced CODEOWNERS, plaintext backlog_metadata, unpinned deps, enterprise-doc disclosure the guard can't see, python-multipart CVE. Two candidate findings (orb.js XSS, Slack code takeover) downgraded to LOW by adversarial verifiers. Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(portal): hide the platform Help widget on client-portal routes (#1588) The global "Trinity Help" chat widget is fixed at bottom-right (z-50) and overlapped the client portal chat composer's Send button. It's an operator/ platform-docs widget (gated on platform auth) and is meaningless on the standalone client portal, so gate it off there via a `hideHelpWidget` route meta on the two portal routes (`ClientPortalPublic` /portal and `EnterpriseClientPortal`). App.vue now renders it only when `authStore.isAuthenticated && !route.meta.hideHelpWidget`. Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * feat(portal): attach/upload files directly in the customer portal chat (ent#144) (#1587) A client can now attach files in the portal chat composer. The backend already had everything — `POST /client-portal/agents/{name}/documents` (writes to the client inbox), and `portal_chat`'s `_collect_inbox_for_turn` attaches inbox images as vision + lists documents — and the store already had `uploadDocument`/`fetchUploads`. The only missing piece was the composer UI. - `PortalChat.vue`: adds an `uploadDocument` prop and a paperclip attach control (hidden multi-file input). Picked files upload to the inbox immediately and render as chips with state (uploading / done / error) and a remove button. On send, the done attachments' (server-sanitized) filenames are appended as `[Attached: …]` so `_collect_inbox_for_turn` attaches images as vision THAT turn (it keys on the filename / image-intent) and lists documents. Files-only turns are allowed; send is blocked while an upload is in flight; a 25 MB client guard mirrors the backend cap (415/quota surfaced as a chip error). - `Portal.vue`: passes `:upload-document="(name, file) => store.uploadDocument(name, file)"`. - The attach control hides when no upload handler is wired (operator-preview `ClientPortal.vue` renderer), so nothing changes there. Public-repo (gated Vue) change only — no backend/submodule change (reuses the shipped enterprise endpoint + inbox consumption). Refs Abilityai/trinity-enterprise#144 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * fix(access): restore the per-recipient proactive-messaging toggle (#1577) (#1590) The `allow_proactive` toggle (the only UI for #321/#376) was silently dropped when the #1317 Access-tab redesign replaced the Sharing tab's Team Sharing rows — leaving no way to opt a recipient into proactive messages except a raw API call. Backend was fully intact; this is a UI-only restore. - `AccessPanel.vue`: each operator row gets a Proactive toggle bound to the `allow_proactive` the `/access` roster already returns (no extra fetch). On change it persists via the store and reflects the server's confirmed value, reverting + surfacing the error on failure (honest status, no optimistic-only flip). Pending invites are toggleable too (the flag rides on the `agent_sharing` row, which exists pre-resolution) with a tooltip on timing. A static note states the owner is always allowed (owners aren't in the roster, so there's no misleading owner toggle). - `stores/agents.js`: new `setProactive(name, email, allow)` → `PUT /api/agents/{name}/shares/proactive`. - `feature-flows/proactive-messaging.md`: updated — it still documented the removed SharingPanel markup/line numbers. - `tests/unit/test_1577_proactive_toggle_guard.py`: static regression guard (3) asserting the toggle + endpoint wiring survive future panel refactors (the frontend has no JS unit runner; a full render e2e is a `ui` follow-up). Related to #1577 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * feat(github): wire the managed agent PAT for the gh CLI + REST API, not just git (#1574) (#1591) Trinity injected the resolved GitHub PAT as GITHUB_PAT (authenticating git via the origin URL) but not the `gh` CLI or REST API, which read GH_TOKEN/GITHUB_TOKEN — so agents had to prefix every command with `GH_TOKEN="$GITHUB_PAT" gh …`, and `gh` wasn't even installed. This makes the SAME token cover both. No new token, endpoint, or UI — wiring only. Expose GH_TOKEN + GITHUB_TOKEN = the resolved PAT at every point GITHUB_PAT is set today, gated identically (only when a repo + PAT resolve — never an empty token that makes `gh` look logged-in but broken): - create (`crud.py`) and recreate (`lifecycle.py`) bake them into the container env; - the no-restart `.env` propagation (`github_pat_propagation_service._patch_env_github_pat`) now patches/adds all three keys, kept in sync; - `startup.sh` exports them from GITHUB_PAT so child processes (agent server, terminal shells) auto-authenticate — also covering older baked images that only carry GITHUB_PAT, without a recreate. Install the `gh` CLI in the agent base image (`Dockerfile`) from GitHub's official apt repo (base image must be rebuilt for existing agents to get the binary; the env vars are harmless on older images — git keeps working). Honest surfaces: the `set_agent_github_pat` MCP tool description and `docs/.../github-pat-setup.md` now state the managed token covers `gh`/REST too, keeping the scope caveat (wiring makes the token available; it can't grant scopes the token lacks). The credential sanitizer's `.*TOKEN.*`/`GITHUB_.*` patterns already mask GH_TOKEN/GITHUB_TOKEN (asserted). Tests: `tests/unit/test_1574_gh_token_wiring.py` — the .env patcher mirrors the PAT onto all three keys (replace-in-place / append, lookalike-key-safe, value mirrored); static guards that create/recreate/startup/Dockerfile each wire the gh vars; sanitizer covers the new vars. Related to #1574 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * fix(operator-queue): quarantine persistently-failing creates to stop the sync hot-loop (#1525) (#1589) The `created_at` KeyError in `create_item` was already made defensive on dev (#1426 — `.get(...) or utc_now_iso()` + `on_conflict_do_nothing`). This closes the remaining #1525 gap: the sync loop still re-attempted ANY failing create on every ~5s cycle forever (the row never persists → `operator_queue_item_exists` stays False → retry + ERROR-log indefinitely), so a DB error or any other persistent create failure — not just the fixed field case — still hot-loops. - `operator_queue_service._sync_agent`: track per-request consecutive create-failure counts; after `MAX_CREATE_ATTEMPTS` (3) skip that request (one WARN at the quarantine threshold instead of an unbounded ERROR stream). A create that later succeeds clears the counter; an in-memory safety valve caps the map so it can never grow without bound. - `db/operator_queue.create_item`: the last hard-indexed field (`id`) now uses `.get` and raises a clear `ValueError` (which the caller quarantines) instead of an opaque `KeyError`. Also hardened the WS-broadcast `item["id"]`. Tests: `test_1525_operator_queue_quarantine.py` (4, pure/mocked) — create is attempted at most the cap (not once per cycle), success clears the counter, a healthy request leaks no quarantine state, and the id-guard raises ValueError. Related to #1525 Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * feat(mcp): one-click Copy connection config on the Expose-via-MCP panel (#1575) (#1585) * feat(mcp): one-click Copy connection config on the Expose-via-MCP panel (#1575) Surfaces a ready-to-paste external-client config — with a least-privilege, agent-scoped, revocable API key already embedded — from the #846 exposure panel, so an external MCP client connects in one flow (enable → copy → paste). Direction: reuse the existing per-agent MCP connector (ent#46 → OSS #118) rather than mint a duplicate credential system. The connector already provides exactly the hard parts #1575 asks for — a scoped `scope='connector'` key, owner-selected playbooks exposed as tools, and `build_snippets` producing per-client `.mcp.json`/CLI blocks with the key embedded — but only on the Sharing tab. This wires that capability onto `McpExposedPanel.vue` (Settings → Expose via MCP), shown when `mcp_exposed` is on. - Frontend-only, no new backend endpoint/key type: reuses `GET/POST/DELETE /api/agents/{name}/connector[/key]` (owner-only, `OwnedAgentByName`) + `ExposedToolsPanel` for the playbook allow-list. - One-click "Copy connection config": mints (or regenerates) the scoped key and copies the `.mcp.json` in a single action via the robust `utils/clipboard` helper — the only moment the live secret exists. - Copy-once integrity: with an existing key, "Copy config" copies the placeholder config and offers "Regenerate & copy" for a fresh live key; "Revoke" severs any connected client. Key already lists in Settings → MCP Keys. - Safe default: the section only appears once the agent is MCP-exposed; a plain warning marks the config as a live secret. Docs: mcp-connector.md gains the 2nd-surface row; architecture #846 block notes the connect surface. Verification: `McpExposedPanel.vue` compiles clean via @vue/compiler-sfc (full `vite build` blocked by a pre-existing unrelated missing `mermaid` dep in AgentWorkspace.vue). Live click-through / ui-labeled e2e needs the running frontend+backend stack (not up locally). Not changed (documented scope): a 422 on an invalid playbook name — the picker only offers live user_invocable playbooks, so the invalid path is UI-unreachable; left to the connector's existing read-time filter. Related to #1575 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(mcp): flash a "Copied!" animation on the connection-config copy buttons (#1575) Adds an inline copied-state affordance to the connect-config copy actions (Copy connection config / Copy config / per-client snippet Copy): on a successful clipboard write the button swaps to a green "✓ Copied!" with a scale-pop checkmark for ~1.6s, then reverts. One shared timer (cleared on unmount); only fires when the copy actually succeeded; honors prefers-reduced-motion. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(mcp): make the copied state transform the button itself (#1575) Stronger, unmissable copy feedback: on a successful copy the primary "Copy connection config" button fills solid success-green, gains a ring + glow, bumps to a bolder "Copied to clipboard!" with a larger checkmark, and plays a one-shot pop + outward ring-pulse (copied-btn-flash) before settling. The existing-key "Copy config" button gets the same solid-green ring treatment. Reverts after ~1.6s; honors prefers-reduced-motion. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * feat(mcp): animate the connector snippet Copy buttons too (#1575) The MCP connector panel (Sharing tab, ConnectorChannelPanel) is the other surface that shows per-client copy snippets; its plain "Copy" links gave no feedback. Give them the same copied-state treatment as the exposure panel: on a successful copy the button flashes solid success-green with a ring + pop + "Copied!" checkmark, reverting after ~1.6s (honors reduced-motion). Also route its copy() through the robust utils/clipboard helper instead of raw navigator.clipboard. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> * fix(tests): conftest no longer deletes real agents named test-* (#1558) (#1586) * fix(tests): stop conftest from deleting real agents named test-* (#1558) The session-scoped `api_client` fixture deleted EVERY agent whose name began with `test-` on whatever `TRINITY_API_URL` pointed at — silent, unprompted data loss that destroyed a developer's real `test-agent-2` (bound Telegram bot, chat history, GitHub sync). Any `test-*` agent on a staging/prod instance was one test invocation from deletion. Fix — fail-closed on every axis: - Dedicated prefix: the suite now names every agent it creates `pytest-ephemeral-*` (a namespace no human uses), never the broad `test-`. Renamed all conftest agent generators (test_agent_name, module_agent_name, stopped_agent, shared_agent). - Session registry: created names are registered (`register_created_agent`) and reclaimed by name at session end (belt over each fixture's own teardown). - Startup leftover-sweep is now OPT-IN (`TRINITY_TEST_CLEANUP_SWEEP`), refuses any non-localhost target (`is_local_target`), and only removes provably suite-owned names (`select_sweepable_agents` — pure, fail-closed). Default: no sweep at all. - `cleanup_test_agent(require_suite_owned=True)` refuses (no stop/delete call) a name the session can't prove it created — used by every sweep path. - Docstring + tests/README now state plainly that the suite mutates the target instance and must point at localhost. …
AndriiPasternak31
added a commit
that referenced
this pull request
Jul 28, 2026
…talog
One template whose `credentials:` — or `credentials.mcp_servers` — was a list,
a string, or **null** raised an uncaught AttributeError out of
`_build_local_template` -> `get_local_templates()` -> `GET /api/templates`:
HTTP 500 with ZERO templates listed. One bad template hid every good one.
The `github:` builder was worse: no `isinstance` guard at all on untrusted repo
metadata (`_fetch_template_yaml` returns `safe_load(...) or {}`, and a top-level
list is truthy). Deeply nested YAML escaped the parse handler entirely as
`RecursionError` — a `RuntimeError`, not a `yaml.YAMLError`.
Worse than the crash because it was silent: `env_file: "OPENAI_API_KEY"` — an
ordinary typo, the list dash forgotten — was iterated character by character
into the generated `.env`, emitting fifteen single-letter variables, never
writing the real credential, with no error, no warning and no crash. The agent
booted and its MCP server failed at first use with nothing pointing at the
cause.
And `credentials.config_files[].path` was joined onto the staging directory and
opened for write with no normalization, so an absolute path or a `..` escape
was an arbitrary-file-write primitive — reachable by any authenticated user,
since `deploy_local_agent_logic` accepts an uploaded template archive.
Four tolerant readers in `template_service.py` are now the only way into the
block, with two deliberately opposite contracts:
* Read paths never raise. The catalog degrades the derived field to empty,
attaches `credential_errors` to the entry, logs one WARNING naming the
template id — and the template STILL LISTS. `get_local_templates` also fences
each per-template build, so a future unguarded field cannot regress the
property the readers buy.
* The write path fails loud. `generate_credential_files` validates first and
raises the HTTP-free `CredentialDeclarationError`, which its only caller maps
1:1 to 400 `INVALID_CREDENTIAL_DECLARATION` (Invariant #1: services hold no
HTTP concerns). It is called before the docker try/except, so the 400 is not
flattened to a 500.
`config_files[].path` is rejected at the parse boundary AND re-checked at the
write sink (`crud._safe_cred_file_path` -> 400 `INVALID_CREDENTIAL_FILE_PATH`),
using the same resolve + `is_relative_to` CodeQL barrier as
`_safe_local_template_path`.
Absent / null / `{}` all stay a valid zero-credential contract — the ent#124
starter trio ships exactly that, and a commented-out block must not acquire a
spurious warning.
`credentials.env_file` stays a names-only list. The enriched per-variable
declaration lands under its own top-level key (PR-B) precisely so an older
Trinity reading a newer template is structurally untouched.
Tests: `test_ent128a_catalog_resilience.py` — 33 pass here, 31 fail on
`origin/dev`, the two headline ones with the exact bug signatures
(`AttributeError: 'list' object has no attribute 'get'` and the literal
`O=\nP=\nE=\nN=` output). Includes a parity test so a malformed BUNDLED template
fails CI instead of a user's fresh install.
No DB change, so the dual-track migration rule (#9) does not apply.
PR-A of trinity-enterprise#128 (AC #5). PR-B — the enriched declaration schema —
re-gates after this merges.
Refs Abilityai/trinity-enterprise#128
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Jul 29, 2026
…1804) (#1863) * docs(requirements): CAS-won terminal owns the paired activity close (#1804) Trinity Rule #1 — requirements before implementation. scheduling.md §10.15: the terminal-write contract now includes closing the paired agent_activities dispatch row. Records the one-owner helper, the activity CAS lattice (mirrors the execution predicate), the widened lookup, the bulk/per-row split by cardinality, and the terminal-write-anchored parity guard. infrastructure.md §12.9 (CLEANUP-001): the 120-minute activity sweep is demoted to a backstop for the unclaimed, and moves after the stale-slot reaper so it can no longer beat a legitimate closer within one cycle. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(activities): make the activity close a lattice CAS with a tri-state outcome (#1804) T1+T2. The db-layer spine for the #1804 contract. - ActivityCloseOutcome (UPDATED / ALREADY_CLOSED / NOT_FOUND). One bool cannot answer both "did this row exist" (routers/internal.py 404s) and "did anything change" (activity_service broadcasts); once idempotent no-op closes are a designed outcome the two answers diverge routinely. - complete_activity becomes an atomic CAS on _close_predicate, which MIRRORS the execution-row predicate in db/schedules/executions.py: incoming COMPLETED -> activity_state != 'cancelled' (an authoritative close may upgrade a provisional FAILED — the #1083 late-SUCCESS-after-lease-expiry path); incoming CANCELLED/FAILED -> activity_state = 'started' (nothing overwrites an authoritative close, so a double close cannot clobber completed_at / duration_ms / error). The lattice diagram is inline over the predicate. - get_open_activity_id_for_execution takes include_failed so the LOOKUP agrees with the write — a lookup narrower than the CAS makes the widened predicate inert. Ordering prefers still-'started' rows. - close_open_activities_for_executions: set-wise bulk close for the watchdog sweeps, one transaction, no per-row WS, chunked at _SQLITE_MAX_IN_VARS. No schema change, no migration (Rule #9 not triggered). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(activities): add close_execution_activity, the single owner of the close contract (#1804) T3. A leaf helper on activity_service (imports only models/database/db.activities — no services.* edge, so no cycle) that every CAS-won terminal writer calls. - Reuses models.activity_state_for_terminal (#1332) — no second mapping. - Lattice-aware lookup: an authoritative terminal (SUCCESS/CANCELLED) searches started|failed so it can upgrade a provisional FAILED; a provisional terminal searches started only. Callers pass a terminal status and stay ignorant of it. - Delegates to complete_activity, so the agent_activity WebSocket broadcast and subscriber notify survive (what a db-layer close would have lost). - Broadcasts only on ActivityCloseOutcome.UPDATED; ALREADY_CLOSED is a designed no-op and must not emit an event claiming the activity just closed. - complete_activity's bool now means "exists and closed" — only NOT_FOUND is False, so routers/internal.py keeps its 404 semantics and an idempotent re-close does not start 404ing the scheduler. - spawn_close_execution_activity: sync fire-and-forget wrapper for the synchronous pull sink, mirroring spawn_task_terminal_event (strong task ref, fail-open with no running loop). Fail-open throughout: the close runs after a committed terminal write. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(execution): close the paired activity at every CAS-won terminal writer (#1804) T4-T8. Wires the eight terminal writers onto the single owner. task_execution_service: - _write_terminal_and_gate gains the missing CAS-LOSS branch (the SUCCESS applier has had one since #1332): re-read the row and close the activity in the terminal that actually stands. `activity_status` leaves the signature — it is derived from `status`, so the two can no longer drift. - the asyncio.CancelledError shutdown handler now closes too. #767 closed the execution record here so the sweep would not inflate ITS duration but left the activity for the 120-minute backstop to inflate instead; worse, the row is `failed`, so startup recovery (which scans `running`) skips it forever. routers/internal: the second shutdown writer, same shape (no activity_id in scope — the helper looks it up). cleanup_service: - watchdog and startup _recover_execution close on the CAS-won branch. The startup one was DISCARDING its CAS bool (returned True unconditionally absent an exception); it is now captured, gates the close, and is returned. - _close_bulk_swept_activities: a SIBLING of _emit_bulk_terminal_events, never folded into it — that method short-circuits when nobody subscribes, which would skip the close on every install with no event subscribers. Driven by the collect_failed rows #1714 already collects; one transaction, no per-row WS. - _sweep_stale_activities moves AFTER _sweep_stale_slots: it ran one line before the reaper that legitimately closes activities, so within a single cycle the 120-minute fabricator could beat a real closer. - _close_reaped_activity / _close_stale_slot_activity delegate to the helper. - CleanupReport.activities_closed_on_recovery (not summed into `total` — it is an observability counter over work already counted). pull_coordination_service: closes on the CAS-won branch via the sync spawn wrapper. lease_reaper_service: requeued_execution_ids, closed CANCELLED — a superseded attempt is not a failure, and the re-queue preserves execution_id so the next delivery opens a second activity against the same row. chat_execution_service: terminate folds onto the helper (it was the fifth hand-rolled copy of the idiom, and a copy is invisible to the parity guard). Behaviour unchanged — R4. db/schedules/cleanup: mark_no_session_executions_failed returns the CAS-WON count, not the candidate count (its sibling already did). report. no_session_executions was over-reporting; deliberate, visible value change. Tests updated where a mock encoded the old call surface; one behavioural assertion inverted on purpose (test_terminal_write_cas_gate: a lost CAS now closes the activity in the persisted state instead of leaving it open). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test(1804): R1-R5 regressions, the two-table chain test, and the parity guard T9+T10. test_1804_recovery_closes_activity.py — db layer against the real schema (db_harness) + service + every wired writer: R1 a FAILED activity upgrades to COMPLETED, through the lookup (the pairing that keeps the fix from being inert) R3 an already-closed close never touches completed_at/duration_ms/error R2 _write_terminal_and_gate's CAS-loss closes with the PERSISTED state R5 both backend-shutdown CancelledError handlers close their activity plus: broadcast on UPDATED only, watchdog/startup gating on the CAS bool, the bulk close running with zero event subscribers (the #1714 gate scopes the event, never the close), the pull sink on applied-but-not-replayed/ conflict, and the lease reaper's requeued_execution_ids. test_1804_terminal_activity_chain.py — the two CAS predicates live in two different tables; mocks encode what the author believed, so these run the real statements and assert the tables agree. Includes the late-SUCCESS upgrade end to end and the cancel-is-never-overwritten mirror image. test_1804_terminal_activity_parity.py — anchored on terminal WRITES, not on completion-event emission. The emit set is a strict subset (both shutdown writers emit nothing), which is exactly how they hid from review. Explicit allowlist, each entry justified by lifecycle position, plus a self-test that the guard actually fires and a staleness check on the allowlist. R4 (terminate byte-identical) lives in test_1332, which the previous commit updated to the new call surface. tests/lint_sys_modules.py: clean, no new violations. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(architecture): record the terminal-activity close contract (#1804) New canonical block "Terminal-Activity Close Contract (#1804)" — one home for the feature, pointers from the places that used to imply the old model: - Fire-and-Forget Dispatch (#1083): the close is a property of winning the CAS, not of holding the activity_id local; apply_result is one writer among eight. - Task Completion Events (#1578): the emit set is NOT the close set — both shutdown handlers write a terminal and emit nothing, which is why the parity guard is anchored on terminal writes. - Background Services / Cleanup Service: the recovery closes, activities_closed_on_recovery, and the backstop moving last in the cycle. - services catalog: activity_service owns the closer. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(feature-flows): the terminal-activity close contract (#1804) /sync-feature-flows. activity-stream.md — new "The Close Contract (#1804)" section: the owner (close_execution_activity + the sync spawn wrapper), the state lattice with the side-by-side execution/activity diagram and why the lookup must agree with the CAS, the split by cardinality, the full writer table, and the demotion of the 120-minute backstop. task-execution-service.md — the _write_terminal_and_gate lost-CAS branch (and the dropped activity_status param), the backend-shutdown close, and a row in the Activity Tracking table pointing at the contract. dashboard-timeline-view.md — why the amber bar used to lie, and that no frontend change was needed: ReplayTimeline was reading a lying database. feature-flows.md — Recent Updates row. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(1804): make the close outcome identity-stable and never downgrade a recovery Two real defects the full-suite run surfaced (both green in isolation, red at 5,100 tests — the pollution class the dossier warned about). 1. ActivityCloseOutcome moves db/activities.py -> models.py. Callers compare it by `is`, and db_harness evicts `db.activities` from sys.modules per test. Any test that imported services.activity_service BEFORE an eviction held one enum class while a later `from db.activities import ...` got a different one, so every identity check silently went False. models is the leaf everything imports and nothing re-imports, so the object stays the same one — and it now sits beside ActivityState/TaskExecutionStatus, where a shared db↔service contract type belongs. Re-exported through db.activities. 2. Both _recover_execution closes get their own try/except. The terminal write and the capacity release have already succeeded at that point; letting a close failure propagate flipped a recovered row into the `errors` bucket and would make the watchdog retry a row it had already recovered. Fail-open is the rule for everything after a committed terminal — this was the one place I left it implicit. Full unit suite: 5136 passed, 14 skipped, 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(1804): the #1083 result callback must look up failed activities too Self-review catch. The callback endpoint IS the late-SUCCESS path — the one the lattice was widened for. A lease reaper that beat the callback has already FAILED the row and closed the activity FAILED; the execution CAS deliberately lets a genuine late SUCCESS correct the row ("a FAILED row falls through so a late SUCCESS can still overwrite a reaper LEASE_EXPIRED"). With a started-only lookup the callback passed activity_id=None, apply_result closed nothing, and the pair settled at execution=success, activity=failed — permanently. That is #1804 inverted, on the exact path the upgrade exists for. Harmless for a FAILED callback: the close CAS refuses to overwrite an already-closed activity. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(activity-stream): note the callback's include_failed lookup (#1804) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * test: confine the git-reset loader's sys.modules stubs to their own test `_load_git_service` installs Mocks under the real names `database`, `services.docker_service` and `services.activity_service`. It deliberately leaves them in `sys.modules` after the loader returns (the reset path imports `activity_service` lazily at call time) — but nothing put them back afterwards either, so the Mocks stayed installed for the rest of the session. That is a silent, ordering-dependent landmine for any later test that lazily imports one of those names. #1804 makes `cleanup_service._close_stale_slot_activity` delegate to `activity_service.close_execution_activity`; with this file running first, `test_1083_lease_reaper.py::test_swallows_errors` awaited the leaked Mock and died with `TypeError: object Mock can't be used in 'await' expression` — a real red under CI's pytest-randomly seeds, in a test unrelated to git reset. Adds the lint-recognised `_STUBBED_MODULE_NAMES` + `_restore_sys_modules` autouse pair, also restoring `services.git_service*` (the loader force-reimports it against the Mocks, so leaving that behind poisons later importers too). `tests/lint_sys_modules.py` drops this file from 9 violations to 0. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(1804): close the reflexive COMPLETED edge and make CAS-loss labels honest Three review findings on the terminal-activity close contract. 1. The close lattice inherited the upstream's permissive edge (the bug it exists to prevent). `_close_predicate` was specified as an authority ORDERING (`started < failed < {completed, cancelled}`) but implemented as an EXCLUSION copied literally from the execution CAS: `!= 'cancelled'`. Those two disagree exactly on the reflexive case — `!= 'cancelled'` matches `'completed'`, so a second COMPLETED close was permitted and re-dated `completed_at`/`duration_ms`/`error`. Executed against the real path, a 15-minute activity (`duration_ms=900000`) re-closed COMPLETED became ~9h: the exact fabricated-duration symptom #1804 exists to eliminate, arriving through #1804's own fix. It is reachable from `_write_terminal_and_gate`'s lost-CAS branch, which passes an explicit `activity_id` — so the narrower `started|failed` lookup cannot shield it. The literal copy was faithful: `update_execution_status`' SUCCESS predicate really is `!= CANCELLED` and really does admit `success -> success`. The execution row survives that edge only because an upstream guard (the #1083 callback's authoritative-terminal replay short-circuit) stops the duplicate before it reaches the CAS — a protection the activity's new call sites do not have. The predicate now states the ordering literally, `IN ('started','failed')`, and the branch's five lattice tests gain the `X -> X` case they all skipped because it looks like a no-op. 2. A CAS loss to a *successful* row stamped "superseded by ..." onto a clean success, and rendered the enum repr while doing it. `error` is now None on an authoritative SUCCESS close (a non-NULL `error` on a `completed` activity reads as a problem in every activity-derived view — the rule the shipped terminate path already follows), and the label uses `.value`, since `f"{TaskExecutionStatus.FAILED}"` renders as `TaskExecutionStatus.FAILED` on 3.11+ — the `str, Enum` footgun #1578 already paid for. 3. `_recover_execution` returning the terminal CAS bool (it must, to gate the close) changed what a False MEANS to `recover_orphaned_executions`, which counted every False as `errors`. A lost CAS is RELIABILITY-005's guarded writer working as designed — a real completion landed during restart — so folding it into `errors` makes a healthy restart race read as a failing one, and would have made this fix look like it introduced failures. False is now partitioned: genuine exceptions self-count into `stats["errors"]`, the remainder is reported as `cas_lost`. Docs updated in lockstep (architecture.md, requirements/scheduling.md, feature-flows/activity-stream.md) to state the COMPLETED arm as deliberately tighter than the execution CAS rather than a literal mirror, plus a learnings.md entry on inheriting a permissive edge when mirroring a predicate. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Eugene Vyborov <[email protected]>
AndriiPasternak31
added a commit
that referenced
this pull request
Jul 29, 2026
…talog
One template whose `credentials:` — or `credentials.mcp_servers` — was a list,
a string, or **null** raised an uncaught AttributeError out of
`_build_local_template` -> `get_local_templates()` -> `GET /api/templates`:
HTTP 500 with ZERO templates listed. One bad template hid every good one.
The `github:` builder was worse: no `isinstance` guard at all on untrusted repo
metadata (`_fetch_template_yaml` returns `safe_load(...) or {}`, and a top-level
list is truthy). Deeply nested YAML escaped the parse handler entirely as
`RecursionError` — a `RuntimeError`, not a `yaml.YAMLError`.
Worse than the crash because it was silent: `env_file: "OPENAI_API_KEY"` — an
ordinary typo, the list dash forgotten — was iterated character by character
into the generated `.env`, emitting fifteen single-letter variables, never
writing the real credential, with no error, no warning and no crash. The agent
booted and its MCP server failed at first use with nothing pointing at the
cause.
And `credentials.config_files[].path` was joined onto the staging directory and
opened for write with no normalization, so an absolute path or a `..` escape
was an arbitrary-file-write primitive — reachable by any authenticated user,
since `deploy_local_agent_logic` accepts an uploaded template archive.
Four tolerant readers in `template_service.py` are now the only way into the
block, with two deliberately opposite contracts:
* Read paths never raise. The catalog degrades the derived field to empty,
attaches `credential_errors` to the entry, logs one WARNING naming the
template id — and the template STILL LISTS. `get_local_templates` also fences
each per-template build, so a future unguarded field cannot regress the
property the readers buy.
* The write path fails loud. `generate_credential_files` validates first and
raises the HTTP-free `CredentialDeclarationError`, which its only caller maps
1:1 to 400 `INVALID_CREDENTIAL_DECLARATION` (Invariant #1: services hold no
HTTP concerns). It is called before the docker try/except, so the 400 is not
flattened to a 500.
`config_files[].path` is rejected at the parse boundary AND re-checked at the
write sink (`crud._safe_cred_file_path` -> 400 `INVALID_CREDENTIAL_FILE_PATH`),
using the same resolve + `is_relative_to` CodeQL barrier as
`_safe_local_template_path`.
Absent / null / `{}` all stay a valid zero-credential contract — the ent#124
starter trio ships exactly that, and a commented-out block must not acquire a
spurious warning.
`credentials.env_file` stays a names-only list. The enriched per-variable
declaration lands under its own top-level key (PR-B) precisely so an older
Trinity reading a newer template is structurally untouched.
Tests: `test_ent128a_catalog_resilience.py` — 33 pass here, 31 fail on
`origin/dev`, the two headline ones with the exact bug signatures
(`AttributeError: 'list' object has no attribute 'get'` and the literal
`O=\nP=\nE=\nN=` output). Includes a parity test so a malformed BUNDLED template
fails CI instead of a user's fresh install.
No DB change, so the dual-track migration rule (#9) does not apply.
PR-A of trinity-enterprise#128 (AC #5). PR-B — the enriched declaration schema —
re-gates after this merges.
Refs Abilityai/trinity-enterprise#128
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Jul 30, 2026
…talog (ent#128 PR-A) (#1835) * fix(templates): stop a malformed `credentials:` block emptying the catalog One template whose `credentials:` — or `credentials.mcp_servers` — was a list, a string, or **null** raised an uncaught AttributeError out of `_build_local_template` -> `get_local_templates()` -> `GET /api/templates`: HTTP 500 with ZERO templates listed. One bad template hid every good one. The `github:` builder was worse: no `isinstance` guard at all on untrusted repo metadata (`_fetch_template_yaml` returns `safe_load(...) or {}`, and a top-level list is truthy). Deeply nested YAML escaped the parse handler entirely as `RecursionError` — a `RuntimeError`, not a `yaml.YAMLError`. Worse than the crash because it was silent: `env_file: "OPENAI_API_KEY"` — an ordinary typo, the list dash forgotten — was iterated character by character into the generated `.env`, emitting fifteen single-letter variables, never writing the real credential, with no error, no warning and no crash. The agent booted and its MCP server failed at first use with nothing pointing at the cause. And `credentials.config_files[].path` was joined onto the staging directory and opened for write with no normalization, so an absolute path or a `..` escape was an arbitrary-file-write primitive — reachable by any authenticated user, since `deploy_local_agent_logic` accepts an uploaded template archive. Four tolerant readers in `template_service.py` are now the only way into the block, with two deliberately opposite contracts: * Read paths never raise. The catalog degrades the derived field to empty, attaches `credential_errors` to the entry, logs one WARNING naming the template id — and the template STILL LISTS. `get_local_templates` also fences each per-template build, so a future unguarded field cannot regress the property the readers buy. * The write path fails loud. `generate_credential_files` validates first and raises the HTTP-free `CredentialDeclarationError`, which its only caller maps 1:1 to 400 `INVALID_CREDENTIAL_DECLARATION` (Invariant #1: services hold no HTTP concerns). It is called before the docker try/except, so the 400 is not flattened to a 500. `config_files[].path` is rejected at the parse boundary AND re-checked at the write sink (`crud._safe_cred_file_path` -> 400 `INVALID_CREDENTIAL_FILE_PATH`), using the same resolve + `is_relative_to` CodeQL barrier as `_safe_local_template_path`. Absent / null / `{}` all stay a valid zero-credential contract — the ent#124 starter trio ships exactly that, and a commented-out block must not acquire a spurious warning. `credentials.env_file` stays a names-only list. The enriched per-variable declaration lands under its own top-level key (PR-B) precisely so an older Trinity reading a newer template is structurally untouched. Tests: `test_ent128a_catalog_resilience.py` — 33 pass here, 31 fail on `origin/dev`, the two headline ones with the exact bug signatures (`AttributeError: 'list' object has no attribute 'get'` and the literal `O=\nP=\nE=\nN=` output). Includes a parity test so a malformed BUNDLED template fails CI instead of a user's fresh install. No DB change, so the dual-track migration rule (#9) does not apply. PR-A of trinity-enterprise#128 (AC #5). PR-B — the enriched declaration schema — re-gates after this merges. Refs Abilityai/trinity-enterprise#128 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(templates): make the credential-file path guard a two-step barrier CodeQL flagged `_safe_cred_file_path` with two HIGH `py/path-injection` alerts, on the join itself and on the containment check. It was right to: the helper had only step 2 of the pattern (resolve + `is_relative_to`), and CodeQL does not treat that alone as a barrier — the sibling `_safe_local_template_path` clears the same query because it allowlists the RAW string first. Add that step 1 here too: reject empty, absolute, `..`-bearing, and anything outside `[A-Za-z0-9._/-]` before the value ever reaches the join, then keep the resolve + containment as step 2. `_CRED_FILE_PATH_RE` permits `/` (unlike `_LOCAL_TEMPLATE_NAME_RE`) because this is a relative *path*, not a single slug. Not defensive padding for a scanner — the two-step shape is what makes the guard legible to a reader as well, and it is the established pattern in this file. Test extends to the allowlist rejections (empty, leading dash, space, semicolon) alongside the traversal cases. Refs Abilityai/trinity-enterprise#128 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Jul 31, 2026
… 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]>
vybe
added a commit
that referenced
this pull request
Sep 22, 2026
…, one stale rule, get_metrics, declared-metric tiles, metric: widget binding, D-010 (Abilityai/trinity-enterprise#479) (#2951) * feat(metrics): declared-metric registry — template.yaml metrics: reader, metric_definitions store, reconcile on create/pull/sync/start, definitions API, compat D-009 (Abilityai/trinity-enterprise#477) * fix(metrics): re-chain the registry migration to 0066 after dev's 0065, make the declared-metrics reader total on non-string keys, register the J12 harness (Abilityai/trinity-enterprise#477) * fix(metrics): a refused metric type change keeps status_values_json (Abilityai/trinity-enterprise#477) `reconcile` copies the whole declaration payload over an existing row, so a re-declaration whose `type` was REFUSED still overwrote `status_values_json` from the refused entry. Re-declaring a `status` metric as `counter` therefore kept the stored type `status` while nulling its declared value domain, leaving a status row that nothing can interpret — and ent#478's point validator would have had to widen to "accept any string" to cope with it. The stored type stands, so the column that exists only for that type stands with it. One line in the refusal branch; `test_a_refused_type_change_keeps_the_ declared_status_values` goes red without it (verified by removing the line). Found by the ent#478 plan review (TD-15); landed here because 478 stacks on this branch. * feat(metrics): metric_points schema, store, validator and wire model (Abilityai/trinity-enterprise#478) Checkpoint A of ent#478 — everything below the route. The push path itself (route, settings, sweep, MCP tool) lands in the following commits. **Schema, all four tracks** (Invariant #9): `db/schema.py` DDL + three indexes, `db/tables.py` Core metadata, the SQLite `metric_points_table` migration, and Alembic `0067_metric_points <- 0066_metric_definitions`. No surrogate id: the primary key IS the point identity `(agent_name, ts, idempotency_key)`, which keeps the eventual partition key inside the only unique constraint so ent#80 can partition by month without a table rebuild. `dims` is JSONB on PostgreSQL and TEXT on SQLite through a new per-column marker rule — `dims TEXT /* pg:JSONB */` in the shared DDL, rewritten by `to_postgres_table_ddl`. One rule converges the fresh-PG path (`0001_baseline` replays that DDL), the upgrade path and SQLite, with no `ALTER ... USING` repeated in two places. `value_numeric` is `DOUBLE PRECISION`, not `REAL`: `REAL` is float4 on PostgreSQL and would round a revenue metric's cents. **Store** (`db/metric_points.py`): `insert_points` counts with `.returning` rather than `rowcount`, which is not a portable count of what survived a multi-VALUES `DO NOTHING`. The cap count and the sweep's candidate count are both LIMIT-bounded, and the count and the prune are built from ONE predicate (the ent#433 rule). The prune chunks by `ts` RANGE — there are no ids — taking boundary ties with it so a busy millisecond cannot wedge the loop, and is bounded to 20 chunks per call so a narrowed window drains over several cleanup cycles instead of blocking the others for one very long one (TD-14). **Validator** (`services/metric_points_service.py`): a pure leaf over the ent#477 definitions — no DB, no settings, no HTTP. Points validate against the STORED type, never `type_conflict` (T5), with a hint naming the author-side rename. `ts` must match the RFC 3339 shape and is range-checked as a DATETIME, not a string: `0999-01-01` normalises to `999-01-01T...`, which sorts ABOVE every real timestamp and would head the `ts DESC` read index forever. Below the retention window is refused too, so agent input cannot steer the retention guard into permanent refusal. Messages echo codes, indices and dimension KEYS only — this output lands in an LLM's context and in logs. **Model** (`models.py`): the frozen `MetricPointIn` wire shape ent#479 reads back and #536 binds a canvas chart to. A before-validator rejects `bool` (an `int` subclass Pydantic was measured to coerce to `1.0`) and non-finite floats (SQLite stores NaN as NULL, PostgreSQL as NaN — one batch, two meanings). **Cascade** (`db/agent_cleanup.py`): one CASCADE ref. The identity hash excludes `agent_name`, so a rename re-keys losslessly. Tests: 59 validation/model + 27 store (SQLite; the JSONB column-type assertion is PostgreSQL-marked so it actually runs on the PG leg), including a negative control showing what `test_schema_parity` structurally cannot see and a facade signature-parity check. * feat(metrics): record_metrics route, Settings knobs, retention sweep and quota audit (Abilityai/trinity-enterprise#478) Checkpoint B — the push path itself. The MCP tool and the docs follow. **Route** `POST /api/agents/{name}/metrics/points` in its own module (router → service → db, Invariant #1), registered before the agents router's single-segment routes. Gate order is load-bearing: self-gate (access-first, so the answer cannot vary by whether a metric exists) → rate limit → size → batch idempotency → definitions → validate → daily cap → insert. Two idempotency layers. The ROW key is the invariant and needs nothing; the BATCH key gives Invariant #18's "returns the first result". Where no client key is supplied but `execution_id` resolves to this agent, the batch key is derived from the execution — which is what dedups a batch of `ts`-less points on a re-delivered turn, since those would otherwise take a fresh server-now timestamp and hash to something new. With neither, a retry is a new observation, stated rather than papered over with a body hash (a body hash would drop the legitimate "same numbers an hour later"). Every non-2xx exit past the claim goes through one `_reject` choke point that releases it first: a 422 that wedged the caller's key would turn one malformed batch into a day of silently dropped metrics. DB failures are CLASSIFIED — connectivity is 503 + `Retry-After`, a content error is a non-retryable 500, because telling an agent to retry a batch the database will reject identically forever is how a permanent error becomes an infinite loop. **Settings** (C6): `metrics_retention_days` (365, a retention key with its own guard site) and `metrics_daily_point_cap` (100000, `0` = unlimited), with a NEW env tier — `ENV_BACKED_OPS_KEYS` + `config.resolve_ops_default` + `settings_service.resolve_ops_setting`, opt-in per key so the ~20 keys the retention endpoint documents as env-less keep their precedence. One semantic: env is a live fallback, and the #2085 boot seeder SKIPS an env-set key rather than freezing its value into a row. `get_ops_setting`, the boot log, `GET /api/settings/retention` and the definitions `policy` all resolve through the one chain and report which tier answered. The ent#297 redirect is generalised (E4): the unvalidated catch-all PUT now refuses EVERY key that has validation, not a hand-maintained subset — the cap was reachable there, where garbage stores verbatim and then 500s the reader. The cap reader coerces garbage to the default, never to `0`. **Sweep** (C7) beside the sibling row sweeps, with two deliberate differences: `floor=FLOOR_METRIC_POINTS` (100k, one agent-day at the cap), because at the default 1000 any real ingest rate refuses every cycle and then sits blocked behind single-use acks; and the ack is consumed only once the REMAINING backlog is under the floor, since the prune is bounded per call. The counter is added to all three `CleanupReport` sums including the one gating the WAL checkpoint. The sweep also joins `retention.py::_ack_sweeps` so a narrowed window is approvable where the operator looks (TD-12). **Audit** (C10/TD-10): quota events only — one `METRICS` row per (agent, UTC day) on the first cap refusal, best-effort. `audit_log` is append-only and undeletable for a year, so a row per accepted batch would be up to 86k permanent rows per agent per day at the cap. **Definitions policy** (C8) now reads live and says `enforced: True`, with a source per knob. Deliberate reds, each flipped here: `test_ent477_settings_knobs.py` is REPLACED by `test_ent478_settings_knobs.py` (every assertion inverts — ent#477 asserted the knobs must not exist until an enforcer shipped, and recorded "no env tier" as a tripwire precisely so this change could not happen silently); `test_ent477_definitions_endpoint.py` flips to `enforced is True`; `test_297` goes 11 → 12 retention keys and gains the generalised-redirect assertion. Tests: 572 passed across the ent478 + ent477 suites and the guards this touches (`test_1771a` set-equality, `test_2085` seeder, `test_297`, `test_models_centralized`). * feat(metrics): record_metrics MCP tool, requirements §48, and the docs the contract lives in (Abilityai/trinity-enterprise#478) Checkpoint C — the third surface (Invariant #13) and the written contract. **MCP tool** `src/mcp-server/src/tools/metrics.ts`: `record_metrics` plus `refresh_metric_definitions`, the remedy its own `metric_undeclared` hint names — shipped together so the hint points at something the agent reading it can actually call (TD-4). Agent-scoped keys only, with no agent-target parameter to spoof; both policy rows are `kind: "none"` because the backend self-gates the path agent. The tool never throws: a thrown error ends the agent's turn over what is usually a correctable mistake, and the 422 body carries a reason code per point precisely so the agent can fix the batch and re-send. Those per-point errors are surfaced verbatim. The retryable split is the load-bearing part — 503 is a store outage worth retrying, a 500 means the batch itself is unstorable and will fail identically forever, and the two 429s are distinguished because "wait a moment" and "wait until tomorrow" are different remedies. The description teaches the four rules an author can get wrong in a way the platform cannot detect afterwards: declare first, values are not coerced, identity excludes the value (so a correction is a new `ts`), and pass `execution_id` so a re-delivered turn replays. **Requirements**: §47.8 rewritten (the knobs it recorded as deliberately absent are now minted and enforced, and the env tier it recorded as non-existent is built), and a new §48 — the frozen wire shape #536/#479/#538 all defer to, the identity rule, the reason-code list ent#483 will validate parity against, the timestamp rules and the cap semantics. **Architecture**: `database.md` gets the table with the four column decisions that each go against a plausible default (no surrogate id, value outside the hash, the JSONB marker rule, DOUBLE PRECISION); `api-endpoints.md` the route; `backend.md` the router and the pure validator; `mcp-server.md` the new module; `reliability.md`'s counts move 10→11 guard sites and 11→12 retention keys, the env-layer sentence is corrected, and the ack-gated sweep list is now three. **Guide**: the "keep writing metrics.json until then" instruction is replaced by the actual `record_metrics` contract, and the retention/cap paragraph now says both are enforced and where to read the live numbers. Plus the feature flow's write-path section, the journey catalog (J12 gains 478 and stays `built: false` — the promise needs ent#479's read; JOURNEYS.md regenerated, not hand-edited), `tests/registry.json`, and `METRICS_RATE_LIMIT` / `METRICS_RETENTION_DAYS` / `METRICS_DAILY_POINT_CAP` in `.env.example` and both compose files. Tests: 19/19 in `metrics.test.ts`; `tsc --noEmit` clean; the full MCP suite is 477 pass / 1 fail, that failure being a pre-existing `run_agent_loop` gating test (confirmed identical with these changes reverted). Doc guards green (journey catalog, architecture split, testing-docs consolidation). * fix(metrics): bind the batch idempotency key to the body, repair the retention test stubs, and close the review's small findings (Abilityai/trinity-enterprise#478) * feat(metrics): re-back GET /metrics with the point store, one stale rule, MCP get_metrics (Abilityai/trinity-enterprise#479) Checkpoint A — the read half of ent#476's "one read of a business number". `services/metric_read_service.py` is new and holds the platform's SINGLE definition of freshness: `stale ⟺ cadence declared AND now − last_point_at > 2 × cadence`, strict `>`, with a future point clamped to age 0. `freshness()` is pure and importable without `database`, so #2927's role card and ent#666 call it rather than deriving a fourth threshold (a test pins that property). No cadence → `stale: None` / `no_cadence`; no points → `no_points`, not stale. `GET /api/agents/{name}/metrics` keeps its URL and is re-backed by the ent#478 point store, replacing the agent-server `metrics.json` proxy (deleted with its `__init__` export; zero importers). The read is store-only, so a STOPPED agent answers exactly like a running one — the proxy used to say "Agent must be running to read metrics", which made every number disappear at the moment an operator most wanted to see it. Contract: uniform-404 dependency then the agent self-gate (an agent key reads only its own numbers); `window ∈ auto/24h/7d/30d/90d` plus `since`/`until`, `auto` sized to the declared cadence; dimensioned metrics come back as one series per dims tuple with `latest` folded by the declared `aggregation` (TD-2); the default read ships ≤120 buckets per metric and raw points only on the single-metric path, newest-first (`ASC + LIMIT` would have kept last week and dropped today). Named refusals: 422 `window_invalid`, 422 `metric_undeclared` (never 404 — the MCP classifier reads 404 as not-authorized), a retired name carrying the `include_retired` hint (TD-10), 503 `metric_store_unavailable`. Read rate limit 240/min per agent (TD-6). D-010's persisted finding is echoed with `findings_evaluated_at`, so "no finding" can be told from "not evaluated" (TD-1). Store: `latest_points_for` seeks per declared name with an `(ts DESC, idempotency_key DESC)` tiebreak — a `row_number()` partition would number every row the agent ever recorded, and without the tiebreak SQLite and PostgreSQL may disagree about which point is "latest". `get_agent_health` gains an INFORMATIONAL `metrics` block, attached in the router after both build paths (never inside the fleet loop) and wrapped so a store failure yields `null` rather than a failed health check. It never touches `aggregate_status` or `issues`. MCP `get_metrics` (agent-scoped, no target parameter), `client.getAgentMetrics`, the `access.ts` policy row, and the health block passed through `monitoring.ts`. Tests: 45 backend unit tests (freshness table + boundaries, read store on `db_backend`, route gates/refusals/shape/D-010 echo, health informational-only) and 9 new MCP node:test cases. 603 passed across `test_ent47{7,8,9}_*` + `test_compatibility_checks.py`. Co-Authored-By: Claude Opus 5 <[email protected]> * feat(metrics): retire metrics.json via D-010, bind dashboard widgets to declared metrics (Abilityai/trinity-enterprise#479) Checkpoint B (backend half) + the compat half of checkpoint C. **D-010** (SOFT, static) names `metrics.json` as superseded rather than the read silently omitting what it holds. Serving the file when the store is empty was rejected deliberately — two sources for one number is what ent#476 exists to prevent — so the file becomes a finding instead. The collector now reads it WITH content (small flat JSON, existing size cap) so the detail can name which keys have no `template.yaml metrics:` entry: "you still write this file" is advice, "these numbers are declared nowhere" is a fix. Keys only, charset bounded, 25 max — `checks_json` is persisted and rendered. The route committed in the previous checkpoint already echoes this finding with `findings_evaluated_at`. Catalog 90 → 91; `docs/agent-validation-spec.md` gains its row and section. **The `metric:` binding**: a `dashboard.yaml` metric/status/progress widget may carry `metric: <name>` and is filled from the registry on every read — `value`, `color` (from the declared status `values[].color`, or thresholds for numeric types), `history` from the bucketed series, `stale`, `last_point_at`. Order is cache → snapshot → bind → history-enrich, on BOTH the live and the cached path, and the snapshot writer and the history enrichment both SKIP bound widgets through one shared `is_bound` predicate: a bound number in `agent_dashboard_values` would be a second source for a value the registry owns, and the two would disagree the moment the poll and the recording cadence drift apart. An undeclared name yields `binding_error` and NO value (a wrong number is worse than no number); a store outage degrades per widget and never 5xxs a dashboard. **The agent-server validator** (Invariant #5) no longer requires `value` — or `color` on a status widget — when `metric:` is set, so an author stops having to write a fake number forever. Older images keep the strict rule, so the guide will tell authors to keep a placeholder `value:`; the backend overwrites it when the binding resolves, and a test pins that. **`GET /api/agent-dashboard/{name}/exists`** now answers `{has_dashboard, has_declared_metrics}` in one DB-only request, so the tab can appear for an agent with declared metrics and no `dashboard.yaml` — and it is gated with the uniform-404 dependency, which it was not before: a bare `get_current_user` made it a fleet-wide existence oracle for any logged-in principal (TD-9 / E-S2). Tests: 23 new cases (D-010 shapes incl. both legacy file spellings and the charset bound; binding value/placeholder-overwrite/undeclared/outage/status colour/threshold colour; the two skips; the validator relaxation exercised against the REAL agent-image module). 624 passed across `test_ent47{7,8,9}_*` + `test_compatibility_checks.py`. Co-Authored-By: Claude Opus 5 <[email protected]> * feat(metrics): declared-metric tiles, bound widgets and the two-flag dashboard probe in the agent view (Abilityai/trinity-enterprise#479) Checkpoint B, frontend half — the surfaces that read what ent#477/#478 record. **`DeclaredMetricsTiles.vue`** is a SIBLING of `DashboardPanel`, not an arm inside it. The panel's state machine ends in "Agent Not Running" and "No Dashboard Defined"; the tiles are store-backed and must render for a stopped agent with no `dashboard.yaml` at all, which is precisely ent#439's sensible default and precisely the agent the panel refuses to render anything for. Own fetch, own interval, own `viewState`, so a metrics outage cannot take the dashboard down or vice versa. Every tile states WHEN its point was recorded — relative on the face, absolute on hover — because a number with no time is a claim about now and for a recorded metric that is usually false. A stale metric keeps showing its last known value with a warning chip naming what it was late against; it is never rendered as current. A metric with no declared cadence gets a neutral "No cadence declared" chip and is never called stale. The declared-but-empty copy is the backend's, so the tile and the route cannot name different next actions (`/update-dashboard` when the agent has that playbook, `record_metrics` when it does not). **The stale rule is not implemented here.** `stale` / `freshness` / `stale_after` arrive decided by `metric_read_service.freshness`; a browser-side recomputation would be a second rule the first time either was edited. **Two flags, one probe.** `GET …/exists` now answers `has_dashboard` AND `has_declared_metrics`, and `buildTabs` shows the Dashboard tab for EITHER. The probe lost its running-only condition at all four call sites: both halves are DB-only, and a stopped agent's recorded numbers are exactly what an operator wants. `buildTabs` moved to `utils/agentTabs.js` — it was tested by brace-matching its TEXT out of the SFC and `new Function`-ing it, which is a real execution but only existed because a spec could not import an SFC (#2918). **Two defects found while wiring it up, both in the previous checkpoint:** 1. `GET /api/agent-dashboard/{name}/exists` answered **422 to every caller**, owner included. `AuthorizedAgentByName` declares its path parameter as `agent_name`, so a route spelling it `{name}` left the dependency with nothing to bind. The probe was dead — the frontend's `catch` swallowed it into the boot ladder, so the tab still appeared for a running agent with a dashboard and `has_declared_metrics` was simply never true. The URL is unchanged; only the binding name moved. `test_ent479_exists_gate.py` went red on three of four cases before the fix and is the gate test the rider asked for: an absent and an inaccessible agent are byte-identical 404s (#186), and that cannot be proved by the sibling route suites, which override the dependency away to reach their handlers' own gates. 2. `bind_dashboard_widgets` wrote `widget["history"]` as a bare LIST while `_enrich_widgets_with_history` writes `{values, trend, …}` and `DashboardPanel.vue` reads `history.values`. A bound widget would silently lose its sparkline and trend arrow with every backend assertion green. One consumer, one shape, now pinned. `BoundMetricMark.vue` carries the bound widget's chip, point time, stale mark and binding error for all three arms that take a binding — its own component because a 735-line panel is already an #1031 candidate. A binding error renders the REASON, never a number: the backend removes `value` for an undeclared name, and a bare dash tells an operator nothing. `utils/metricFormat.js` lifts the panel's formatters so the two surfaces cannot drift, and makes them type-aware (5400 is `1h 30m`, not `5,400`) and direction-aware (rising revenue is good, rising error rate is not; a `neutral` metric gets no verdict at all). Tests: 4 new frontend specs, two of them MOUNTED under jsdom (the stale mark, the empty copy, in-place refresh keeping DOM identity and scrollTop, a failed refresh keeping the data, the three bound arms, the binding-error copy) plus the pure formatter and tab-gate suites. 3405 passed across the whole frontend unit suite on three consecutive runs, ratchets included; `check:tokens` clean; `npm run build` clean. Backend: 24 + 4 in the ent#479 binding and gate suites. Mutation-checked — inverting the tab gate and the freshness chip turns 8 of these red. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(metrics): §49 the read contract, D-010 + placeholder rule in the guide, J12 gains 479, bundled templates call record_metrics (Abilityai/trinity-enterprise#479) Checkpoint C — writing down what ent#479 decided, and stopping the repo's own templates from teaching the retired path. **Requirements §49** is the new section: the one staleness rule as a four-row table with the two boundaries a reader guesses wrong (exactly 2× is not stale; a future point clamps to fresh, and `no_cadence` is `null` rather than `false` because "not stale" and "unanswerable" are different claims); the route with its gate order, window contract and named errors; why the default read is bucketed; why `metric=` on a retired name is a 422 and not a 200; the health block being informational and never a verdict; the tiles as the default dashboard; the widget binding and the one `is_bound` skip that stops `agent_dashboard_values` becoming a second source. **§47.9 is rewritten**: the `metrics.json` read is gone, the file is not a fallback when the store is empty — deliberately, because "serve the file when we have nothing better" is exactly how two sources drift apart — and D-010 names it instead. **The guide** stops telling agents to write `metrics.json`. The old "metrics.json Format" section becomes a four-step migration; the complete example records with `record_metrics`; the CLAUDE.md snippet does too. It gains a "reading your own metrics back" section whose point is that declaring a `cadence:` is what buys you a staleness answer at all, and the **placeholder rule** (TD-3): an agent on a base image built before this issue still enforces the strict validator, so keep `value: 0` alongside `metric:` until it is rebuilt — the backend overwrites it whenever the binding resolves, so the placeholder is never what an operator sees. The Agent Dashboard section now opens by saying you may not need a `dashboard.yaml` at all. **Both feature flows** are rewritten around the completed loop rather than the legacy proxy: `agent-custom-metrics.md` replaces its metrics.json/MetricsPanel diagram and dead file table with the declare → record → read flow, the read contract and the retirement; `agent-dashboard.md` documents the binding, its three per-widget failure modes, the deprecation of snapshotting an author-written `value:` for a business number, and the two-flag gated `/exists` probe — including the path-parameter trap that made it 422 for everyone. **Architecture rows** for `metric_read_service` (the one stale rule, the call-time `db` resolution that keeps `freshness` importable, the `history` shape the panel reads, `is_bound`), the read endpoint, the third `metrics.ts` tool, the tiles/`metricFormat`/`agentTabs` frontend seam, the gated `/exists`, and a database note that the read adds no column and no index — the existing `(agent_name, metric, ts DESC)` btree already prefixes every access, and `0067_metric_points` stays head. **J12** carries `[477, 478, 479]` and stays `built: false`: the promise is whole in code, what is missing is the walk. The harness docstring gains the three steps that make it a journey rather than a registry test — record and read back with a real freshness verdict, read again with the agent STOPPED and get the same answer, and find D-010 rather than a served `metrics.json`. **TD-7** — the four in-repo templates that still instructed agents to write `metrics.json` (`demo-analyst`, `demo-researcher`, `dd-intake` and the system agent's `/update-dashboard` playbook) now call `record_metrics`. Text only, no playbook redesign — that is ent#482. Without this every demo and the system agent would show "declared, no points yet" on a fresh install. `tests/registry.json` gains all six ent#479 backend suites (none were registered by the earlier checkpoints) and the MCP row picks up `get_metrics`. 290 passed: `test_ent479_*` + `test_2338_journey_catalog` + `test_compatibility_checks`. 94 more across the testing-docs, model-placement, enumeration-uniformity and admin-gate guards. Co-Authored-By: Claude Opus 5 <[email protected]> * fix(metrics): drop out-of-window points before bucketing, reachable empty-state copy, retire the agent-server metrics.json route, readable D-010 detail, refuse retired bindings, fold charts across series (Abilityai/trinity-enterprise#479) I1: `_bucket` is fed the newest N points, not the window, so a point older than `since` got a negative index and was CLAMPED into bucket 0 — the read opened with a fabricated spike (the fold of every excluded point) stamped before `since`, and `stats`/`sparklineMax`/a bound widget's `history` were computed from it. Filter to `[since, until]` before indexing; keep the `SERIES_BUCKETS - 1` clamp only so `ts == until` lands in the last bucket. Each bucket now carries its index `i`, which is what makes cross-series folding well defined. I2: `has_playbook` was reachable only by its default, so the ruled "schedule `/update-dashboard`" copy was unrenderable. The route cannot compute it store-only (the playbook catalog is a container probe, and `agent_skills` knows only library assignments while the bundled templates carry the playbook in `.claude/commands/`), so the parameter is dropped and one sentence names both actions. A signature pin keeps a dead flag from coming back. I3: the agent-server `GET /api/metrics` no longer reads `metrics.json` (or `template.yaml`). Route kept per 49.7, answering 410 with `{has_metrics: false, superseded_by, finding: "D-010"}`. I4: D-010's `detail` is `{keys, undeclared}`; the tile spelled it through `toDisplayString` as JSON braces and the spec pinned a string the backend never emits. Rendered as a sentence, fixture corrected. I5: a widget bound to a RETIRED metric now refuses with `binding_error_code: metric_retired` + `retired_at` and no value — TD-10's rule applied to a reader that cannot pass `include_retired`. Every refusal gains a machine code beside its sentence. I6: `chart` is one bucket list shared by the sparkline, `stats` and a bound widget's `history`, so they describe the same thing as `latest.value`: the cross-series fold for `sum`/`avg`, and for `last` the single series named by `chart.dims`, which the tile labels. Plus the bucket-vs-window clamp class in learnings.md. Co-Authored-By: Claude Opus 5 <[email protected]> * test(metrics): align the live-tier agent-metrics test with the ent#479 body (Abilityai/trinity-enterprise#479) The read is store-only now: `status` / `has_metrics` / `values` were the metrics.json proxy's body (retired by D-010), so the suite asserted a shape the route no longer emits. It now asserts the ent#479 fields — `declared`, `window`, `stale_rule`, `findings`, per-metric `latest`/`freshness`/`stale` — pins the retired fields as ABSENT, and drops the 'stopped agents have no metrics' expectation, since a stopped agent now answers exactly like a running one. * merge-train: re-chain the registry revision to 0069 after dev's 0066–0068, isolate the start-hook tests' task set, drive the Alembic PG test on TEST_POSTGRES_URL (Abilityai/trinity-enterprise#477) Mechanical fixes applied on the member branch, per the merge-train note on #2942: - 0066_metric_definitions → 0069_metric_definitions on top of 0068_agent_shared_files_audience. dev landed 0066_public_user_memory_writes, 0067_agent_role_readiness and 0068_agent_shared_files_audience after this branch's last re-chain, so it was a second #2068 fork (alembic-head-watch was red). check_alembic_heads.py: 70 revisions, 1 head. - test_ent477_git_refresh_hook: the two start-hook tests gather metric_registry._inflight_refresh_tasks, a module-level set that other tests leave stale tasks in (spawned on a loop that closed before the done-callback fired). Under CI's random ordering asyncio.gather then raised 'The future belongs to a different loop'. Each test now monkeypatches a fresh set. - test_the_alembic_revision_builds_the_table_on_postgres called upgrade_to_head() on the DATABASE_URL default (SQLite), where 0004's 'ADD COLUMN IF NOT EXISTS' cannot parse; schema-parity was red on every PR in the stack that touches db/. It now points DATABASE_URL at TEST_POSTGRES_URL, resets the schema, upgrades to head and reads back. Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: make SOURCES live, hash-stable definition_hash, mcp header on git.py (Abilityai/trinity-enterprise#477) Mechanical, per the /review findings recorded on #2942: - SOURCES was a constant nobody read. _reconcile now refuses a source outside it (ValueError) before anything reaches the store, and a test drives the refusal. - definition_hash hashed the entry INCLUDING the definition_hash key that _reconcile writes into it, so hashing one list twice drifted and would have reported every metric as updated. The hash now excludes its own key; a test pins the stability. - routers/git.py gains its first-line '# mcp:' header (Invariant #13) — this PR touches three of its handlers and the file had none. Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: drop two unreferenced store helpers, one source for the dim/skew limits (Abilityai/trinity-enterprise#478) Mechanical, per the /review findings recorded on #2948: - db/metric_points.py: metric_points_remaining and build_point_row had no caller in src/ or tests/ (the sweep calls count_metric_points_candidates directly; the service builds its own row dict). - services/metric_points_service.py: MAX_DIM_VALUE_LEN and TS_FUTURE_SKEW_SECONDS duplicated METRIC_DIM_VALUE_MAX_LEN and METRIC_TS_FUTURE_SKEW_SECONDS in models.py; the service now reads the models.py values, so the wire contract has one spelling. Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: wire METRICS_READ_RATE_LIMIT into compose and .env.example (Abilityai/trinity-enterprise#479) Mechanical, per the /validate-pr config-packaging check (§4.9) recorded on #2951: the knob was read via os.getenv in routers/agent_files.py but declared in neither compose file nor .env.example, so the tuning lever was inert on every deployment. Default unchanged (240/min). Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: the cleanup suite's mock learns the metric-point accessors, hosted compose mirrors prod's METRICS block, lint-clean sys.modules poisoning (Abilityai/trinity-enterprise#478) Mechanical, surfaced by the full unit suite on the merged stack (none of these ran in CI — the stacked base never triggers backend-unit-test): - tests/unit/test_cleanup_inner_sweeps.py: _configure_db never set count_metric_points_candidates / prune_metric_points, so the ent#478 sweep stored a MagicMock in report.metric_points_pruned and the WAL-checkpoint sum raised "'>' not supported between MagicMock and int". - docker-compose.hosted.yml: test_2280_hosted_compose_parity requires the backend environment to match prod; the three METRICS_* knobs were added to prod only. - tests/unit/test_ent478_point_validation.py: bare sys.modules pop/assign/del → monkeypatch.setitem + undo (tests/lint_sys_modules.py). Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: the bound-widget threshold reads the registry's direction vocabulary, snapshot skip proven on a live engine, hosted compose + lint + three nits (Abilityai/trinity-enterprise#479) Per the /review findings recorded on #2951: - metric_read_service._threshold_color judged direction as 'up' / 'down', which the registry never emits (DIRECTIONS = up_good / down_good / neutral). Every declared metric therefore fell into the 'up' arm, so an up_good revenue widget turned red for EXCEEDING its critical threshold and a neutral metric was judged at all — while the tile beside it, via utils/metricFormat.js::thresholdClasses, did the opposite. The backend now spells the tile's rule: down_good breaches at-or-above, up_good at-or-below, neutral declines. The pinning test used direction='up' and was green for the wrong reason; three tests now drive both arms and neutral. - The snapshot-writer skip for a bound widget was pinned by inspect.getsource; it is now executed through the real engine (capture_dashboard_snapshot writes the plain widget and not the bound one). - docker-compose.hosted.yml mirrors prod's METRICS_READ_RATE_LIMIT line (test_2280_hosted_compose_parity). - test_ent479_freshness_rule: bare sys.modules.pop → monkeypatch.delitem. - Nits: unused Optional import in agent_server/routers/info.py, the refreshMetricDefinitions JSDoc in client.ts sat above getAgentMetrics, routers/monitoring.py gains its '# mcp:' header (Invariant #13). Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: sim <[email protected]>
vybe
added a commit
that referenced
this pull request
Sep 22, 2026
…eshness, spelled once; GET /objectives + get_objectives (Abilityai/trinity-enterprise#666) (#2953) * feat(metrics): declared-metric registry — template.yaml metrics: reader, metric_definitions store, reconcile on create/pull/sync/start, definitions API, compat D-009 (Abilityai/trinity-enterprise#477) * fix(metrics): re-chain the registry migration to 0066 after dev's 0065, make the declared-metrics reader total on non-string keys, register the J12 harness (Abilityai/trinity-enterprise#477) * fix(metrics): a refused metric type change keeps status_values_json (Abilityai/trinity-enterprise#477) `reconcile` copies the whole declaration payload over an existing row, so a re-declaration whose `type` was REFUSED still overwrote `status_values_json` from the refused entry. Re-declaring a `status` metric as `counter` therefore kept the stored type `status` while nulling its declared value domain, leaving a status row that nothing can interpret — and ent#478's point validator would have had to widen to "accept any string" to cope with it. The stored type stands, so the column that exists only for that type stands with it. One line in the refusal branch; `test_a_refused_type_change_keeps_the_ declared_status_values` goes red without it (verified by removing the line). Found by the ent#478 plan review (TD-15); landed here because 478 stacks on this branch. * feat(metrics): metric_points schema, store, validator and wire model (Abilityai/trinity-enterprise#478) Checkpoint A of ent#478 — everything below the route. The push path itself (route, settings, sweep, MCP tool) lands in the following commits. **Schema, all four tracks** (Invariant #9): `db/schema.py` DDL + three indexes, `db/tables.py` Core metadata, the SQLite `metric_points_table` migration, and Alembic `0067_metric_points <- 0066_metric_definitions`. No surrogate id: the primary key IS the point identity `(agent_name, ts, idempotency_key)`, which keeps the eventual partition key inside the only unique constraint so ent#80 can partition by month without a table rebuild. `dims` is JSONB on PostgreSQL and TEXT on SQLite through a new per-column marker rule — `dims TEXT /* pg:JSONB */` in the shared DDL, rewritten by `to_postgres_table_ddl`. One rule converges the fresh-PG path (`0001_baseline` replays that DDL), the upgrade path and SQLite, with no `ALTER ... USING` repeated in two places. `value_numeric` is `DOUBLE PRECISION`, not `REAL`: `REAL` is float4 on PostgreSQL and would round a revenue metric's cents. **Store** (`db/metric_points.py`): `insert_points` counts with `.returning` rather than `rowcount`, which is not a portable count of what survived a multi-VALUES `DO NOTHING`. The cap count and the sweep's candidate count are both LIMIT-bounded, and the count and the prune are built from ONE predicate (the ent#433 rule). The prune chunks by `ts` RANGE — there are no ids — taking boundary ties with it so a busy millisecond cannot wedge the loop, and is bounded to 20 chunks per call so a narrowed window drains over several cleanup cycles instead of blocking the others for one very long one (TD-14). **Validator** (`services/metric_points_service.py`): a pure leaf over the ent#477 definitions — no DB, no settings, no HTTP. Points validate against the STORED type, never `type_conflict` (T5), with a hint naming the author-side rename. `ts` must match the RFC 3339 shape and is range-checked as a DATETIME, not a string: `0999-01-01` normalises to `999-01-01T...`, which sorts ABOVE every real timestamp and would head the `ts DESC` read index forever. Below the retention window is refused too, so agent input cannot steer the retention guard into permanent refusal. Messages echo codes, indices and dimension KEYS only — this output lands in an LLM's context and in logs. **Model** (`models.py`): the frozen `MetricPointIn` wire shape ent#479 reads back and #536 binds a canvas chart to. A before-validator rejects `bool` (an `int` subclass Pydantic was measured to coerce to `1.0`) and non-finite floats (SQLite stores NaN as NULL, PostgreSQL as NaN — one batch, two meanings). **Cascade** (`db/agent_cleanup.py`): one CASCADE ref. The identity hash excludes `agent_name`, so a rename re-keys losslessly. Tests: 59 validation/model + 27 store (SQLite; the JSONB column-type assertion is PostgreSQL-marked so it actually runs on the PG leg), including a negative control showing what `test_schema_parity` structurally cannot see and a facade signature-parity check. * feat(metrics): record_metrics route, Settings knobs, retention sweep and quota audit (Abilityai/trinity-enterprise#478) Checkpoint B — the push path itself. The MCP tool and the docs follow. **Route** `POST /api/agents/{name}/metrics/points` in its own module (router → service → db, Invariant #1), registered before the agents router's single-segment routes. Gate order is load-bearing: self-gate (access-first, so the answer cannot vary by whether a metric exists) → rate limit → size → batch idempotency → definitions → validate → daily cap → insert. Two idempotency layers. The ROW key is the invariant and needs nothing; the BATCH key gives Invariant #18's "returns the first result". Where no client key is supplied but `execution_id` resolves to this agent, the batch key is derived from the execution — which is what dedups a batch of `ts`-less points on a re-delivered turn, since those would otherwise take a fresh server-now timestamp and hash to something new. With neither, a retry is a new observation, stated rather than papered over with a body hash (a body hash would drop the legitimate "same numbers an hour later"). Every non-2xx exit past the claim goes through one `_reject` choke point that releases it first: a 422 that wedged the caller's key would turn one malformed batch into a day of silently dropped metrics. DB failures are CLASSIFIED — connectivity is 503 + `Retry-After`, a content error is a non-retryable 500, because telling an agent to retry a batch the database will reject identically forever is how a permanent error becomes an infinite loop. **Settings** (C6): `metrics_retention_days` (365, a retention key with its own guard site) and `metrics_daily_point_cap` (100000, `0` = unlimited), with a NEW env tier — `ENV_BACKED_OPS_KEYS` + `config.resolve_ops_default` + `settings_service.resolve_ops_setting`, opt-in per key so the ~20 keys the retention endpoint documents as env-less keep their precedence. One semantic: env is a live fallback, and the #2085 boot seeder SKIPS an env-set key rather than freezing its value into a row. `get_ops_setting`, the boot log, `GET /api/settings/retention` and the definitions `policy` all resolve through the one chain and report which tier answered. The ent#297 redirect is generalised (E4): the unvalidated catch-all PUT now refuses EVERY key that has validation, not a hand-maintained subset — the cap was reachable there, where garbage stores verbatim and then 500s the reader. The cap reader coerces garbage to the default, never to `0`. **Sweep** (C7) beside the sibling row sweeps, with two deliberate differences: `floor=FLOOR_METRIC_POINTS` (100k, one agent-day at the cap), because at the default 1000 any real ingest rate refuses every cycle and then sits blocked behind single-use acks; and the ack is consumed only once the REMAINING backlog is under the floor, since the prune is bounded per call. The counter is added to all three `CleanupReport` sums including the one gating the WAL checkpoint. The sweep also joins `retention.py::_ack_sweeps` so a narrowed window is approvable where the operator looks (TD-12). **Audit** (C10/TD-10): quota events only — one `METRICS` row per (agent, UTC day) on the first cap refusal, best-effort. `audit_log` is append-only and undeletable for a year, so a row per accepted batch would be up to 86k permanent rows per agent per day at the cap. **Definitions policy** (C8) now reads live and says `enforced: True`, with a source per knob. Deliberate reds, each flipped here: `test_ent477_settings_knobs.py` is REPLACED by `test_ent478_settings_knobs.py` (every assertion inverts — ent#477 asserted the knobs must not exist until an enforcer shipped, and recorded "no env tier" as a tripwire precisely so this change could not happen silently); `test_ent477_definitions_endpoint.py` flips to `enforced is True`; `test_297` goes 11 → 12 retention keys and gains the generalised-redirect assertion. Tests: 572 passed across the ent478 + ent477 suites and the guards this touches (`test_1771a` set-equality, `test_2085` seeder, `test_297`, `test_models_centralized`). * feat(metrics): record_metrics MCP tool, requirements §48, and the docs the contract lives in (Abilityai/trinity-enterprise#478) Checkpoint C — the third surface (Invariant #13) and the written contract. **MCP tool** `src/mcp-server/src/tools/metrics.ts`: `record_metrics` plus `refresh_metric_definitions`, the remedy its own `metric_undeclared` hint names — shipped together so the hint points at something the agent reading it can actually call (TD-4). Agent-scoped keys only, with no agent-target parameter to spoof; both policy rows are `kind: "none"` because the backend self-gates the path agent. The tool never throws: a thrown error ends the agent's turn over what is usually a correctable mistake, and the 422 body carries a reason code per point precisely so the agent can fix the batch and re-send. Those per-point errors are surfaced verbatim. The retryable split is the load-bearing part — 503 is a store outage worth retrying, a 500 means the batch itself is unstorable and will fail identically forever, and the two 429s are distinguished because "wait a moment" and "wait until tomorrow" are different remedies. The description teaches the four rules an author can get wrong in a way the platform cannot detect afterwards: declare first, values are not coerced, identity excludes the value (so a correction is a new `ts`), and pass `execution_id` so a re-delivered turn replays. **Requirements**: §47.8 rewritten (the knobs it recorded as deliberately absent are now minted and enforced, and the env tier it recorded as non-existent is built), and a new §48 — the frozen wire shape #536/#479/#538 all defer to, the identity rule, the reason-code list ent#483 will validate parity against, the timestamp rules and the cap semantics. **Architecture**: `database.md` gets the table with the four column decisions that each go against a plausible default (no surrogate id, value outside the hash, the JSONB marker rule, DOUBLE PRECISION); `api-endpoints.md` the route; `backend.md` the router and the pure validator; `mcp-server.md` the new module; `reliability.md`'s counts move 10→11 guard sites and 11→12 retention keys, the env-layer sentence is corrected, and the ack-gated sweep list is now three. **Guide**: the "keep writing metrics.json until then" instruction is replaced by the actual `record_metrics` contract, and the retention/cap paragraph now says both are enforced and where to read the live numbers. Plus the feature flow's write-path section, the journey catalog (J12 gains 478 and stays `built: false` — the promise needs ent#479's read; JOURNEYS.md regenerated, not hand-edited), `tests/registry.json`, and `METRICS_RATE_LIMIT` / `METRICS_RETENTION_DAYS` / `METRICS_DAILY_POINT_CAP` in `.env.example` and both compose files. Tests: 19/19 in `metrics.test.ts`; `tsc --noEmit` clean; the full MCP suite is 477 pass / 1 fail, that failure being a pre-existing `run_agent_loop` gating test (confirmed identical with these changes reverted). Doc guards green (journey catalog, architecture split, testing-docs consolidation). * fix(metrics): bind the batch idempotency key to the body, repair the retention test stubs, and close the review's small findings (Abilityai/trinity-enterprise#478) * feat(metrics): re-back GET /metrics with the point store, one stale rule, MCP get_metrics (Abilityai/trinity-enterprise#479) Checkpoint A — the read half of ent#476's "one read of a business number". `services/metric_read_service.py` is new and holds the platform's SINGLE definition of freshness: `stale ⟺ cadence declared AND now − last_point_at > 2 × cadence`, strict `>`, with a future point clamped to age 0. `freshness()` is pure and importable without `database`, so #2927's role card and ent#666 call it rather than deriving a fourth threshold (a test pins that property). No cadence → `stale: None` / `no_cadence`; no points → `no_points`, not stale. `GET /api/agents/{name}/metrics` keeps its URL and is re-backed by the ent#478 point store, replacing the agent-server `metrics.json` proxy (deleted with its `__init__` export; zero importers). The read is store-only, so a STOPPED agent answers exactly like a running one — the proxy used to say "Agent must be running to read metrics", which made every number disappear at the moment an operator most wanted to see it. Contract: uniform-404 dependency then the agent self-gate (an agent key reads only its own numbers); `window ∈ auto/24h/7d/30d/90d` plus `since`/`until`, `auto` sized to the declared cadence; dimensioned metrics come back as one series per dims tuple with `latest` folded by the declared `aggregation` (TD-2); the default read ships ≤120 buckets per metric and raw points only on the single-metric path, newest-first (`ASC + LIMIT` would have kept last week and dropped today). Named refusals: 422 `window_invalid`, 422 `metric_undeclared` (never 404 — the MCP classifier reads 404 as not-authorized), a retired name carrying the `include_retired` hint (TD-10), 503 `metric_store_unavailable`. Read rate limit 240/min per agent (TD-6). D-010's persisted finding is echoed with `findings_evaluated_at`, so "no finding" can be told from "not evaluated" (TD-1). Store: `latest_points_for` seeks per declared name with an `(ts DESC, idempotency_key DESC)` tiebreak — a `row_number()` partition would number every row the agent ever recorded, and without the tiebreak SQLite and PostgreSQL may disagree about which point is "latest". `get_agent_health` gains an INFORMATIONAL `metrics` block, attached in the router after both build paths (never inside the fleet loop) and wrapped so a store failure yields `null` rather than a failed health check. It never touches `aggregate_status` or `issues`. MCP `get_metrics` (agent-scoped, no target parameter), `client.getAgentMetrics`, the `access.ts` policy row, and the health block passed through `monitoring.ts`. Tests: 45 backend unit tests (freshness table + boundaries, read store on `db_backend`, route gates/refusals/shape/D-010 echo, health informational-only) and 9 new MCP node:test cases. 603 passed across `test_ent47{7,8,9}_*` + `test_compatibility_checks.py`. Co-Authored-By: Claude Opus 5 <[email protected]> * feat(metrics): retire metrics.json via D-010, bind dashboard widgets to declared metrics (Abilityai/trinity-enterprise#479) Checkpoint B (backend half) + the compat half of checkpoint C. **D-010** (SOFT, static) names `metrics.json` as superseded rather than the read silently omitting what it holds. Serving the file when the store is empty was rejected deliberately — two sources for one number is what ent#476 exists to prevent — so the file becomes a finding instead. The collector now reads it WITH content (small flat JSON, existing size cap) so the detail can name which keys have no `template.yaml metrics:` entry: "you still write this file" is advice, "these numbers are declared nowhere" is a fix. Keys only, charset bounded, 25 max — `checks_json` is persisted and rendered. The route committed in the previous checkpoint already echoes this finding with `findings_evaluated_at`. Catalog 90 → 91; `docs/agent-validation-spec.md` gains its row and section. **The `metric:` binding**: a `dashboard.yaml` metric/status/progress widget may carry `metric: <name>` and is filled from the registry on every read — `value`, `color` (from the declared status `values[].color`, or thresholds for numeric types), `history` from the bucketed series, `stale`, `last_point_at`. Order is cache → snapshot → bind → history-enrich, on BOTH the live and the cached path, and the snapshot writer and the history enrichment both SKIP bound widgets through one shared `is_bound` predicate: a bound number in `agent_dashboard_values` would be a second source for a value the registry owns, and the two would disagree the moment the poll and the recording cadence drift apart. An undeclared name yields `binding_error` and NO value (a wrong number is worse than no number); a store outage degrades per widget and never 5xxs a dashboard. **The agent-server validator** (Invariant #5) no longer requires `value` — or `color` on a status widget — when `metric:` is set, so an author stops having to write a fake number forever. Older images keep the strict rule, so the guide will tell authors to keep a placeholder `value:`; the backend overwrites it when the binding resolves, and a test pins that. **`GET /api/agent-dashboard/{name}/exists`** now answers `{has_dashboard, has_declared_metrics}` in one DB-only request, so the tab can appear for an agent with declared metrics and no `dashboard.yaml` — and it is gated with the uniform-404 dependency, which it was not before: a bare `get_current_user` made it a fleet-wide existence oracle for any logged-in principal (TD-9 / E-S2). Tests: 23 new cases (D-010 shapes incl. both legacy file spellings and the charset bound; binding value/placeholder-overwrite/undeclared/outage/status colour/threshold colour; the two skips; the validator relaxation exercised against the REAL agent-image module). 624 passed across `test_ent47{7,8,9}_*` + `test_compatibility_checks.py`. Co-Authored-By: Claude Opus 5 <[email protected]> * feat(metrics): declared-metric tiles, bound widgets and the two-flag dashboard probe in the agent view (Abilityai/trinity-enterprise#479) Checkpoint B, frontend half — the surfaces that read what ent#477/#478 record. **`DeclaredMetricsTiles.vue`** is a SIBLING of `DashboardPanel`, not an arm inside it. The panel's state machine ends in "Agent Not Running" and "No Dashboard Defined"; the tiles are store-backed and must render for a stopped agent with no `dashboard.yaml` at all, which is precisely ent#439's sensible default and precisely the agent the panel refuses to render anything for. Own fetch, own interval, own `viewState`, so a metrics outage cannot take the dashboard down or vice versa. Every tile states WHEN its point was recorded — relative on the face, absolute on hover — because a number with no time is a claim about now and for a recorded metric that is usually false. A stale metric keeps showing its last known value with a warning chip naming what it was late against; it is never rendered as current. A metric with no declared cadence gets a neutral "No cadence declared" chip and is never called stale. The declared-but-empty copy is the backend's, so the tile and the route cannot name different next actions (`/update-dashboard` when the agent has that playbook, `record_metrics` when it does not). **The stale rule is not implemented here.** `stale` / `freshness` / `stale_after` arrive decided by `metric_read_service.freshness`; a browser-side recomputation would be a second rule the first time either was edited. **Two flags, one probe.** `GET …/exists` now answers `has_dashboard` AND `has_declared_metrics`, and `buildTabs` shows the Dashboard tab for EITHER. The probe lost its running-only condition at all four call sites: both halves are DB-only, and a stopped agent's recorded numbers are exactly what an operator wants. `buildTabs` moved to `utils/agentTabs.js` — it was tested by brace-matching its TEXT out of the SFC and `new Function`-ing it, which is a real execution but only existed because a spec could not import an SFC (#2918). **Two defects found while wiring it up, both in the previous checkpoint:** 1. `GET /api/agent-dashboard/{name}/exists` answered **422 to every caller**, owner included. `AuthorizedAgentByName` declares its path parameter as `agent_name`, so a route spelling it `{name}` left the dependency with nothing to bind. The probe was dead — the frontend's `catch` swallowed it into the boot ladder, so the tab still appeared for a running agent with a dashboard and `has_declared_metrics` was simply never true. The URL is unchanged; only the binding name moved. `test_ent479_exists_gate.py` went red on three of four cases before the fix and is the gate test the rider asked for: an absent and an inaccessible agent are byte-identical 404s (#186), and that cannot be proved by the sibling route suites, which override the dependency away to reach their handlers' own gates. 2. `bind_dashboard_widgets` wrote `widget["history"]` as a bare LIST while `_enrich_widgets_with_history` writes `{values, trend, …}` and `DashboardPanel.vue` reads `history.values`. A bound widget would silently lose its sparkline and trend arrow with every backend assertion green. One consumer, one shape, now pinned. `BoundMetricMark.vue` carries the bound widget's chip, point time, stale mark and binding error for all three arms that take a binding — its own component because a 735-line panel is already an #1031 candidate. A binding error renders the REASON, never a number: the backend removes `value` for an undeclared name, and a bare dash tells an operator nothing. `utils/metricFormat.js` lifts the panel's formatters so the two surfaces cannot drift, and makes them type-aware (5400 is `1h 30m`, not `5,400`) and direction-aware (rising revenue is good, rising error rate is not; a `neutral` metric gets no verdict at all). Tests: 4 new frontend specs, two of them MOUNTED under jsdom (the stale mark, the empty copy, in-place refresh keeping DOM identity and scrollTop, a failed refresh keeping the data, the three bound arms, the binding-error copy) plus the pure formatter and tab-gate suites. 3405 passed across the whole frontend unit suite on three consecutive runs, ratchets included; `check:tokens` clean; `npm run build` clean. Backend: 24 + 4 in the ent#479 binding and gate suites. Mutation-checked — inverting the tab gate and the freshness chip turns 8 of these red. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(metrics): §49 the read contract, D-010 + placeholder rule in the guide, J12 gains 479, bundled templates call record_metrics (Abilityai/trinity-enterprise#479) Checkpoint C — writing down what ent#479 decided, and stopping the repo's own templates from teaching the retired path. **Requirements §49** is the new section: the one staleness rule as a four-row table with the two boundaries a reader guesses wrong (exactly 2× is not stale; a future point clamps to fresh, and `no_cadence` is `null` rather than `false` because "not stale" and "unanswerable" are different claims); the route with its gate order, window contract and named errors; why the default read is bucketed; why `metric=` on a retired name is a 422 and not a 200; the health block being informational and never a verdict; the tiles as the default dashboard; the widget binding and the one `is_bound` skip that stops `agent_dashboard_values` becoming a second source. **§47.9 is rewritten**: the `metrics.json` read is gone, the file is not a fallback when the store is empty — deliberately, because "serve the file when we have nothing better" is exactly how two sources drift apart — and D-010 names it instead. **The guide** stops telling agents to write `metrics.json`. The old "metrics.json Format" section becomes a four-step migration; the complete example records with `record_metrics`; the CLAUDE.md snippet does too. It gains a "reading your own metrics back" section whose point is that declaring a `cadence:` is what buys you a staleness answer at all, and the **placeholder rule** (TD-3): an agent on a base image built before this issue still enforces the strict validator, so keep `value: 0` alongside `metric:` until it is rebuilt — the backend overwrites it whenever the binding resolves, so the placeholder is never what an operator sees. The Agent Dashboard section now opens by saying you may not need a `dashboard.yaml` at all. **Both feature flows** are rewritten around the completed loop rather than the legacy proxy: `agent-custom-metrics.md` replaces its metrics.json/MetricsPanel diagram and dead file table with the declare → record → read flow, the read contract and the retirement; `agent-dashboard.md` documents the binding, its three per-widget failure modes, the deprecation of snapshotting an author-written `value:` for a business number, and the two-flag gated `/exists` probe — including the path-parameter trap that made it 422 for everyone. **Architecture rows** for `metric_read_service` (the one stale rule, the call-time `db` resolution that keeps `freshness` importable, the `history` shape the panel reads, `is_bound`), the read endpoint, the third `metrics.ts` tool, the tiles/`metricFormat`/`agentTabs` frontend seam, the gated `/exists`, and a database note that the read adds no column and no index — the existing `(agent_name, metric, ts DESC)` btree already prefixes every access, and `0067_metric_points` stays head. **J12** carries `[477, 478, 479]` and stays `built: false`: the promise is whole in code, what is missing is the walk. The harness docstring gains the three steps that make it a journey rather than a registry test — record and read back with a real freshness verdict, read again with the agent STOPPED and get the same answer, and find D-010 rather than a served `metrics.json`. **TD-7** — the four in-repo templates that still instructed agents to write `metrics.json` (`demo-analyst`, `demo-researcher`, `dd-intake` and the system agent's `/update-dashboard` playbook) now call `record_metrics`. Text only, no playbook redesign — that is ent#482. Without this every demo and the system agent would show "declared, no points yet" on a fresh install. `tests/registry.json` gains all six ent#479 backend suites (none were registered by the earlier checkpoints) and the MCP row picks up `get_metrics`. 290 passed: `test_ent479_*` + `test_2338_journey_catalog` + `test_compatibility_checks`. 94 more across the testing-docs, model-placement, enumeration-uniformity and admin-gate guards. Co-Authored-By: Claude Opus 5 <[email protected]> * fix(metrics): drop out-of-window points before bucketing, reachable empty-state copy, retire the agent-server metrics.json route, readable D-010 detail, refuse retired bindings, fold charts across series (Abilityai/trinity-enterprise#479) I1: `_bucket` is fed the newest N points, not the window, so a point older than `since` got a negative index and was CLAMPED into bucket 0 — the read opened with a fabricated spike (the fold of every excluded point) stamped before `since`, and `stats`/`sparklineMax`/a bound widget's `history` were computed from it. Filter to `[since, until]` before indexing; keep the `SERIES_BUCKETS - 1` clamp only so `ts == until` lands in the last bucket. Each bucket now carries its index `i`, which is what makes cross-series folding well defined. I2: `has_playbook` was reachable only by its default, so the ruled "schedule `/update-dashboard`" copy was unrenderable. The route cannot compute it store-only (the playbook catalog is a container probe, and `agent_skills` knows only library assignments while the bundled templates carry the playbook in `.claude/commands/`), so the parameter is dropped and one sentence names both actions. A signature pin keeps a dead flag from coming back. I3: the agent-server `GET /api/metrics` no longer reads `metrics.json` (or `template.yaml`). Route kept per 49.7, answering 410 with `{has_metrics: false, superseded_by, finding: "D-010"}`. I4: D-010's `detail` is `{keys, undeclared}`; the tile spelled it through `toDisplayString` as JSON braces and the spec pinned a string the backend never emits. Rendered as a sentence, fixture corrected. I5: a widget bound to a RETIRED metric now refuses with `binding_error_code: metric_retired` + `retired_at` and no value — TD-10's rule applied to a reader that cannot pass `include_retired`. Every refusal gains a machine code beside its sentence. I6: `chart` is one bucket list shared by the sparkline, `stats` and a bound widget's `history`, so they describe the same thing as `latest.value`: the cross-series fold for `sum`/`avg`, and for `last` the single series named by `chart.dims`, which the tile labels. Plus the bucket-vs-window clamp class in learnings.md. Co-Authored-By: Claude Opus 5 <[email protected]> * test(metrics): align the live-tier agent-metrics test with the ent#479 body (Abilityai/trinity-enterprise#479) The read is store-only now: `status` / `has_metrics` / `values` were the metrics.json proxy's body (retired by D-010), so the suite asserted a shape the route no longer emits. It now asserts the ent#479 fields — `declared`, `window`, `stale_rule`, `findings`, per-metric `latest`/`freshness`/`stale` — pins the retired fields as ABSENT, and drops the 'stopped agents have no metrics' expectation, since a stopped agent now answers exactly like a running one. * feat(metrics): the objective join — target vs actual with freshness, spelled once (Abilityai/trinity-enterprise#666) An objective (Tandem §3.4) names a metric by name; §47 says what that name means; §48 says what it currently reads; §49's `freshness()` says whether to believe it. `services/objective_join_service.py` is the join of those four, and it is the ONE join — the role card (ent#527), the project hub (ent#661) and proactivity (ent#605) consume it rather than each growing their own, which is the defect epic ent#476 exists to remove. Two halves in one module. The pure half imports at module top with no store or Docker behind it: `canon_root`, `parse_objective`, `objective_concerns`, `objective_is_active`, `select_objectives`, `resolve_direction`, `gap`, `join_objectives`. The async half goes through the agent door — files are truth and they live in the container (E7/E13), so a stopped agent answers `unavailable: agent_stopped` with copy naming the fix rather than a number that was true once. `actual` is the tile's folded latest, not a second computation (TD-1). `_latest_entry` is extracted from `_compose_metric` and both it and the new `latest_by_metric` go through it, so "the objective's actual" and "the number on the tile" are the same fact by construction — pinned by a parity test including a dimensioned `sum` metric, where a re-implemented fold would plausibly diverge. `latest_by_metric` does no series, bucket or stats work and takes `definitions=` / `names=`, so the join pays one registry read and one point read for the names an objective actually references, and none at all when there is nothing to join. Direction falls through to the objective file when the registry has no opinion (TD-2): `neutral` is the column DEFAULT and no bundled template declares `direction:`, so registry-only would have shipped a feature where every gap is uncomputable on day one. Two DECLARED directions that disagree is a `direction_mismatch` finding and the registry wins. `hold` is the grammar's third direction, mapped to the registry's `neutral` but told apart from silence by `direction_source` — and it has its own gap arm, `on_target` within `tolerance` and `off_target` otherwise, never behind/ahead, because a value that should be held has no good side to be on. `gap.status` is POSITION relative to target given direction, never pace (TD-3). `by` and `horizon` ride every row so ent#605 can judge pace itself; nothing here computes one. `stale` is orthogonal: a stale metric still gets its gap, with `stale: true` beside it — the card renders "30 / 35 · stale" and the consumer decides. Never a blank. An objective naming an undeclared metric is a `metric_undeclared` finding with the fix attached; a SUPPORTING agent gets `metric_not_declared_here` instead and is not counted as undeclared, because "declare it and refresh" is advice it cannot take (the registry is per-agent; cross-agent reads are ent#80). A retired metric withholds its last value and says why. A file that will not parse is `objective_invalid` with its path, not a silent `continue`. Hardening the fan-out costs less than recovering from it: objective reads run ≤ 2 in flight and abort to `agent_unreachable` on the first typed transport failure, so one dead agent-server cannot drive open the circuit breaker that chat rides on. The scan lists up to 100 files, filters, and caps the OUTPUT at 20 — capping the listing first hides an agent's own objective behind twenty foreign ones in a shared fleet canon. Author values are normalised at parse: `.nan` / `.inf` / lists / bools become `target_text`, so no bare `NaN` reaches a body that `JSON.parse` would throw on. Tests: 107 unit cases across the gap table (nine positions × three directions, the `hold` arm, tolerance, NaN/inf/list/bool targets), the join (undeclared, not-declared-here, retired, stale, no-points, no-cadence, mismatch, duplicates, summary arithmetic), the composition (three unavailable states, zero-config with no store call, scan bounds, concurrency bound, fan-out abort, traversal refusal) and the parity + wiring guards. * feat(metrics): the objectives read, MCP get_objectives, and §50 (Abilityai/trinity-enterprise#666) The two doors onto the join, plus the docs that make it a contract rather than an implementation detail. `GET /api/agents/{name}/objectives` copies `/metrics`'s gate order verbatim — uniform-404 dependency, then the agent self-gate (403; an agent key reads only its own, cross-agent is ent#80's grant), then the limiter on the name the gate has already validated. It gets its OWN rate knob, `OBJECTIVES_READ_RATE_LIMIT` at 60/min rather than the 240 copied from a store-only read: this route drives the container — a listing plus up to 100 small file reads through the agent door — and ten open role cards at a 30 s poll is 20/min, so 60 clears normal traffic and still stops a loop from pinning an agent-server the platform also needs for chat. A store outage is the only non-2xx below the gates (503 + `Retry-After: 30`). Everything else is a named field on a 200, because "this agent is stopped" is an answer, not an error. The model is the contract, structurally. `ObjectiveJoinRead` is the `response_model` and the service's dict is returned unchanged; a key-parity test walks that dict against every model's fields recursively, so an additive service key fails the build instead of being silently filtered out of every response — the 2026-07-27 `response_model`-is-an-allowlist trap closed by a guard rather than by remembering. Author-shaped targets (`.nan`, `.inf`, lists, bools, a 4 KB string) are pushed through the real route and parsed with `parse_constant` armed, since a bare `NaN` on the wire is precisely what blanks the card the join exists to fill. MCP `get_objectives` (Invariant #13) is `get_metrics`'s shape again: agent-scoped via `getAgentName`, no agent-target parameter to spoof, `kind: "none"` in the access policy because the backend self-gates the path agent, body returned verbatim, never throws. Its description carries the three things an agent will otherwise invent — that `gap.status` is position and not pace, that `stale: true` means record a fresh point rather than report the gap, and that an undeclared metric arrives as a named finding with the remedy (or `metric_not_declared_here`, where there is nothing for the caller to fix). It says outright not to re-derive a gap from `get_metrics` plus an objective file, because two answers to one question is the defect ent#476 removes. Docs: requirements §50 (the §3.4 grammar including `hold` and the `active` filter, the four sources and which owns what, the gap semantics table, the direction fallback matrix, the findings catalog with the fix each names, the gate order, the response shape, the bounds and why each is where it is, the zero-config path, the consumer list with the no-second-join rule, and the two known costs — the 60-file fleet canon and the two doors onto template.yaml); the feature flow gains an Objectives section with the dataflow and the PR #2927 rebase note (what `role_card.py` drops, the slim portal projection per TD-4, the limiter the portal route gains, and both Alembic landing orders); architecture rows in backend / api-endpoints / mcp-server; a guide section telling an agent that an objective names its metric BY NAME and what that implies; J12 gains 666. * fix(metrics): findings only for joined objectives, neutral direction for hold, fan-out budget, skipped-file and invalid-id findings, executable rebase note (Abilityai/trinity-enterprise#666) * merge-train: re-chain the registry revision to 0069 after dev's 0066–0068, isolate the start-hook tests' task set, drive the Alembic PG test on TEST_POSTGRES_URL (Abilityai/trinity-enterprise#477) Mechanical fixes applied on the member branch, per the merge-train note on #2942: - 0066_metric_definitions → 0069_metric_definitions on top of 0068_agent_shared_files_audience. dev landed 0066_public_user_memory_writes, 0067_agent_role_readiness and 0068_agent_shared_files_audience after this branch's last re-chain, so it was a second #2068 fork (alembic-head-watch was red). check_alembic_heads.py: 70 revisions, 1 head. - test_ent477_git_refresh_hook: the two start-hook tests gather metric_registry._inflight_refresh_tasks, a module-level set that other tests leave stale tasks in (spawned on a loop that closed before the done-callback fired). Under CI's random ordering asyncio.gather then raised 'The future belongs to a different loop'. Each test now monkeypatches a fresh set. - test_the_alembic_revision_builds_the_table_on_postgres called upgrade_to_head() on the DATABASE_URL default (SQLite), where 0004's 'ADD COLUMN IF NOT EXISTS' cannot parse; schema-parity was red on every PR in the stack that touches db/. It now points DATABASE_URL at TEST_POSTGRES_URL, resets the schema, upgrades to head and reads back. Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: make SOURCES live, hash-stable definition_hash, mcp header on git.py (Abilityai/trinity-enterprise#477) Mechanical, per the /review findings recorded on #2942: - SOURCES was a constant nobody read. _reconcile now refuses a source outside it (ValueError) before anything reaches the store, and a test drives the refusal. - definition_hash hashed the entry INCLUDING the definition_hash key that _reconcile writes into it, so hashing one list twice drifted and would have reported every metric as updated. The hash now excludes its own key; a test pins the stability. - routers/git.py gains its first-line '# mcp:' header (Invariant #13) — this PR touches three of its handlers and the file had none. Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: drop two unreferenced store helpers, one source for the dim/skew limits (Abilityai/trinity-enterprise#478) Mechanical, per the /review findings recorded on #2948: - db/metric_points.py: metric_points_remaining and build_point_row had no caller in src/ or tests/ (the sweep calls count_metric_points_candidates directly; the service builds its own row dict). - services/metric_points_service.py: MAX_DIM_VALUE_LEN and TS_FUTURE_SKEW_SECONDS duplicated METRIC_DIM_VALUE_MAX_LEN and METRIC_TS_FUTURE_SKEW_SECONDS in models.py; the service now reads the models.py values, so the wire contract has one spelling. Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: wire METRICS_READ_RATE_LIMIT into compose and .env.example (Abilityai/trinity-enterprise#479) Mechanical, per the /validate-pr config-packaging check (§4.9) recorded on #2951: the knob was read via os.getenv in routers/agent_files.py but declared in neither compose file nor .env.example, so the tuning lever was inert on every deployment. Default unchanged (240/min). Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: the cleanup suite's mock learns the metric-point accessors, hosted compose mirrors prod's METRICS block, lint-clean sys.modules poisoning (Abilityai/trinity-enterprise#478) Mechanical, surfaced by the full unit suite on the merged stack (none of these ran in CI — the stacked base never triggers backend-unit-test): - tests/unit/test_cleanup_inner_sweeps.py: _configure_db never set count_metric_points_candidates / prune_metric_points, so the ent#478 sweep stored a MagicMock in report.metric_points_pruned and the WAL-checkpoint sum raised "'>' not supported between MagicMock and int". - docker-compose.hosted.yml: test_2280_hosted_compose_parity requires the backend environment to match prod; the three METRICS_* knobs were added to prod only. - tests/unit/test_ent478_point_validation.py: bare sys.modules pop/assign/del → monkeypatch.setitem + undo (tests/lint_sys_modules.py). Co-Authored-By: Claude Fable 5.1 <[email protected]> * merge-train: the bound-widget threshold reads the registry's direction vocabulary, snapshot skip proven on a live engine, hosted compose + lint + three nits (Abilityai/trinity-enterprise#479) Per the /review findings recorded on #2951: - metric_read_service._threshold_color judged direction as 'up' / 'down', which the registry never emits (DIRECTIONS = up_good / down_good / neutral). Every declared metric therefore fell into the 'up' arm, so an up_good revenue widget turned red for EXCEEDING its critical threshold and a neutral metric was judged at all — while the tile beside it, via utils/metricFormat.js::thresholdClasses, did the opposite. The backend now spells the tile's rule: down_good breaches at-or-above, up_good at-or-below, neutral declines. The pinning test used direction='up' and was green for the wrong reason; three tests now drive both arms and neutral. - The snapshot-writer skip for a bound widget was pinned by inspect.getsource; it is now executed through the real engine (capture_dashboard_snapshot writes the plain widget and not the bound one). - docker-compose.hosted.yml mirrors prod's METRICS_READ_RATE_LIMIT line (test_2280_hosted_compose_parity). - test_ent479_freshness_rule: bare sys.modules.pop → monkeypatch.delitem. - Nits: unused Optional import in agent_server/routers/info.py, the refreshMetricDefinitions JSDoc in client.ts sat above getAgentMetrics, routers/monitoring.py gains its '# mcp:' header (Invariant #13). Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]> Co-authored-by: sim <[email protected]>
5 tasks
2 of 3 tasks
vybe
pushed a commit
to harimaruthachalam/trinity
that referenced
this pull request
Sep 29, 2026
…essage (Abilityai#3064) count_unread_by_session runs on every 20s Workspace poll, per open tab. Its message arm filters enterprise_portal_messages by the viewer, role = 'assistant', the thread and created_at past a read cursor. No index led on client_email, so the plan read every message in the install: - SQLite: `SCAN m USING INDEX idx_portal_messages_session`. - PostgreSQL: a Seq Scan once rows span more than one agent. New index idx_portal_messages_unread ON enterprise_portal_messages(client_email, role, session_id, created_at): the equality columns first, then the GROUP BY key, then the range. Index-only; no query or behaviour change. Dual track (Rule Abilityai#9): - db/schema.py INDEXES, for fresh installs on both engines; - the versioned SQLite migration `portal_messages_unread_index`; - Alembic `0081_portal_messages_unread_idx` on `0080_agent_skill_sets` (single head). Plans measured on the live query: - SQLite: SCAN m → SEARCH m USING COVERING INDEX idx_portal_messages_unread (client_email=? AND role=?). - PostgreSQL 16 (120k rows, 400 viewers, 20 agents, ANALYZEd): Seq Scan with 119,859 rows filtered, 2,269 buffers, 6.45 ms → Bitmap Index Scan with Index Cond (client_email, role), 143 buffers, 0.87 ms. Test: test_3064 EXPLAINs the SQL count_unread_by_session actually sends, which is captured at the cursor rather than copied. It asserts no scan of the message table, with a negative control proving the assertion can fail. It also covers the SQLite migration on an install that predates the index (idempotent) and the Alembic revision. It was red before the change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
9 tasks
9 of 11 tasks
trinity-ability
pushed a commit
that referenced
this pull request
Oct 5, 2026
…3247) CP1 of the replace-a-pending-ask slice. `operator_queue` gains two nullable TEXT link columns: `replaces` on the successor (the predecessor row's uuid) and `replaced_by` on the predecessor (the successor row's uuid). Both are stamped in the one per-agent locked transaction the next checkpoint adds, so each row is self-describing on every surface that holds only one of the pair. Both schema tracks (Invariant #9): SQLite entry `operator_queue_replace` and Alembic `0090_operator_queue_replace` chained after this branch's head `0089_supersede_queue_flood_backlog` — `0090` is also taken by the independent #3246 branch and open PR #3145, so expect a renumber at merge; `check_alembic_heads.py` names the fork. `schema.py` and `tables.py` DDL updated (the `disposed_by` comment gains `agent`); `_row_to_item` / `_SELECT_COLS` carry the columns; `_MACHINE_ROW_FIELDS` and the ent#715 `MACHINE_ROW_KEYS` pin are extended in the same commit. No index. Co-Authored-By: Claude Fable 5.1 <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Oct 6, 2026
…3247) CP1 of the replace-a-pending-ask slice. `operator_queue` gains two nullable TEXT link columns: `replaces` on the successor (the predecessor row's uuid) and `replaced_by` on the predecessor (the successor row's uuid). Both are stamped in the one per-agent locked transaction the next checkpoint adds, so each row is self-describing on every surface that holds only one of the pair. Both schema tracks (Invariant #9): SQLite entry `operator_queue_replace` and Alembic `0090_operator_queue_replace` chained after this branch's head `0089_supersede_queue_flood_backlog` — `0090` is also taken by the independent #3246 branch and open PR #3145, so expect a renumber at merge; `check_alembic_heads.py` names the fork. `schema.py` and `tables.py` DDL updated (the `disposed_by` comment gains `agent`); `_row_to_item` / `_SELECT_COLS` carry the columns; `_MACHINE_ROW_FIELDS` and the ent#715 `MACHINE_ROW_KEYS` pin are extended in the same commit. No index. Co-Authored-By: Claude Fable 5.1 <[email protected]>
vybe
pushed a commit
that referenced
this pull request
Oct 6, 2026
…3247) CP1 of the replace-a-pending-ask slice. `operator_queue` gains two nullable TEXT link columns: `replaces` on the successor (the predecessor row's uuid) and `replaced_by` on the predecessor (the successor row's uuid). Both are stamped in the one per-agent locked transaction the next checkpoint adds, so each row is self-describing on every surface that holds only one of the pair. Both schema tracks (Invariant #9): SQLite entry `operator_queue_replace` and Alembic `0090_operator_queue_replace` chained after this branch's head `0089_supersede_queue_flood_backlog` — `0090` is also taken by the independent #3246 branch and open PR #3145, so expect a renumber at merge; `check_alembic_heads.py` names the fork. `schema.py` and `tables.py` DDL updated (the `disposed_by` comment gains `agent`); `_row_to_item` / `_SELECT_COLS` carry the columns; `_MACHINE_ROW_FIELDS` and the ent#715 `MACHINE_ROW_KEYS` pin are extended in the same commit. No index. Co-Authored-By: Claude Fable 5.1 <[email protected]>
11 tasks
5 tasks
3 tasks
trinity-ability
pushed a commit
that referenced
this pull request
Oct 18, 2026
… caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]>
4 of 5 tasks
vybe
added a commit
that referenced
this pull request
Oct 29, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
10 tasks done
vybe
added a commit
that referenced
this pull request
Oct 31, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
vybe
added a commit
that referenced
this pull request
Oct 31, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
vybe
added a commit
that referenced
this pull request
Nov 2, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
vybe
added a commit
that referenced
this pull request
Nov 2, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
vybe
added a commit
that referenced
this pull request
Nov 2, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
vybe
added a commit
that referenced
this pull request
Nov 2, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
vybe
added a commit
that referenced
this pull request
Nov 2, 2026
…3787) * feat(eval): delegation link schema — parent_execution_id + evaluation caller columns (ent#935 M.1) Addendum A, checkpoint M.1. Dual-track (Invariant #9): - schedule_executions.parent_execution_id (nullable) - agent_evaluations.caller_agent / parent_execution_id / delegation_mode (nullable; sync|async|fan_out|reminder|loop, NULL = not delegated) - idx_agent_evaluations_caller (caller_agent, agent_name, created_at) SQLite: db/migrations.py::delegation_link (each table's half applied on its own, so a DB holding only one table never meets the caller_agent index without the column). PostgreSQL: Alembic 0100_delegation_link after 0099_agent_peer_skill_grants (single head). schema.py DDL + tables.py model updated. agent_evaluations.caller_agent registered CASCADE in agent_cleanup (the parity guard requires it; same policy as agent_peer_skill_grants). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): stamp parent_execution_id at admission behind the provenance guard (ent#935 M.2) Addendum A, checkpoint M.2. The caller's turn id arrived on two doors — X-Trinity-Execution-Id (#2392) and ParallelTaskRequest.parent_execution_id (ent#224) — and was accepted but never stored. Both row writers (/task: create_task_execution_and_activities, /chat: prepare_chat_execution) now persist it on schedule_executions.parent_execution_id, header first, body as fallback, kept ONLY when the parent row's agent_name equals the child's source_agent_name (the _inherited_channel_context provenance rule); otherwise NULL. No delegation_mode on schedule_executions — the evaluator derives it. Tests (tests/unit/test_ent935_delegation_stamping.py, real schema): a two-agent chain joins child->parent through the column; a forged parent (another agent's turn), an unknown id and a missing header store NULL, on both doors; the /chat router hand-off is pinned. Mutation: dropping the agent_name comparison turns both forged-parent tests red. test_1482_write_params re-pinned for the new TaskExecutionFields field. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): requirements §46 addendum — Tier-0 writer, checks vocabulary, sweep (ent#935 A1) FR-7 one platform:tier0 row per execution on the existing ent#366 partial unique index (target_kind='execution'), delegation columns derived from the execution row (NULL mode when sync/async is not recorded). FR-8 the checks vocabulary, the null test (bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched reports skip unattributable). FR-9 the leased sweep that writes it. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): Tier-0 writer, intent resolution and the first four gate checks (ent#935 A1) services/tier0_evaluator.py: check registry (Check id/tier/source/fn), resolve_intent (reuses #1410's unresolved-command detector) and evaluate_execution(execution_id) — takes an id only, imports no fastapi / dependencies / models.User. Gate checks: execution_exists (#2467 integrity record, NULL -> skip no_integrity_record), credential_echo (counts only; staged runtime secrets compared in memory, fail-open), validate_001 (business_status), deliverable_landed (TD-6 null test: bare Done + zero receipts fails; explicit no-op skips no_claim; window-matched report skips unattributable, never passes (TD-3); commit claim alone skips no_receipt_source). A raising check is skip:evaluator_error (class name only); evidence is counts/ids, claim excerpt <=200 chars and scrubbed. db/evaluations.py: upsert_platform_evaluation — one platform:tier0 row per execution keyed target_kind='execution' on idx_agent_evaluations_rating_target (TD-2, no migration), UPDATE-then-INSERT with the ent#366 SAVEPOINT retry; delegation columns derived from the execution row on every write (derive_delegation: fan_out_id -> fan_out, loop_id -> loop, triggered_by=reminder -> reminder, else NULL — sync vs async is not on the row). latest_tier0_for_execution, unevaluated_execution_ids (settled, bounded, terminal schedule/agent runs). db/schedules/executions.py: get_execution_receipts (asks, completed effects, metric points by id; reports by window). utils/credential_sanitizer.count_hits. database.py forwards. tables.py index comment: Tier-0 rows now use the index. Zero edits to task_execution_service.py. Tests: test_935_tier0_writer.py, test_935_tier0_checks.py (part 1, incl. the null test), test_935_intent_resolution.py — 77 passed. Mutations: dropping the reminder branch, the IntegrityError retry, the unattributable skip or the no-op skip each turn tests red. TD-2(a): a Tier-0 row with a rating-shaped quality never enters workspace_rating_tally, list_workspace_ratings_for_targets or get_workspace_rating. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): playbook_outputs gate, budget_vs_baseline signal and the gate-only headline (ent#935 A2) services/tier0_evaluator.py: - playbook_outputs (gate): every output the invoked skill declares must have left a receipt. Declared outputs from an `outputs:` frontmatter key (flat or under `trinity:`) read through the ent#183 hardened parser first, the `## Output` prose section only when none is declared (TD-5). Missing ask/effect/metric receipt, or a declared report with no report in the window -> fail declared_output_missing; window-matched report -> skip unattributable (TD-3); "Unknown command" (#1410) -> fail playbook_unresolved; a `Not done:` footer naming work -> skip declared_not_done; named skips otherwise. The skill is the library copy (_load_skill), recorded by source id + tree sha; a failing lookup is skip skill_unreadable with the exception class only. No skill text in evidence. - budget_vs_baseline (signal): cost / duration_ms / tool_call_count / context_used against the p5-p95 band of the series' last <=20 successful runs, min 5; NULL is left out, never read as zero. - headline(): gate checks only (TD-7), stored as checks_json.headline; a failing signal never moves it. db/schedules/executions.py: recent_series_metrics (schedule series; agent + playbook series, bounded scan) and the #1741 tool-call count; database.py forwards. FR-8 corrected in the same commit: headline key, the exact playbook_outputs and budget rules, and trajectory_bounds / footprint marked planned-not-built (their specified source, tool_call rows in agent_activities, is never written by the platform). Tests: test_935_tier0_checks_part2.py (35) incl. the null tests on the headline: do-nothing and claims-everything-done fail it, an honest abort passes it. Mutations: disabling the declared_output_missing fail turns 3 tests red; counting signals in the headline turns 2 red. Restored byte-identical. Zero edits to task_execution_service.py. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): leased Tier-0 sweep — 60 s cadence, fail-open lease, bounded ticks (ent#935 B.1) The deterministic evaluator's single writer path (TD-1/TD-8). A backend loop (`services/tier0_sweep_service.py`, mirroring `skills_sync_service` / the every 60 s under the Redis lease `tier0:leader` (TTL 180 s). The lease fails OPEN: no Redis or a Redis error makes the worker a leader for the tick, a contended lease skips the tick without waiting, and two leaders at once leave one row because the write is idempotent on the ent#366 partial unique index (TD-2). Nothing in the sweep sits in the terminal write path — zero edits to `task_execution_service.py` (decision 16); pinned by an import check. `tier0_evaluator.sweep` grades up to 25 settled (≥30 s), recent (≤24 h), unevaluated terminal schedule/agent runs per tick, each in `to_thread` behind a Semaphore(4) under `wait_for(10 s)`. `wait_for` cannot stop a thread, so the bound is enforced by `record_timeout`: a row every check of which is `skip: evaluator_timeout`, written only when no row exists — a late grade is never replaced by a skip, and a hung evaluation is not re-picked every tick. Wiring: start in `_schedule_watch_loops` (+13 s stagger, beside the heartbeat watch and the monitoring loop), stop in `_shutdown_background_services` (releases the lease). Both phases stay under the #1028 line/complexity pins. §46 FR-9 rewritten to describe exactly this. Tests (`test_935_sweep.py`, real schema): candidate filter, per-tick bound with continuation, never re-picks, one raising evaluation does not stop the batch, timeout row + late grade wins, off-loop execution, two sweepers racing one execution → one row, replayed terminal re-grades the same row; lease: one holder, fail-open (no Redis, Redis error), release, lapse, contended tick skipped, failing tick survives, TD-8 bounds handed to the sweep; AST wiring pin over main.py. Mutations recorded: a never-contended lease turns `test_only_one_worker_holds_the_lease` red; a non-idempotent writer (plain INSERT) turns the never-picked-again, racing and replay tests red. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 read route and the write fence on platform:tier0 rows (ent#935 B.2) Read: `GET /api/agents/{agent_name}/executions/{execution_id}/evaluation` returns the run's Tier-0 row under the agent's existing evaluation access rule (`get_authorized_agent_by_name`, uniform 404) and the ent#366 projection. Not evaluated yet, or an execution that is not this agent's, is one 404 `not_evaluated`, so the path is not an oracle over other agents' execution ids. Classified `agent_callable` in the #2996 route census (the graded agent reads its own grade — read != write) and pinned against the live app by the runtime census. Write fence (epic ent#205 AC), pinned by driving every path an agent could reach with a Tier-0-shaped body that names the platform evaluator, the execution target and all three delegation columns: the graded agent's own key, a connector key and a non-admin person are refused by the admin write route (403, no row); an admin's write is filed under `admin:<user>` with no target and no delegation and never answers the Tier-0 read; the request model has no field for the fenced columns; a Workspace rating cannot address `target_kind='execution'` (422) and its evaluator is always prefixed. AST pins: every DML on `agent_evaluations` lives in `db/evaluations.py` (+ the owner-only agent-delete cascade), the writers have exactly three callers past the facade, the evaluator and sweep take an execution id only and import no FastAPI / `dependencies` / `models`, the write route is the only non-GET route, and the MCP server has no `/evaluations` surface. Positive half: the sweep's writer path still writes, and an admin row and the Tier-0 row coexist for one execution. §46 gains FR-10 (read + fence) beside FR-9. Test harness note: the unit conftest re-imports `dependencies` between tests (`_POP_PREFIXES`), so the auth override is keyed on the ROUTER's binding of `get_current_user`, not the module attribute — otherwise the real gate runs and answers 401 in a random-order session. Mutations recorded: filing the admin write as `platform:tier0` turns `test_an_admin_write_cannot_become_a_tier0_row` red; gating the write route on `get_current_user` turns the three refusal tests red. Both restored byte-identical. Co-Authored-By: Claude Fable 5.1 <[email protected]> * feat(eval): Tier-0 checks on the execution page — gate-only headline (ent#935 C.1) ExecutionDetail.vue now shows the run's Tier-0 result, read from the B.2 route GET /api/agents/{name}/executions/{id}/evaluation. One headline from the GATE checks only (TD-7): "Checks passed" / "Checks failed" / "No gate check applied" (all skipped), with "N of M gate checks …" and the failed gates listed by id, reason and scalar evidence. Signals are listed as "recorded, not counted" observations, never worded or badged as pass/fail. A 404 not_evaluated renders "Not evaluated" (manual and chat runs are not graded); any other failure says the checks could not be loaded, with Retry. Running and queued runs ask for no grade. The panel is a child component (components/ExecutionChecks.vue) because ExecutionDetail.vue's raw_gray count is frozen at its baseline and the neutral chrome has no semantic token; the view gains one import and one element. Reads through the shared api client. Raw-colour: 0 non-gray in the new file, ExecutionDetail unchanged (16/107). Tests: tests/unit/executionChecks.mount.spec.js (10, mounted): pass, fail, all-skip, headline derived when absent, signals never pass/fail, 404 → Not evaluated, 500 → error, wired into ExecutionDetail, running run not fetched. Mutation: verdict mapping fail→pass turned 2 tests red; restored byte-identical (cmp), 10/10 green. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Tier-0 on the execution page, feature flow, sweep row; fix stale Tier-0 claims (ent#935 C.2) - requirements §46: FR-10a — the ExecutionDetail "Checks" card (gate-only headline, signals recorded-not-counted, 404 → Not evaluated). The per-schedule / per-agent "Checks passed" rate is stated as planned, not built. - feature-flows/agent-evaluations.md: Tier-0 section with the sweep → evaluator → upsert → read route → page diagram; evaluator values, quality ownership, files and tests brought up to date. - architecture/background-services.md: Tier-0 Sweep row (tier0:leader, fail-open, bounds). architecture/execution.md: pointer on why Tier-0 is not a terminal fan-out consumer. Claims the code now contradicts, fixed in the same commit: - workspace-ratings.md and requirements/core-agent.md said Tier-0 rows carry no target and so never touch the rating index; they use it (platform:tier0 / execution / <execution_id>), one row per run. - architecture/observability.md said the Tier-0 evaluator populates `quality`; it leaves `quality` NULL. - architecture/database.md listed the evaluator value as 'tier0'; it is 'platform:tier0' (plus admin:<user>, workspace:<email>). Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" rate on the analytics rollups (ent#935 C3.1) Adds `checks_passed_rate` + `evaluated_count` beside Completion on the three existing analytics payloads: per-schedule (`get_schedule_analytics`), the schedules rollup rows (`get_agent_schedules_summary`) and the agent Overview (`get_agent_analytics`). Read-only, additive, no schema change and no new route. Rate = runs whose Tier-0 gate headline passed / runs evaluated, read from `agent_evaluations` rows with `evaluator='platform:tier0'` joined on the run (inner join, capped by the existing pool cap). A skip-only row is evaluated but not passed. A run with no Tier-0 row is not evaluated and is on neither side of the rate. With 0 evaluated the rate is None, so the UI shows "—". Workspace and operator rating rows never match. Tests: test_935_checks_passed_rate.py (20). Mutation: counting a skip-only headline as passed turned 7 of them red. The four hand-rolled-schema analytics fixtures (1115, 1474, 3139, agent_analytics) now create the agent_evaluations table the accessors join. No unit test pins the envelopes' top-level key set. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(eval): "Checks passed" beside Completion on the schedule card and Overview (ent#935 C3.2) ScheduleAnalyticsCard gets a "Checks passed" tile next to Completion. The Overview completion headline and each "Schedules performance" row get the same rate as a second number. The rollup's "success" caption now reads "completion", the name ent#206 gave that number. Neutral ink only. At evaluated_count == 0 the rate reads "—", never 0%. The tooltip says "N of M runs evaluated · deterministic checks, not answer quality". Spec: checksPassedTile.spec.js (mounted, 5 tests). Mutation: making the Overview formatter render 0% at zero evaluated turned the "—" test red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * chore(design): re-freeze two raw_gray entries for the Checks passed tiles (ent#935 C3.2) ScheduleAnalyticsCard.vue raw_gray 55 -> 60 and OverviewPanel.vue 150 -> 155. This is deliberate: the AC adds a second number beside Completion in both, using the neighbours' neutral ground and ink, because no semantic ink token exists. raw_nongray stays 0. The two entries were edited by hand and named in _ent935_note, not regenerated. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(eval): Checks passed rate is built — FR-10a, feature flow, API catalog (ent#935 C3.3) §46 FR-10a now describes the rate as built and states the rule. Rate = runs whose platform:tier0 gate headline passed / runs evaluated. Skip-only rows count as evaluated, not passed. A run with no Tier-0 row is not evaluated. At zero evaluated the field is null and renders "—". Workspace and operator rows never count. The agent-evaluations feature flow names `checks_passed_rate` + `evaluated_count` and the three accessors and tiles; its "not built" line drops the rate. The three analytics rows in api-endpoints.md list the new fields. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a Tier-0 timeout row is INSERT-only and never overwrites a grade (ent#935 review I1) record_timeout checked for a row and then upserted; a grade landing in between was replaced by six evaluator_timeout skips, permanently (the run is never re-picked). The timeout row now goes through insert_platform_evaluation_if_absent: SAVEPOINT INSERT, IntegrityError means a grade is already there and it is kept, no UPDATE fallback. A late grade still re-grades a timeout row in place via the upsert. Mutation: record_timeout back on upsert_platform_evaluation turns test_a_grade_landing_between_the_check_and_the_timeout_write_is_kept red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): a no-op sign-off no longer hides a deliverable claim (ent#935 review I4) deliverable_landed checked the no-op phrase before computing claims, so 'Filed the report and sent the email. No action needed from you.' with zero receipts skipped as no_claim instead of failing TD-6's null test. Claims are computed first; a no-op phrase excuses them only when every claim word is a generic completion word (done/completed/finished). Bare 'Done' with zero receipts still fails; a pure no-op reply still skips. Red before the fix: test_a_no_op_sign_off_never_hides_a_deliverable_claim (4 cases) failed with skip/no_claim. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the claim excerpt is cut from text scrubbed whole (ent#935 review I2) _scrubbed_excerpt sliced the window before scrubbing, so a pattern-shaped or staged secret crossing either window edge left a fragment that matched neither its pattern nor its staged value, and it survived into the persisted claim_excerpt. deliverable_landed now scrubs the whole bounded scan text once (_scrub) before taking claim positions, and the excerpt is a plain slice of that text. Docstrings say what is actually true. Red before the fix: test_a_secret_straddling_the_excerpt_window_leaves_no_fragment (staged/pattern x start/end edge, 4 cases) showed the fragment. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): purging a delegating agent keeps the callee's Tier-0 grades (ent#935 review I3) AgentRef(agent_evaluations, caller_agent, CASCADE) deleted every grade an agent had delegated, i.e. other agents' Tier-0 history, changing their Checks passed rate and execution verdicts. caller_agent is initiator provenance, so it follows the source_agent_name precedent: unregistered, and listed in test_agent_cleanup_parity._EXEMPT (the regex matches it only because ent#662's agent_peer_skill_grants.caller_agent is a managed grant). Red before the fix: test_deleting_the_caller_keeps_the_callee_grade (count 0 == 1). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): skip-only Tier-0 rows are excluded from Checks passed (ent#935 review I5) The execution page reads a skip-only row as 'No gate check applied' while the rollup counted the same row as evaluated-not-passed, pulling the rate down for reasons the tooltip could not explain. evaluated_count is now the runs with at least one gate check graded (pass or fail); the rate is passed / that count, null ('—') when it is zero. No new payload key. Tooltips read 'runs with a gate check graded'; FR-10a, the feature flow and the model comments state the new rule (api-endpoints rows name the fields only, no rule to fix). Red before the fix: test_935_checks_passed_rate (6 cases). Frontend mutation: the old tooltip string turns checksPassedTile.spec.js red. Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(eval): the sweep counts an evaluation that wrote no row as failed (ent#935 review I6) sweep() discarded evaluate_execution's None (not eligible / write failed) and counted it as evaluated, so the only tick-level log line over-reported and a run whose write fails every tick read as evaluated for 24 h. It now returns 'evaluated' only when a row came back, else 'failed'; the existing 'Tier-0 sweep: {...}' tick log carries the count. Red before the fix: test_an_evaluation_that_wrote_no_row_counts_as_failed ((2, 0, 0) == (1, 1, 0)). Refs Abilityai/trinity-enterprise#935 Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Trinity Agent (trinity) <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
This was referenced Nov 9, 2026
10 tasks done
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.
No description provided.