Skip to content

feat(workspace): the role card in Agent details — role, objectives with metric freshness, readiness (abilityai/trinity-enterprise#527) - #2927

Merged
vybe merged 12 commits into
devfrom
feature/ent527-role-card
Sep 22, 2026
Merged

vybe merged 12 commits into
devfrom
feature/ent527-role-card

Conversation

@dolho

@dolho dolho commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes abilityai/trinity-enterprise#527 (the Role + Readiness half; the relationship line waits for ent#500 as the issue allows) · implements the #663 1.0 gate. OSS-core (Workspace).

What

When a companion has a role (Tandem, ent#497), the Info rail's Agent details show a Role card: the role it fills, the objectives it owns or supports with each metric's value / target / freshness, the viewer's relationship, and its readiness. Framework §8's organisation UI shrunk to one agent — files are truth, the card is a projection.

Read through the platform, never a second store. client_portal/role_card.py reads on every request, through the agent door (the same one the Files tab uses): template.yaml (x-role: {role, status, seat} — what the #511 wizard writes — and x-canon.clone_path, default canon), <canon>/roles/<id>.yaml, <canon>/objectives/*.yaml (§3.4 grammar: owner: role:<id> or supporting_agents naming this agent), and the agent's own /api/metrics (metrics.json + last_updated). Ids/paths that reach a read are validated (no traversal), text is bounded, objectives ≤ 20. Every failure is named: no x-role → no card (panel unchanged, AC 5); missing / invalid / unreadable role file → role.error with copy that says what to do; stopped agent → "reads its files when it runs".

Freshness is honest (quality bar #4). A metric is stale when its value is missing, unstamped, or older than the framework's 30-day bound (§3.5); it renders as stale beside its last value, never as current.

Readiness is the owner's stamp (#663, ruled 2026-09-20). x-role.status is agent-writable, so it cannot say a companion is ready. New agent_role_readiness (agent_name PK, status, changed_at, changed_by; SQLite agent_role_readiness_table + Alembic 0065_agent_role_readiness; CASCADE in AGENT_REFS). Effective state = the stamp if present, else calibrating; a template that says ready with no stamp is shown as calibrating with "no owner has stamped it — only the owner's stamp counts". POST …/role/readiness is gated on the platform's owner of the agent record (get_owned_roster; creator, not an assignment kind): named 403 readiness_owner_only for a shared user, portal-token principals are never owners, the agent has no route (its key gets 403 at the portal door). The card shows state, since when, by whom. The flip records — the confirm says it does not switch any schedule on. While calibrating: the viewer's own walkthrough count (asks in their Main capped at ten; their thumbs-down).

Relationship: null until ent#500 → rendered as "no assignment recorded", never blank.

Acceptance criteria

  • Role section when x-role / role file exists: name, mission, path — test_the_role_reads_from_the_canon_file_through_the_agent
  • Objectives with metric / target / value / freshness; stale marked stale — test_objectives_are_the_ones_the_role_owns_or_this_agent_supports, test_a_stale_or_missing_metric_is_marked_stale_never_current, test_a_metric_with_no_freshness_stamp_at_all_is_stale
  • Your relationship: stated "no assignment recorded" (ent#500 pending) — mounted spec
  • Readiness with date + who; calibrating shows walkthrough progress — test_the_owners_stamp_wins_and_names_who_and_when, test_walkthrough_counts…; fix(agent-lifecycle): stop showing credentials_injection: failed for subscription agents (#612) #663: owner-only flip, agent never — test_only_the_owner_may_flip_and_the_refusal_is_named, test_without_an_owner_stamp_the_template_word_is_calibrating_whatever_it_says
  • Degrades honestly: no role → no section; failed role file says so — test_an_agent_with_no_x_role_has_no_card, test_a_role_file_that_fails_to_load_says_so, test_a_transport_failure…
  • Platform-authenticated door only; canon read through the platform — the route is on the portal principal; no second store

Verification

pytest unit/test_ent527_role_card.py                               20 passed
+ schema_parity, alembic guards, auth wiring, models_centralized     64 passed
-k "cleanup|agent_refs|rename_cascade|portal_agent_page|ent523|ent547"  121 passed
check_alembic_heads → 1 head · check_alembic_parity → PASS
vitest 142 files / 3245 (incl. portalAgentRole.spec.js 8, mounted) · check:tokens OK · vite build OK
/verify-local --skip-unit --skip-agent → PASS (build, boot+health, integration)

Live (dev stack, PostgreSQL, sidekick): Alembic 0065_agent_role_readiness applied at boot. Planted x-role {sales-lead, status: ready} in sidekick's template, canon/roles/sales-lead.yaml, two objectives (one owned, one a CFO's) and metrics.json. GET …/role: role read from the file, only the owned objective listed, strategies_developed 7/12 as of just now, close_rate stale (never pushed), readiness calibrating + unstamped_ready despite the file saying ready. Info rail, light + dark: card renders as designed; Mark ready → confirm → stamped ready · since just now · by <owner> (PG row present); agent's own MCP key at the door → 403; owner flips back → calibrating; done → 422. Screenshots on request.

⚠️ Alembic: #2920 and #2924 each also add a 0065_* off 0064; whichever lands later must re-chain (alembic-head-watch flags the fork).

Docs

docs/memory/requirements/core-agent.md §5.36 (new), feature-flows/workspace-role-card.md (new, indexed), architecture/{workspace,database}.md.

🤖 Generated with Claude Code

dolho and others added 3 commits September 21, 2026 10:48
…name (#2914)

Assigning a library skill whose name matched a `.claude/skills/<name>/` the
agent wrote itself overwrote the agent's copy, gitignored and untracked the
directory, and buried an `unmanaged_dir_overwritten` warning in the assignment
response. The library and the agent's repo share one flat namespace on the
agent side, so a name match is not proof of the same skill — the library
silently won.

The inject path now refuses a directory that exists without the platform's
`.trinity-skill.json` marker before a byte is staged: no archive, no restore,
no `.gitignore` line, no untracking, not listed under CLAUDE.md Platform
Skills. `force` (manual Sync) does not override it; a platform-managed dir
keeps upgrading in place; an unreadable probe keeps the pre-existing fail-open
direction. The per-skill status is `conflict` — neither `injected` nor
`failed` (overall `success` stays true so the fleet re-inject does not alarm on
a standing conflict every auto-sync); `skills_conflict` + `conflicts[]` carry
it, and `deliver_assigned` reports `conflict` / `partial` + `conflicts[]`.

The verdict is recorded on the assignment row (`agent_skills.delivery_status`,
SQLite `agent_skills_delivery_status` + Alembic `0065`), carried across the
bulk-replace PUT for retained names, cleared by the next injection where the
name lands, and gone on unassign. The Skills tab reads it off the rows so the
badge, the explanation (which skill, the agent's own copy is what runs) and an
inline "Unassign library skill" action show on a fresh load; `inject()` re-reads
the rows so a resolved conflict clears without a reload. MCP passes the
delivery block through, `sync_agent_skills` names conflicts on its success
branch, and `get_agent_skills` carries `delivery_status` per row.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…; delivery copy and draft fixes (#2914)

Merge-train review on #2920: marker-absence was read as "the agent authored
this" and refused, but the platform itself wrote marker-less directories on
two live paths — the pre-#384 legacy fallback (SKILL.md only) and a restore
that dropped the meta member — so each would have turned its own package
into a permanent, unrepairable conflict on the next sync (AC#6 violated).

Both are closed at the write: `_legacy_fallback` writes the marker beside
SKILL.md (manifest = what was actually written), and `_restore_skill` writes
the marker back directly when the agent's `restored` list lacks it
(`marker_written_directly`). If the marker cannot be written the injection
is reported `failed` (`marker_not_written`; the legacy write is rolled back)
rather than a half-managed directory. Five tests cover the two paths, their
failure arms, and the legacy-marker round trip that closes AC#6.

Also from the review: `deliveryText` grammar ("its own a skill") with a real
plural arm; the `not_delivered` arm now names conflicts beside the failure
it retries; the Skills tab resets its draft only when the assigned SET
changes, so a Sync (which re-reads the rows for the verdict) no longer
wipes unsaved ticks; the conflict copy says "a directory the platform did
not create — usually a skill it authored" rather than asserting authorship.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@dolho dolho added priority-p1 Critical path type-feature New functionality theme-ui-ux Theme: UI/UX labels Sep 21, 2026
@dolho

dolho commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Screenshots — Workspace › sidekick › Info rail (local dev, PostgreSQL, PR branch mounted)

Hosted here (GitHub's API can't take image uploads; private artifact — share from its menu for reviewers): https://claude.ai/artifact/WNYZ3Bpvj1C5vemNCxwVwr

1 · Calibrating, unstamped (light) — the agent's template.yaml says x-role.status: ready; the card shows calibrating with "The agent's file says ready, but no owner has stamped it — only the owner's stamp counts." Role: Sales Lead · active, mission, canon/roles/sales-lead.yaml, seat. Objectives: only the one the role owns (the CFO's is not listed); strategies_developed 7 / 12 · as of just now, close_rate — / 0.3 · stale (never pushed). Your relationship · no assignment recorded. Walkthrough 4 of 10 asks. Mark ready offered (viewer is the owner).

2 · Dark theme — same card on the dark rail.

3 · After the owner's flip — confirm ("does not switch any schedule on") → ready · since just now · by <owner>, agent_role_readiness row in PG, control becomes Back to calibrating; the walkthrough line disappears (calibrating only).

Also exercised, not pictured: sidekick's own MCP key at the door → 403; owner flips back → calibrating; status: done → 422.

Files (PNG, 2× DPR) saved locally at ~/Desktop/abilityai/ent527-screenshots/01–03*.png — drag them into this thread if you want them inline.

@dolho

dolho commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author
image

@dolho
dolho requested a review from vybe September 21, 2026 11:37
dolho and others added 6 commits September 21, 2026 14:44
…ds and writes their memory (Abilityai/trinity-enterprise#637)

A role companion's proactive brief is a scheduled run, and a scheduled run
could not touch an individual user's memory: `write_user_memory` refused every
`schedule` trigger, so a brief could not carry the open loops and commitments
that make the next brief better than the last. That gap is what forced "one
agent per seat"; operator ruling R26 removed it.

The seat is ent#498's address, read off the execution row, never sent. The
ent#498 stamp already writes `source_channel='portal'` +
`source_channel_client=<email>` after the roster and block checks;
`services/schedule_seat_memory.seat_for_execution` reads it back for a
`schedule`-triggered row and nothing else, and `routers/public_memory.py`
accepts the write for exactly that case. `source_user_email` is deliberately
not stamped — `client_portal/work` reads it as "work I started" and two
stream-ownership checks key on it. No address → refused as before, now saying
"names no one".

The run reads before it writes: the tool is whole-blob replace, so the
internal dispatch composes the seat's MEM-001 memory block plus a seat note
into `execute_task(system_prompt=…)` on both branches, only after the stamp
landed. The public persona prompt is not folded in.

One write boundary, now with history: `db.write_public_user_memory_agent_notes`
replaces the notes and records `public_user_memory_writes` (previous + new,
execution, trigger, schedule) in one transaction — ent#419's screen lands
there once, and its rollback layer is this table. The Workspace agent details
gain "What it remembers about you" (`PortalAgentMemory.vue`,
`GET /agents/{name}/memory`) listing the writes with schedule name and time,
and Undo (`POST …/memory/writes/{id}/undo`) — latest-first, a named 409 for
a later write, uniform 404 for a foreign id. Dual-track migration (SQLite
`public_user_memory_writes_table` + Alembic `0065`), CASCADE in AGENT_REFS.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…erve the same seat (Abilityai/trinity-enterprise#637)

The manual trigger stamps triggered_by='manual' with the operator's own
source_user_email (#1970); the brief is still addressed to the seat, so the
seat resolver keys on a real schedule_id + the ent#498 portal stamp across
all three fire paths and never consults source_user_email.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…bilityai/trinity-enterprise#637)

Found live: the Workspace projection keyed the write's kind on
triggered_by == 'schedule', and a Run-now fire is 'manual', so the seat's
own write rendered as "In a conversation". The boundary records schedule_id
only for a seat run, so that is the key. Pinned with the projection test
and the named-refusal test.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…065 — the three 2026-09-21 schema PRs are stacked (Abilityai/trinity-enterprise#637)

Three open PRs each added a 0065_* off 0064, which alembic-heads reads as
three heads and `upgrade head` would apply nothing. #2924 now stacks on
#2920 (base branch fix/2914-skill-name-conflict) and its revision is
0066 off 0065_agent_skills_delivery_status. The migrations.py append
collision is resolved by keeping both entries, #2920's first.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…th metric freshness, readiness (Abilityai/trinity-enterprise#527)

When a companion has a role (Tandem, ent#497), the Info rail shows a Role
card: the role it fills, the objectives it owns or supports with each
metric's value / target / freshness, the viewer's relationship, and its
readiness. Framework §8's organisation UI shrunk to one agent — files are
truth, the card is a projection. The Role + Readiness half; the
relationship line reads ent#500's assignment when it lands and states "no
assignment recorded" until then.

Files are truth, read through the platform, never a second store:
`client_portal/role_card.py` reads template.yaml (`x-role`, `x-canon`),
`<canon>/roles/<id>.yaml`, `<canon>/objectives/*.yaml` and the agent's own
`/api/metrics` through the agent door on every request; ids and paths that
reach a read are validated, text is bounded, and every failure is named
(`role.error`, `unavailable`) — no `x-role` means no card at all. A metric
is stale when its value is missing, unstamped, or older than the
framework's 30-day bound, and stale renders as stale, never as current.

Readiness is the agent owner's stamp (#663, ruled 2026-09-20).
`x-role.status` is agent-writable, so `agent_role_readiness` (dual-track:
SQLite + Alembic 0065, CASCADE in AGENT_REFS) holds the state, when it
changed and who flipped it; a template that says `ready` with no stamp is
shown as calibrating with the note that no owner stamped it. The flip is
`POST …/role/readiness`, gated on the platform's owner of the agent record
(named 403 for everyone else, no route for the agent), behind a confirm
that says it does not switch any schedule on. While calibrating the card
shows the viewer's own walkthrough count (asks in their Main, capped at
ten, and their thumbs-down).

`PortalAgentRole.vue` is mounted-tested (#2918); the backend card is
driven through a fake agent door; the stamp against a real SQLite file.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@dolho
dolho changed the base branch from dev to feature/ent637-schedule-user-memory September 21, 2026 11:49
@dolho
dolho force-pushed the feature/ent527-role-card branch from 20f8588 to 43b1586 Compare September 21, 2026 11:49
@dolho

dolho commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

merge-train prep (mechanical): rebased onto feature/ent637-schedule-user-memory and retargeted to it (stack: #2920 → #2924 → #2927). Revision is now 0067_agent_role_readiness off 0066_public_user_memory_writes (43b158637); the same-tail appends in database.py, migrations.py, schema.py, tables.py, agent_cleanup.py, the portal models/router, clientPortal.js, PortalAgentDetails.vue and two architecture docs were resolved keep-both (#2924's first). Merge order: after #2924. Retarget to dev once it lands.

@vybe

vybe commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

PM note (operator ruling 2026-09-21, recorded on ent#476): business metrics now have one read path and one stale rule on the platform — GET /api/agents/{name}/metrics re-backed by metric_points (ent#479), stale = no point within 2× the declared cadence. This PR's freshness (the metrics.json last_updated stamp with the framework's 30-day bound) is the definition being retired, and the objective ↔ metric join it builds in role_card.py moves to a shared read (new sub-issue of ent#476, filed today).

Two acceptable paths, operator's preference is the first:

  1. Sequence behind ent#479 — both are on the 1.0 floor, all claimed by the operator today; rebase the card onto the endpoint and the shared join when they land.
  2. Ship as interim — merge as is, with the swap named in ent#479's acceptance (already added) and the 30-day rule marked interim in docs/memory/feature-flows/workspace-role-card.md.

Nothing else in the PR changes (readiness flip, x-role, role file read stay as designed).

vybe pushed a commit that referenced this pull request Sep 21, 2026
…s-wide caplog, stale release allowlist (#2935)

* fix(tests): three reds that keep CI honest-but-wrong — a guard race, a process-wide caplog, and a stale release allowlist

Three failure classes have been redding `backend-unit-test` on dev and the
regression diff on unrelated PRs (#2920, #2924, #2927, the 09-18 train):

1. `test_subprocess_pgroup` — `signal_guard.guarded_killpg` walked the
   group's members, then read each member's cgroup; the harness parent
   exiting in between (that IS the scenario under test) made `_cgroup_of`
   answer None, which read as "outside the session cgroup", and a kill of
   a group that was entirely ours a millisecond earlier was refused.
   Membership is now decided per LIVE member: a pid that vanished (or is a
   zombie) is not a member. A live pid whose cgroup cannot be read stays
   foreign — fail closed, unchanged. Two tests pin both halves; reverting
   the guard turns the race test red.

2. `test_2789…test_retry_budget_is_logged_with_its_cause` asserted over
   EVERY caplog record in the process, so a background task left by an
   earlier test (order-dependent under a random seed) logging an unrelated
   ERROR read as `['ERROR', 'WARNING'] == ['WARNING']`. It now asserts over
   the module's own logger.

3. `test_2814_workflow_trigger_parity` — every ACCEPTED_UNTIL_RELEASE entry
   is declared on `main` since the v0.9.5 cut and the guard has said
   "prune these" on every run since. Pruned, as the guard was designed to
   demand.

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

* fix(tests): finish the caplog narrowing — six process-wide reads survived

`mine()` was introduced to stop a background task's unrelated record from
reading as this test's own, and applied at four sites. Six reads of the
process-wide `caplog.records` survived in the same function, after the last
`mine()` call — including `:523`, the exact shape the fix was written for,
and two `assert not caplog.records` that any stray record from any logger
reddens.

Verified by negative control: with an unrelated ERROR emitted inside the
third phase's `caplog.at_level` window, the pre-fix assertions fail at
`assert "30s already spent" in caplog.records[0].message`; with `mine()`
they pass. `caplog.records` now appears once, in `mine()` itself.

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

* fix(tests): _is_gone fails closed on an unreadable status, per its docstring

`_is_gone` returned True for every OSError, so a LIVE pid whose
`/proc/<pid>/status` cannot be read (EACCES under a `hidepid=` mount, a
malformed line) was classified as gone, dropped from `live`, and the
`killpg` proceeded. The docstring two lines above states the opposite
contract: "a LIVE pid whose cgroup we cannot read is treated as foreign
(fail closed)".

Only the vanished-pid case is `gone` — FileNotFoundError. Every other
OSError/IndexError now keeps the pid in `live` so the cgroup check can
refuse the kill. This guard replaces os.kill/os.killpg for the whole unit
suite and exists because a mis-fire SIGKILLed a developer's desktop twice.

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

---------

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

vybe commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Migration numbering heads-up (orchestrator, 2026-09-22): PR #2942 (ent#477 declared-metric registry) lands ahead of this PR by operator ruling and carries 0066_metric_definitions ← 0065_agent_skills_delivery_status. This PR's Alembic revision must renumber behind it before merge — 0067_public_user_memory_writes ← 0066_metric_definitions for #2924 and 0068_agent_role_readiness ← 0067_public_user_memory_writes for #2927 — and run scripts/ci/check_alembic_heads.py src/backend/migrations/versions on the merged graph (the head-watch job is advisory). Recorded on ent#476.

@vybe

vybe commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Correction to the numbering note above (orchestrator, 2026-09-22): ent#478 (0067_metric_points) lands right behind ent#477 as part of the same stacked chain, so this PR renumbers behind 0067, not 0066 — #2924 → 0068_public_user_memory_writes ← 0067_metric_points, #2927 → 0069_agent_role_readiness ← 0068_public_user_memory_writes. Same pre-merge check: scripts/ci/check_alembic_heads.py src/backend/migrations/versions on the merged graph. Sorry for the two-step.

trinity-ability pushed a commit that referenced this pull request Sep 22, 2026
…ule, 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]>
@vybe
vybe changed the base branch from feature/ent637-schedule-user-memory to dev September 22, 2026 12:14
sim and others added 2 commits September 22, 2026 13:15
# Conflicts:
#	docs/memory/architecture/database.md
#	docs/memory/architecture/workspace.md
#	docs/memory/learnings.md
#	src/backend/client_portal/models.py
#	src/backend/client_portal/router.py
#	src/backend/database.py
#	src/backend/db/agent_cleanup.py
#	src/backend/db/migrations.py
#	src/backend/db/schema.py
#	src/backend/db/tables.py
#	src/frontend/src/components/portal/PortalAgentDetails.vue
#	src/frontend/src/stores/clientPortal.js
#	tests/unit/test_ent637_schedule_seat_memory.py
… — mechanical, per the merge-train note on the PR

The PM ruling of 2026-09-21 (recorded on ent#476) allows shipping the card
as-is only with the 30-day rule marked interim in the feature flow, pointing
at the ent#479 shared metrics read that replaces it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vybe

vybe commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-09-22) — what was pushed to this branch, and why

Validated at lane B + schema (/validate-pr, /review): no CRITICAL; role_card.py, db/role_readiness.py and the SQLite migration are executed by tests, PortalAgentRole.vue is mounted in its spec. Two mechanical commits pushed here so they survive to the squash:

  1. eb57345dc merge of origin/dev — feat(schedules): a schedule that names a user runs as that seat — reads and writes their memory (abilityai/trinity-enterprise#637) #2924 (this PR's base) squash-merged as 5b1e42638, so all 13 shared files echo-conflicted on feat(schedules): a schedule that names a user runs as that seat — reads and writes their memory (abilityai/trinity-enterprise#637) #2924's own text. Every one was resolved to dev's text plus this PR's delta and proven file-by-file: git diff origin/dev now equals git diff <#2924 tip> <this tip> exactly; learnings.md and the ent#637 test carry no delta vs dev. Retargeted to dev.
  2. bfb4c4e1a interim marker — the PM ruling of 2026-09-21 allowed shipping as-is only with the 30-day freshness rule marked interim in docs/memory/feature-flows/workspace-role-card.md, pointing at the ent#479 shared metrics read that replaces it. Added; nothing else in the PR changed.

Alembic numbering: the 0069 renumber ruled earlier is not applicable yet — #2942 / #2948 are still drafts, so this lands as 0067_agent_role_readiness ← 0066_public_user_memory_writes and the metric-registry pair re-chains behind it. Merged graph: 68 revisions, 1 head. Body patched to Fixes abilityai/trinity-enterprise#527 (the PR body's prose still says 0065; code and docs say 0067).

Left for the author (need intent, not blocking): (a) role_card.py:214 caps the objectives directory listing at 20 alphabetically before filtering to this role — a canon with more objectives can show fewer than the role owns, with no truncated marker; (b) role.stale fires only when review_by is more than 30 days past, while the badge reads "past review"; (c) readiness.changed_by and seat deliver the owner's / seat's email to portal-token principals — the first portal payload to do so; (d) db/role_readiness.py UPDATE-then-INSERT is not atomic on PostgreSQL, so a double-submit on a first flip can 500 rather than refuse by name; (e) clientPortal.js sets roleError on a failed card GET but the component never renders it, so a failed load reads as "no role"; (f) metric values only surface when template.yaml also declares metrics: (/api/metrics returns has_metrics: false otherwise), which the fake client never exercises — relevant to the ent#477/#479 handover.

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

merge-train (2026-09-22): validated at lane B + schema (/validate-pr, /review), no CRITICAL; dev merged on the branch with every echo conflict proven against the true delta, interim marker landed, all checks green on bfb4c4e.

@vybe
vybe merged commit 742b20c into dev Sep 22, 2026
28 checks passed
trinity-ability pushed a commit that referenced this pull request Sep 22, 2026
…ityai/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.
webmixgamer added a commit that referenced this pull request Sep 22, 2026
…d after #2920/#2924/#2927

Content of both tracks is unchanged; only the Alembic parent moves so the
version line resolves to one head again (Invariant #3, #2068). It was chained
on 0064 while 0065–0067 were still open PRs; they have all landed on dev.

Refs Abilityai/trinity-enterprise#549

Co-Authored-By: Claude Fable 5.1 <[email protected]>
vybe pushed a commit that referenced this pull request Sep 22, 2026
…ai/trinity-enterprise#549) (#2936)

* fix(files): a shared file is for the person the turn was for (Abilityai/trinity-enterprise#549)

`agent_shared_files` was scoped by agent alone, so the Workspace Files tab
listed every active share of an agent -- download link included -- to everyone
on its roster: a file made in one person's chat appeared in another person's
tab. Third occurrence of one class (asks, reports, now files): a table scoped
by an owning entity gains a per-person dimension, and a reader written before
the column cannot be neutral about it.

A share now has an addressee. Three nullable columns on both migration tracks
(`addressed_to_email`, `addressed_to_channel` -- display only --,
`audience_source`); NULL email and NULL channel is the owner only, which is
also what every existing row becomes, so there is no backfill.

The platform decides the addressee; the agent does not choose.
`services/turn_audience.py` keeps two questions apart. Given a turn, who is it
for -- pure, table-driven over columns every entry path already stamps, with an
allow-list of channels. And which turn did this call come from -- the hard one:
an MCP call carries the agent's key and nothing about the turn, so the only
link is an execution id the agent types, and a resumed session cites ids out of
its own history (observed live: a turn 22 minutes old). The rule therefore
needs positive evidence: only the agent's own key; the cited id must be this
agent's; an agent-to-agent child is nobody; otherwise the id proves the
CONVERSATION and never the person, and that conversation's running direct turns
must agree on who it is. Every "could not tell" is the owner only, so the
failure direction is under-share. The shortcut that must not come back is
"the agent has exactly one running turn, so take it": a web-terminal session
holds the agent's key, has no execution row, and would hand an operator's file
to whichever client happened to be mid-conversation.

On a channel turn the resolver reads `source_channel_client`, which the router
now stamps only for a verified speaker in a one-to-one chat. In a group the
verified email is the unlocker's, set once per group and not per speaker.

- One override: `audience_email`, checked with the reader's own roster
  predicate; an off-roster address is refused by name and nothing is stored.
- The addressee joins the effect key, so re-addressing a file within one turn
  is a second share rather than a silent replay; the key is hashed and the
  replay snapshot carries no address, so `idempotency_keys` never holds one.
- The Workspace Files tab narrows in the query to the viewer, plus the
  owner-only rows for the agent's owner; an unidentifiable viewer matches
  nothing. The owner's Sharing panel lists everything, says who each file is
  for, and withholds the addressee from key-authenticated callers.
- WhatsApp media and voice notes are addressed by the platform code that
  already holds the recipient.
- `share_file` returns `visible_to_requester` / `visibility_note` (the names
  `set_canvas` uses) and never an address the platform resolved; the guidance
  lives in the tool description, since the prompt section is dropped at the
  minimal tier.

Unchanged and stated: the `?sig=` link remains a bearer credential -- the
audience governs the listing, not the download.

Tests: 87 in tests/unit/test_ent549_file_audience.py, built on real-SQLite
write-to-read round trips (every earlier share test mocked the persist step and
every listing test seeded by INSERT, so nothing crossed write to read), plus
mcp-server and frontend helper tests. 33 call-site mutations, all red, run in
isolated scratch copies; the battery is what found a vacuous test
(`column == None` compiles to `IS NULL`, and the table was empty).

Fixes Abilityai/trinity-enterprise#549

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

* fix(files): name the platform-injected id slot so CodeQL does not read it as a secret

CodeQL's sensitive-data heuristic classifies any identifier containing
"trusted" as secret material. The unused slot for a platform-injected execution
id was named `trusted_execution_id`, and that value reaches two existing log
lines in `idempotency_service.resolve_and_validate_execution` that print an
execution id -- so the first push raised two HIGH
`py/clear-text-logging-sensitive-data` alerts on a file this change never
touched. An execution id is not a secret; the alerts were true to the naming
heuristic and false to the data.

Renamed to `platform_execution_id` (and the local to `platform_turn`), which is
also what the docs already call it. No behaviour change. A comment at the
declaration says why, so the next reader does not name it back.

Refs Abilityai/trinity-enterprise#549

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

* docs(learnings): an identifier named trusted_* is a CodeQL secret source

A new data flow into an existing log line raises the alert on a file the PR
never touched; the fix is a rename at the source, not a dismissal.

Refs Abilityai/trinity-enterprise#549

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

* fix(migrations): chain 0068 onto 0067_agent_role_readiness, dev's head after #2920/#2924/#2927

Content of both tracks is unchanged; only the Alembic parent moves so the
version line resolves to one head again (Invariant #3, #2068). It was chained
on 0064 while 0065–0067 were still open PRs; they have all landed on dev.

Refs Abilityai/trinity-enterprise#549

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

* docs(learnings): move the two ent#549 lessons into fragments (#2945 convention)

dev now takes new ledger entries as one file per lesson under
docs/memory/learnings/, folded into learnings.md at the release cut, so
same-day PRs stop conflicting on the ledger's tail. The two entries this
branch had appended to learnings.md move there unchanged; learnings.md is
byte-identical to dev again.

Refs Abilityai/trinity-enterprise#549

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

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
vybe pushed a commit that referenced this pull request Sep 22, 2026
… turn the #2927 rebase note into the ent#676 follow-up note (abilityai/trinity-enterprise#666)

Mechanical, per the /validate-pr findings recorded on #2953:

- OBJECTIVES_READ_RATE_LIMIT was read via os.getenv in routers/agent_files.py
  and declared nowhere (both compose files, the hosted mirror, .env.example)
  — §4.9. Default unchanged (60/min).
- docs/testing/JOURNEYS.md regenerated from the merged catalog
  (test_2338_journey_catalog was red on the merged stack).
- The feature flow's 'rebase note for PR #2927' assumed ent#666 would land
  first. #2927 landed first, so the role-card cut-over (drop its own join and
  30-day metrics stale rule, slim portal projection, shared limiter key) is a
  follow-up on dev — filed as trinity-enterprise#676 — and the two Alembic
  orders it prescribed are obsolete: the train re-chained the metrics
  revisions as 0069/0070 behind dev's 0066–0068.

Co-Authored-By: Claude Fable 5.1 <[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]>
vybe pushed a commit that referenced this pull request Oct 1, 2026
…lityai/trinity-enterprise#676) (#3132)

* feat(workspace): the role card reads the objective ↔ metric join (Abilityai/trinity-enterprise#676)

The Workspace role card (ent#527) shipped with its own objective ↔ metric
join and a 30-day metric staleness rule over the agent's metrics.json. The
platform's one join (ent#666) and one stale rule (ent#479, 2x cadence)
landed after it, so the join was spelled twice and the card's numbers came
from a source that has answered 410 since ent#479.

- role_card.py drops its join, its metric staleness and the /api/metrics
  read, and calls objective_join_service.read_objective_join with the
  template and client it already holds. is_stale / STALE_AFTER_DAYS remain
  for the role file's review_by only.
- The card serves a field-picking projection: a finding crosses as its
  code, never the operator sentence, an objective file path or the role
  owner. The Workspace holds its own sentence per code.
- No objectives is silent only when it is true. objectives_error names a
  door that died, a slow read, files that would not read, a store failure
  and a refused budget; the role, readiness and the owner's flip survive
  each.
- One budget, two doors: services/objectives_read_budget.py spells the
  agent_objectives_read key, limit and window once. The operator route
  answers 429; the card never does, because the agent can empty the bucket
  through its own get_objectives and the card carries its owner's control.
  A per-viewer cap (20/min per agent) is spent first.
- PortalAgentRole.vue renders actual/target by declared type, gap.status
  as a badge and freshness from the backend's verdict.

Decided at plan review, against the issue's acceptance line "returns 429
under the shared key": a refused read is a 200 without objectives.

Tests: tests/unit/test_ent676_role_card_join.py (the projection's key sets
as literals, the card through the real join, the two doors on the real
in-process limiter), the one-stale-rule test extended to role_card.py, and
the mounted spec for every gap, freshness, finding and error state.
Mutations: 10 on role_card.py / router.py and 7 on the component, each
turning a named test red.

Refs Abilityai/trinity-enterprise#676

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

* feat(workspace): the Role block sits above "Suggested for you" (ent#527 placement follow-up)

Decided at the Abilityai/trinity-enterprise#676 eyeball: in the Info tab
the Role block (role, objectives, relationship, readiness) moves to
directly after the agent's description and before the suggestions. The
reading order is identity, then purpose and state, then actions. The
placement itself came from ent#527 (#2927), so this is its own commit.

The card renders only for a companion with a role, so every other agent's
panel is unchanged.

Test: portalAgentRole.spec.js mounts PortalAgentDetails and asserts the
Role section precedes the suggestions section in the DOM; it was red
before the move.

Refs Abilityai/trinity-enterprise#527, Abilityai/trinity-enterprise#676

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

* Revert "feat(workspace): the Role block sits above "Suggested for you" (ent#527 placement follow-up)"

This reverts commit 649400a.

The /review of PR #3132 found that the Role block renders nothing until its
role read answers, and that read includes the container fan-out, while
"Suggested for you" paints its skeleton at once. Above the suggestions, a
companion's Role block therefore arrived late and pushed the suggestions
and their buttons down the panel (design-system principles 4 and 30). Below
them, its arrival only moves the sections under it. Decided at review: move
it back.

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

* docs, tests: correct what PR #3132's review found stale (Abilityai/trinity-enterprise#676)

- docs/user-docs/sharing-and-access/workspace.md still told Workspace users
  a metric goes stale after 30 days. It now states the 2x cadence rule, "no
  points yet", the target badges, the finding line and the named failed read.
- architecture/backend.md said the role card imports `freshness`; it
  reaches it through the objective join. lifecycle-observability.md §50.6
  sized the budget on "ten role cards polling at 30 s"; the card never polls.
- workspace-role-card.md claimed no objectives is "only ever silent when it
  is true". It now says which failures name themselves, that a file-level
  failure cannot be attributed to a role, and that a role-file error stops
  the card before the objectives are read.
- test_ent666_objectives_route: the 403-before-limiter test patches the seam
  the route calls (`objectives_read_budget.enforce`), not `rate_limiter`
  beneath it. Mutation: moving the limiter above the self-gate turns it red.
- test_ent676: the two-doors fixture pins the limit its arithmetic uses.
- A learnings fragment: the flow sync does not reach docs/user-docs/.

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

* fix(workspace): spend the objectives budget only when the card reads objectives (Abilityai/trinity-enterprise#676)

PR #3132's review (both independent reviewers) found the portal route
deciding admission before the card was built. Every Info-tab open therefore
spent one viewer token and one shared `agent_objectives_read` token, even
for an agent with no role, a stopped agent or a broken role file, none of
which reads an objective.

The router now passes the same two checks, in the same order, as a
required `admit_objectives` callable. `build_role_card` calls it once, after
the role file has been read and just before the join. The builder stays
HTTP-free (Invariant #1), and there is still no default.

Test: test_a_card_that_reads_no_objectives_spends_no_budget (no role, role
file missing, bad role id, stopped). Mutation: asking at the top of the
builder turns all four red.

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

* fix(workspace): the per-viewer objectives cap is a third of the shared limit (Abilityai/trinity-enterprise#676)

PR #3132's review: the per-viewer cap was a fixed 20 while the shared
budget it sits in front of comes from OBJECTIVES_READ_RATE_LIMIT. An
operator who lowered that limit to 20 or less would let one Workspace
viewer empty the budget the operator route and the agent's own
get_objectives draw on, and the "at most a third" comment would be false.

The cap is now derived: max(1, limit // 3), in the budget's window. At the
default 60 it is 20 a minute, so default behaviour is unchanged.

Test: test_the_viewer_cap_is_a_third_of_the_limit_whatever_the_operator_sets
(limit 12: the viewer gets 4, the operator door keeps 8). Mutation: a fixed
20 turns it red.

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

* feat(workspace): a partial objectives list says it may be incomplete (Abilityai/trinity-enterprise#676)

PR #3132's review (both independent reviewers): when some objectives
joined but one of the agent's objective files failed to read or parse, the
card showed the objectives it had with no sign that any were missing.
`objectives_error` covered only the zero-objectives case (the claim-time
ruling), and nothing rendered `finding_codes`.

The card now carries `objectives_partial`: set when objectives joined AND
the join reported a file-level failure (objective_unreadable,
objective_invalid, objective_file_skipped) or files beyond the scan bound.
The Role card shows one line under the list: "Some objective files in the
agent's canon couldn't be read, so this list may be incomplete." It says
"may" because a file-level failure cannot be attributed to a role.

Tests: a table over objectives_partial, one unreadable file beside a joined
objective through the real join, and two mounted cases. Mutations: dropping
the assignment and dropping the line each turn a test red.

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

* test(workspace): the role card never resolves another agent's metric (Abilityai/trinity-enterprise#676)

ent#727 (merged from dev) lets the objective join read a metric from an
agent the reader holds a grant on, but only when the caller passes a
`can_view` naming who is looking; `None` fails closed. The role card
passes none, so a Workspace viewer, possibly an external client, never sees
a number served by an agent they may not be rostered on.

This pins that through the real join with a store that does hold such a
grant, and proves the test is not vacuous by resolving the same metric
through the join when a viewer is named. Mutation: handing the card's join
`can_view=lambda t: True` turns it red on the resolved value (99.0).

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

---------

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

Labels

priority-p1 Critical path theme-ui-ux Theme: UI/UX type-feature New functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants