Skip to content

feat(workspace): deliverables — reports gain an audience and a place to appear (ent#365) - #2383

Merged
dolho merged 3 commits into
devfrom
feature/ent365-workspace-deliverables
Aug 25, 2026
Merged

dolho merged 3 commits into
devfrom
feature/ent365-workspace-deliverables

Conversation

@dolho

@dolho dolho commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

What

An agent's structured reports (#918) were operator-scoped scrollback: the person they were produced for had no way to see them. Two changes make a report a deliverable — it can be addressed to a Workspace user, and the Workspace read is scoped to whoever is asking.

The security half

agent_page.reports() called db.get_reports_for_agent(agent_name) — the operator question, "everything this agent ever published". The Workspace asks a different one. So every rostered client of a shared agent saw every report it had produced, including reports produced for a different client, rendered from free-form agent JSON on a client-facing surface.

ent#428 fixed exactly this shape on the sibling surface (_asks was scoped by agent_name alone, so co-shared clients read each other's asks). This is the same defect over a bigger blob, and the same remedy — plus one hardening: client_email is a required keyword on the detail path, because a default makes the gate fail open, which is the defect.

Addressing, and why it is a column

agent_reports.addressed_to_email — nullable, NULL = operator-only, which is what every report published before this meant. The create route checks the address against the publishing agent's own roster (db.email_has_agent_access — the same predicate #848 inline auth gates on, so "can be addressed" cannot drift from "can reach"):

  • an address the agent does not already talk to → named 400 that says how to fix it
  • an unreadable roster → 503, never a publish

It is deliberately not a key inside payload: that is agent-authored free-form JSON, so an audience buried there would let a prompt-injected agent decide whose Workspace its output lands in. That is the ent#364 rule, restated for a bigger payload.

The chat is resolved server-side

report(audience_email, execution_id)
   → resolve_and_validate_execution(execution_id, agent)   # MEM-001: the agent
     (does this execution belong to this agent?)           #  supplies an id,
   → ent#286 in-flight marker: execution → portal session   #  never an identity
   → agent_reports.portal_session_id

The agent never names a conversation, so it cannot post a card into one it was not part of. No marker (a scheduled run, an expired turn) ⇒ NULL, and the deliverable still lists on the agent page without a card.

What a client sees

Surface Shows
Agent page → Reports Deliverables addressed to this reader
Chat Deliverables produced in this chat (?session_id=), as cards at the end of the thread
Operator surfaces Unchanged — Agent Detail and the fleet view still show everything

Cards reuse the shared components/reports/ dispatch (Technical Notes: do not build a second rendering layer) with #2162's stricter client rule — :fallback-component="ReportSummary", so an unknown shape degrades to a bounded summary and never a raw payload dump. The list re-reads after a turn, not on a timer: a turn is the only thing that can produce a deliverable in a chat.

Deliberate behaviour change

Unaddressed reports no longer appear in the Workspace at all (AC #1: unaddressed output stays operator-only). An install whose agents have not adopted audience_email will see an empty Workspace Reports tab where it previously saw the agent's full history. That history was the leak; the empty state is the correct answer until an agent addresses something.

Verified live

Against a local stack, publishing through the real route and reading through the real portal routes:

publish addressed        → 200
publish unaddressed      → 200
publish to a stranger    → 400 "audience_email is not a client of this agent — share the agent with that address first…"

PORTAL   list            → 1 report  (the addressed one)
OPERATOR list            → 2 reports (unchanged)
PORTAL   detail (unaddressed) → 404
PORTAL   detail (addressed)   → 200

Tests

  • tests/unit/test_ent365_report_audience.py (12) — the list reads the client-scoped accessor and passes the reader (with a canary that fails if the operator accessor is ever called from that path again); a chat-scoped list narrows within the reader's rows; a read failure degrades to empty, not to someone else's reports; the detail gate denies a foreign audience and still applies the ent#360 agent check; the reader identity is required, not defaulted; publishing refuses a stranger (400) and an unreadable roster (503); an unaddressed report performs no roster lookup at all; the session resolves only for an execution this agent owns.
  • src/frontend/tests/unit/portalDeliverables.spec.js — badge/time helpers (incl. clock skew never rendering the future as elapsed) plus source assertions: chat-scoped, refresh-after-turn not polled, payloads cleared on thread switch, stricter client fallback, no console.error-only path.
  • Two fixture repairs, same class: test_1539 and test_918 hand-copied the agent_reports DDL, so the new columns failed them with a fixture error dressed as an accessor failure. Both now derive the table from db.tables metadata — the next column arrives for free.
  • test_schema_parity caught a real gap — the two new indexes existed in the migration but not in the fresh-build DDL. Fixed, not silenced.

Related suites re-run in the backend image: 1164 passed.

Migrations

Dual-track, both nullable-with-no-default: db/migrations.py::_migrate_report_audience (SQLite) + Alembic 0046_report_audience (PostgreSQL), plus two indexes — (addressed_to_email, agent_name, created_at) and (portal_session_id, created_at) — because the Workspace reads by audience on a table retention lets grow to 90 days. db/schema.py and db/tables.py updated so fresh builds match.

Not in this pass, stated

  • Ratings (AC Feature/process engine #6) — trinity-enterprise#366 is not built. The card is the surface it will attach to; nothing here pre-empts its shape.
  • Files (the other half of AC Fix: Add missing Docker labels to system agent container #1) — file scoping is unchanged as the issue directs: the per-agent inbox boundary stays where it is, because that boundary is where the last two portal security bugs lived. Shared files remain listed per agent and are not yet addressable.

Related to Abilityai/trinity-enterprise#365

🤖 Generated with Claude Code

@dolho

dolho commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

/review — self-review of this PR, plus a live pass against a running instance

Branch: feature/ent365-workspace-deliverables → dev · merge-base b7bac09d
Files: 30 (+1241/−82) — 11 backend, 4 frontend, 2 MCP, 3 docs, 5 test files
Scope: CLEAN. Everything traces to an AC or to a fixture the new columns broke. No unrelated files.
Plan completion: AC 1–5 DONE · AC 6 (ratings) NOT DONE — blocked on ent#366, stated · AC 1's file half NOT DONE — out of scope by the issue's own Technical Notes.


Critical: none found

The riskiest surface here is the new gate, so it's worth saying exactly why I believe it holds rather than asserting it:

  • get_report_for_client reads the audience with its own SELECT rather than off _mapping_to_report's output, because that mapper whitelists the fields it exposes and does not carry addressed_to_email. A gate written against its output would compare None to an email and deny every report — fail-closed, and silently wrong. (db/reports.py)
  • client_email is a required keyword on report_detail, not a defaulted one. A default is what makes an audience gate fail open, and it is the exact defect this PR fixes on the list path. Pinned by a test that asserts the TypeError.
  • The empty-email case matches nothing, not everything: if not client_email: return []. Rows with a NULL audience are operator-only, and a caller who cannot be identified must not inherit them.
  • session_id is a narrowing only — the audience condition is applied regardless, so another client's session id returns nothing rather than their deliverables. Pinned by a test, and verified live.

Informational

[I1] _resolve_portal_session swallows every exception (Confidence 8/10) — routers/reports.py

except Exception as e:  # noqa: BLE001
    logger.debug("portal session resolution skipped for %s: %s", execution_id, e)
    return None

Deliberate: a publish must not fail over card placement, and the degraded outcome is honest (the deliverable lists on the agent page without a card). But debug means a genuine regression in the resolution path would be invisible in production logs. Argument for leaving it: this is the only path where a nicety can take down a publish, and the marker is legitimately absent for every scheduled run — at warning it would be noise on the common path. Flagging rather than changing.

[I2] Fixed during this review — a positional-argument trap (Confidence 9/10) — agent_page.reports() had client_email second, so reports(agent, 20) would have read 20 as an email and returned an empty list rather than raising. limit/offset are keyword-only now, so that call cannot be written. (Commit on the branch.)

[I3] The create-response key filter is a belt, not the mechanism (Confidence 9/10) — Pydantic v2 ignores unknown keys by default, so Report(**report) would have worked. The explicit filter keeps the audience out of the response shape without relying on a model-config default a later extra= change could flip. Now says so in a comment.

[I4] Two test fixtures hand-copied the agent_reports DDL (Confidence 10/10) — test_1539 and test_918. The new columns failed them with a fixture error dressed as an accessor failure. Both now derive the table from db.tables metadata, so the next column arrives for free. This is the third schema declaration in the repo for one table; deriving removes two of them.

[I5] test_schema_parity caught a real gap (Confidence 10/10) — the two indexes existed in the migration but not in the fresh-build DDL, so a fresh install would have run without them. Fixed in db/schema.py, not silenced.

Clean categories

SQL is parameterized throughout (SQLAlchemy Core, no interpolation). No new endpoint — the audience rides the existing create route and the existing portal routes, so no new auth boundary. No credential exposure: the WS broadcast stays thin ({agent_name, report_id, report_type, created_at} — an addressee's email never rides a SCOPE_ALL channel), and the summary projection does not carry portal_session_id. Enum completeness: display_hint untouched; the new DELIVERABLE_KIND_LABELS covers every hint the renderer dispatches on, pinned by a test. Frontend: no v-html, no JSON.stringify of a payload, failures land in InlineError next to their control. Migrations: dual-track, both nullable-with-no-default, single Alembic head verified.


Live pass against a running instance

Not asserted from the diff — driven through the real routes on a local stack with this branch's source mounted.

Publish path

addressed report              → 200
unaddressed report            → 200
address outside the roster    → 400 "audience_email is not a client of this agent —
                                     share the agent with that address first…"

Read boundary

PORTAL   list                 → 1 report   (the addressed one)
OPERATOR list                 → 2 reports  (unchanged)
PORTAL   detail (unaddressed) → 404
PORTAL   detail (addressed)   → 200

Server-side session resolution — armed the real ent#286 in-flight marker for a real execution of that agent, published through the real route, and the row came back with portal_session_id set; the chat-scoped read returned exactly that deliverable.

The card, in a browser

deliverables section present : true
card title + badge           : true   ("Metrics" / "Invoice reconciliation")
chat-scoped request          : /…/reports?session_id=7d27744d…
expand → detail fetched      : /…/reports/c4eb39ab…
rendered                     : "INVOICES MATCHED 42 · DISCREPANCIES 3"  (typed KPI renderer)
raw JSON dumped              : false

One correction to my own first run: I initially recorded the expanded card as not rendering. That was a case-sensitive assertion against a CSS-uppercased label, not a defect — the tiles were on screen the whole time.

Tests

670 passed across the report/portal suites in the backend image, including the 12 new ent#365 cases and the two repaired fixtures. Frontend helper assertions executed locally; the spec runs in CI.

CI note (not this PR)

pytest (base, seed 12345) failed on the first run — canceled at 63% after 25m15s, i.e. the job's 25-minute ceiling, on the base side (dev without this diff). All three head jobs passed in 12–14 min. Historically every job in this matrix runs 12–18 min against that ceiling, so the margin is ~1.4× at the observed worst case and one slow runner exceeds it. Nothing in this diff touches it; worth its own issue if it recurs.

🤖 Review generated with Claude Code

@obasilakis obasilakis 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.

Reviewed against /validate-pr, with attention to the security half, the dual-track migration and the three-surface sync. The code here is careful and I want to be explicit about that before the one ask.

What's right:

  • get_reports_for_client is a separate accessor rather than get_reports_for_agent with a filter bolted on — the operator and client questions genuinely differ, and the docstring says why.
  • client_email is a required keyword on report_detail, for the reason stated: a default makes the gate fail open, which is the defect.
  • get_report_for_client reads the audience with its own SELECT rather than off _mapping_to_report's whitelisted dict. That is exactly right and easy to get wrong — a gate written against that output would compare None to an email and deny everything, fail-closed and silently wrong. Both gates still run: audience, then the ent#360 agent check.
  • Case consistency holds end to end, which is the silent-invisibility trap here: ReportCreate._normalize_audience lowercases, email_has_agent_access normalizes (#446), decode_portal_session lowercases (dependencies.py:388), and the platform branch lowercases (portal_auth.py:148). Both principal kinds join safely.
  • Audience and session are columns, not payload keys — a prompt-injected agent cannot pick whose Workspace its output lands in, nor post a card into a conversation it was not part of. Session resolved server-side via resolve_and_validate_execution then the ent#286 marker.
  • 503 on an unreadable roster, named 400 on a stranger — an unverifiable audience never publishes.
  • Audience deliberately kept off the /ws broadcast (SCOPE_ALL, unfiltered — the #918 rule).
  • Both migration tracks match, same index pair, nullable-no-default, schema-parity green. test_schema_parity catching the missing fresh-build indexes and those being fixed rather than silenced is the right outcome.

The ask: the feature cannot activate on any install

services/platform_prompt_service.py is untouched. The fleet-wide "Publishing Reports" block every agent reads carries this call template:

mcp__trinity__report(
    report_type=…, title=…, payload=…,
    display_hint=…, period_start=…, period_end=…)

grep -c audience_email services/platform_prompt_service.py → 0.

So every agent on every install keeps publishing with addressed_to_email = NULL, every report stays operator-only, and the Workspace Reports tab is empty — not "until agents adopt", but with no mechanism by which adoption happens. AC #2 and #3 are unreachable in practice.

To be fair to the PR: the empty tab is the scoping fix working, not a regression — what clients were seeing was other clients' reports. That's why this is the weakest of the three findings I'd raise. But it does mean the deliverable half ships inert, and this is the packaging-gap class one layer up (#1039, #1056: the lever exists, nothing pulls it). #1535's own argument for putting reporting in the platform prompt — so it is a fleet-wide default rather than a per-template opt-in — applies verbatim to the audience.

The block is already CI-pinned to this exact tool (tests/unit/test_1535_report_prompt_guidance.py pins the display_hint enum against the tool schema), so extending it is in-pattern: two lines in the call template plus a sentence on when to address a report.

Happy to be overruled if the intent is that ent#366 or a template pass owns adoption — but then it should say so, because "an install will see an empty tab until they do" currently reads as a state nothing is scheduled to leave.

Non-blocking

  • _resolve_portal_session swallows every failure at logger.debug. Fail-soft is right — a card placement must not fail a publish — but debug is too quiet for the one function the entire in-chat half of AC #3 depends on. A Redis outage, an import error or a marker-key change makes every card silently stop appearing while the agent page still lists them, so nobody has a reason to look. warning costs nothing.
  • _SUMMARY_COLUMNS and _mapping_to_report both omit addressed_to_email — correct for the response shape and the broadcast, but the consequence is that no surface anywhere answers "who was this produced for". The Agent Detail Reports tab now shows deliverables with no indication they were addressed. Product call rather than a defect, but worth a decision rather than a discovery.
  • addressed_to_email is client PII on a table retention lets grow to 90 days, sitting beside agent-authored payload. Covered by the existing agent_reports_retention_days sweep so it ages out; flagging for awareness only.

Process

Body says "Related to Abilityai/trinity-enterprise#365" rather than Fixes. Cross-tracker doesn't auto-promote either way, so ent#365 needs a manual status-in-dev at merge.

dolho added a commit that referenced this pull request Aug 24, 2026
…ps inert (ent#365)

Review finding from @obasilakis on #2383, and it is correct: the audience
column is nullable, every agent defaults to NULL, and nothing anywhere told an
agent the argument exists. The Workspace deliverables tab would have been empty
on every install forever — not 'until agents adopt it', but with no mechanism
by which adoption happens. Packaging-gap class (#1039/#1056): the lever exists,
nothing pulls it.

* platform_prompt_service: 'Publishing Reports' documents audience_email and
  when to use it. #1535's own argument for putting reporting in the platform
  prompt — fleet-wide default, not per-template opt-in — applies verbatim to
  who a report is for.
* test_1535: new test pinning that the argument stays documented AND that the
  name matches what the MCP tool accepts, so prompt and tool cannot drift.
  MAX_BLOCK_CHARS 2000 -> 2400 as an explicit decision with its reasoning
  recorded beside it (the file asks for exactly that); ~100 tokens/turn, versus
  trimming working guidance to fit and trading one inert feature for another.
* routers/reports: _resolve_portal_session failure logs WARNING, not debug. The
  in-chat half of the deliverable depends on that one function, and at debug a
  Redis outage would silently stop every card while the agent page kept listing
  reports — nothing would give anyone a reason to look.
* addressed_to on the REST list + detail responses, so operators can answer 'who
  was this produced for'. Kept OFF the /ws broadcast (SCOPE_ALL, #918 rule).
  _SUMMARY_COLUMNS is read positionally, so the column is appended.

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

dolho commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Blocking finding accepted — you're right, and the framing is the useful part: not "agents haven't adopted it yet" but no mechanism by which adoption happens. I shipped the column, the gate, the scoped accessors and the UI, and then left the one thing that makes any of it fire to chance. That's the plumbing, not the feature.

Fixed in 0116b30.

The prompt — services/platform_prompt_service.py's Publishing Reports block now carries the argument and when to use it:

    display_hint="table",                  # optional, see below
    audience_email="[email protected]",       # optional, see below

Reports are operator-facing by default. When the work was done for a person the operator shared you with, pass audience_email: it also reaches their Workspace — their deliverables, and a card in the chat it came from. Address what a client asked for; leave it off for fleet telemetry. An address that cannot reach you is refused, never silently dropped.

Rendered out of the running backend to confirm it actually reaches an agent, not just the source file.

The budget was the interesting part. The block was at 1907 against a 2000 cap, so there was ~90 chars of room — the addition needed ~400. The two options were trimming working guidance to fit, or raising the ceiling. I raised it to 2400, and recorded the reasoning where the file explicitly asks for it ("Raising this ceiling should be a decision, not an accident"): ~100 tokens per turn, against a feature that is otherwise inert on every install. Squeezing would have traded one inert thing for another.

Pinned so it can't regress: a new test asserts the argument stays documented and that the name matches what reports.ts actually accepts — the prompt and the tool can now only drift loudly. Same discipline as the display_hint pin already in that file.


Non-blocking 1 — logger.debug. Agreed, and your reason is the right one: it's the single function the whole in-chat half depends on, and at debug a Redis outage or a renamed marker key stops every card while the agent page keeps listing reports, so nothing gives anyone a reason to look. Now WARNING, naming the consequence ("the report will publish without an in-chat card") rather than just the exception.

Non-blocking 2 — "who was this for". Taking the decision rather than leaving it a discovery, as you asked. addressed_to now rides the access-controlled REST list and detail responses, so the question is answerable; it stays off the /ws broadcast, which is SCOPE_ALL and unfiltered (the #918 rule — the same reason the audience never went on it in the first place). Note _SUMMARY_COLUMNS is read positionally by _row_to_summary, so the column is appended, not inserted. The badge that renders it on the Agent Detail Reports tab is a follow-up — the data is there now, which was the actual gap.

Non-blocking 3 — PII on a 90-day table. Noted, and it's covered by the existing agent_reports_retention_days sweep, which is in RETENTION_OPS_KEYS and therefore behind the #1644 blast-radius guard and the validated write path. Nothing to do beyond being aware, agreed.

Process — "Related to" is deliberate house rule (relate, don't close; issues close on merge to main), so yes: ent#365 needs the manual status-in-dev at merge. I'll do it.


Also worth flagging since you'll see it on the checks: the one red was pytest (head, seed 12345) cancelled at 25m16s — the job's timeout-minutes: 25, not a test failure. I checked the pattern across the last dozen runs rather than assuming: healthy runs sit at 12–15m across all three seeds (seed 12345 itself passed 4×), and the short "cancelled 1–2m" rows are superseded runs, not timeouts. So this isn't seed-specific and isn't this PR.

It is worth someone's attention though: that cap was chosen when the suite ran "~7–8 min", explicitly sized to absorb the documented 2–2.5× shared-runner variance. At today's 14m median that allowance no longer fits — 14 × 1.8 already exceeds 25. The workflow's own #2019 comment predicts this symptom and names --timeout-method=thread as the fallback for a stall, but the numbers here point at plain suite growth rather than a hang. I'd rather not bundle a shared-workflow change into a feature PR; happy to open a one-line PR raising it if you agree that's the right read.

@github-actions

Copy link
Copy Markdown

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

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

@github-actions

Copy link
Copy Markdown

⚠️ Live-instance suite skipped — merge conflict against dev.

Resolve by merging dev locally and pushing the result; the next nightly re-tests.

dolho and others added 3 commits August 25, 2026 13:38
…to appear (ent#365)

An agent's structured reports (#918) were operator-scoped scrollback: the person
they were produced for had no way to see them. Two changes make a report a
deliverable — it can be addressed to a Workspace user, and the Workspace read is
scoped to whoever is asking.

The second half is a security fix. `agent_page.reports()` called
`db.get_reports_for_agent` — the OPERATOR question, "everything this agent ever
published" — so every rostered client of a shared agent saw every report it had
produced, including reports produced for a different client, rendered from
free-form agent JSON on a client-facing surface. ent#428 fixed exactly this shape
on the sibling ask surface; this is the same defect over a bigger blob. The
detail read carries the same gate, and `client_email` is a REQUIRED keyword
there: a default would make the gate fail open, which is the defect itself.

Addressing is a validated column (`agent_reports.addressed_to_email`), checked at
the create route against the publishing agent's OWN roster via
`db.email_has_agent_access` — the same predicate #848 inline auth gates on, so
"can be addressed" cannot drift from "can reach". An address the agent does not
already talk to is refused with a named 400 that says how to fix it; an
unreadable roster is a 503, never a publish. It is deliberately not a key inside
`payload`: that is agent-authored, so an audience buried there would let a
prompt-injected agent choose whose Workspace its output lands in (the ent#364
rule, restated).

The producing chat is resolved SERVER-side: the agent passes an execution_id, the
backend confirms the execution belongs to it (`resolve_and_validate_execution`,
the MEM-001 rule) and reads the session from the ent#286 in-flight marker. The
agent never names a conversation, so it cannot post a card into one it was not
part of; no marker means no card, and the deliverable still lists on the agent
page. Cards reuse the shared components/reports/ dispatch with #2162's stricter
client fallback, and re-read after a turn rather than on a timer.

Deliberate behaviour change, stated in the docs: unaddressed reports no longer
appear in the Workspace at all (AC #1), so an install whose agents have not
adopted `audience_email` sees an empty Reports tab where it previously saw the
leak. Operator surfaces are untouched.

Verified live against a local stack: an addressed report reaches the portal list
and detail (200), the unaddressed one appears only on the operator list and 404s
on the portal detail, and an address outside the agent's roster is refused by
name.

Two fixture repairs came with it, both the same class: `test_1539` and
`test_918` hand-copied the `agent_reports` DDL, so the new columns failed them
with a fixture error dressed as an accessor failure. Both now derive the table
from `db.tables` metadata, which also means the next column arrives for free.
`test_schema_parity` caught a real gap — the two new indexes existed in the
migration but not in the fresh-build DDL — and that is fixed rather than
silenced.

Out of scope by direction: file scoping is unchanged (the per-agent inbox
boundary is where the last two portal security bugs lived), and the rating
affordance waits on ent#366 — the card is the surface it will attach to.

Related to Abilityai/trinity-enterprise#365

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

Review of this PR's own diff: `client_email` sits second on `agent_page.reports`,
so a caller passing `limit` positionally would have had 20 read as an email —
matching nothing and returning an empty list rather than raising. `limit`/`offset`
are keyword-only now, so that call cannot be written.

Also states what the create-response key filter is: a belt over Pydantic v2's
ignore-unknown default, not the mechanism keeping the audience out of the
response shape.

Related to Abilityai/trinity-enterprise#365

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ps inert (ent#365)

Review finding from @obasilakis on #2383, and it is correct: the audience
column is nullable, every agent defaults to NULL, and nothing anywhere told an
agent the argument exists. The Workspace deliverables tab would have been empty
on every install forever — not 'until agents adopt it', but with no mechanism
by which adoption happens. Packaging-gap class (#1039/#1056): the lever exists,
nothing pulls it.

* platform_prompt_service: 'Publishing Reports' documents audience_email and
  when to use it. #1535's own argument for putting reporting in the platform
  prompt — fleet-wide default, not per-template opt-in — applies verbatim to
  who a report is for.
* test_1535: new test pinning that the argument stays documented AND that the
  name matches what the MCP tool accepts, so prompt and tool cannot drift.
  MAX_BLOCK_CHARS 2000 -> 2400 as an explicit decision with its reasoning
  recorded beside it (the file asks for exactly that); ~100 tokens/turn, versus
  trimming working guidance to fit and trading one inert feature for another.
* routers/reports: _resolve_portal_session failure logs WARNING, not debug. The
  in-chat half of the deliverable depends on that one function, and at debug a
  Redis outage would silently stop every card while the agent page kept listing
  reports — nothing would give anyone a reason to look.
* addressed_to on the REST list + detail responses, so operators can answer 'who
  was this produced for'. Kept OFF the /ws broadcast (SCOPE_ALL, #918 rule).
  _SUMMARY_COLUMNS is read positionally, so the column is appended.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@dolho
dolho force-pushed the feature/ent365-workspace-deliverables branch from 0116b30 to d0d833f Compare August 25, 2026 10:39
@dolho

dolho commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Code review — re-review at d0d833f

Read the full diff against dev with the surrounding code for each hunk: portal auth / principal normalisation, the ent#286 in-flight marker, the migration runner, every _SUMMARY_COLUMNS consumer, the MCP tool shaping, and the Vue composition.

The core security fix is sound. Both principal paths lowercase the email (decode_portal_session and the platform branch) and ReportCreate._normalize_audience lowercases too, so the == audience comparison cannot silently deny; get_report_for_client treats a missing row and a NULL audience identically; agent_page.reports still whitelists its output so addressed_to never reaches a portal client; the broadcast stays thin; Alembic 0046 chains off the real head 0045_merge_rooms_hotfix; and the SQLite migration's no such table fresh-install path is handled by the runner.

The previous review's blocking item — the platform prompt never mentioning audience_email, so the feature shipped inert — is fixed in d0d833f.

Medium

1. routers/reports.py:66 — in-chat deliverable cards can never appear for a synchronous portal turn.

_resolve_portal_session depends on the ent#286 reverse marker, and mark_turn_inflight has exactly one caller: client_portal/service.py:2054, inside start_portal_turn — the streaming 202 path. The synchronous POST /api/enterprise/client-portal/agents/{name}/chat never sets it.

Two live paths hit this. PortalConversation.deliver() falls back to the sync send when the streaming dispatch route 404/405s or the request never lands (its own comment at :777), and ent#83's documented headless integration surface uses the sync route exclusively. In both, the agent publishes with a valid audience_email + execution_id, get_inflight_session_for_execution returns None, and the deliverable is stored with portal_session_id = NULL — so the card silently never renders in the chat. The docstring enumerates "a scheduled run, an expired turn" as the NULL cases; this third one is undocumented and is a user path, not an edge.

2. PortalDeliverables.vue:106 — the chat card fetches the whole payload, bypassing #2162 row windowing.

store.fetchAgentReport(props.agentName, d.id) is called with no options, so rows_limit / rows_offset are omitted and report_detail returns the payload whole. An agent files a tabular deliverable near the 5 MiB REPORT_PAYLOAD_MAX_BYTES ceiling and addresses it to a client; expanding the card in chat ships all ~5 MiB to the browser and renders every row — while the sibling Reports tab on the agent page pages the identical report through the store's windowed orchestration. The card also carries no "load more", so there is no bounded read available here at all.

3. db/reports.py:39 — client email addresses now flow to agent principals through MCP list_reports.

Appending agent_reports.c.addressed_to_email to _SUMMARY_COLUMNS puts addressed_to on every ReportSummary, including GET /api/agents/{name}/reports and GET /api/reports, which src/mcp-server/src/tools/reports.ts returns verbatim (JSON.stringify({count, reports}); filterReportsForAgentScope filters ROWS by agent, never fields).

Scenario: agent B holds an agent_permissions edge to agent A. list_reports({agent_name: "A"}) now returns A's clients' email addresses into B's LLM context, where none were exposed before. It also contradicts the tool's own advertised contract — "Returns METADATA only (id, type, title, period, created_at)". Either strip addressed_to in the MCP layer or scope it to non-agent principals.

Low

4. routers/reports.py:237 — the create response's addressed_to is always null, even for an addressed report. Report extends ReportSummary, so addressed_to is in Report.model_fields — but the dict db.create_report returns carries the key addressed_to_email, which the comprehension drops. GET /api/reports/{id} (via _mapping_to_report) does return it populated, so the same model means two different things depending on the route. The inline comment claims the filter "keeps the audience out of the response shape" while ReportSummary was simultaneously changed to expose it — the two intentions contradict each other. The MCP tool papers over it by echoing params.audience_email, so nothing breaks today.

5. routers/reports.py:193 — the publish-time predicate is broader than the read-time one, so a publish can succeed to an address that can never see it. db.email_has_agent_access returns True for any user whose role is admin (db/agent_settings/sharing.py:249) regardless of sharing, whereas the Workspace read gate _require_roster → service.agent_on_roster(agent, email, include_owned) is agent_sharing ∪ owned only. An agent addresses a report to a platform admin who neither owns nor is shared the agent: create returns 200, the row is stored with that audience, and the admin's Workspace 404s on the agent page — the deliverable is unreachable by anyone. That falsifies the stated invariant that "'can be addressed' cannot drift from 'can reach'".

🤖 Generated with Claude Code

@obasilakis obasilakis 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.

Re-reviewed at d0d833f against the state I reviewed at acbf569. The branch was rebased onto current dev, so the delta is one new commit (d0d833f) plus the rebase; I diffed the new commit in isolation and then re-read the whole PR diff against the merge base rather than trusting the earlier pass.

Verdict on the earlier findings

The blocking one — the feature could not activate on any install — is properly fixed. services/platform_prompt_service.py now documents audience_email in the fleet-wide "Publishing Reports" block, with a sentence on when to address a report and when not to, so adoption is a mechanism rather than a hope. The part I did not ask for and think is the better half of the fix is test_1535_report_prompt_guidance.py::test_audience_is_documented_so_the_deliverables_surface_can_fill, which pins both that the argument stays documented and that its name still matches what reports.ts accepts — the prompt and the tool cannot now drift into documenting an argument the tool would drop. Raising MAX_BLOCK_CHARS from 2000 to 2400 is the right way to spend that budget, and recording the reasoning in the constant is what the file asks for.

_resolve_portal_session now logs at WARNING, with a message that names the consequence ("the report will publish without an in-chat card"). That is what I was after: fail-soft behaviour, non-silent failure.

"Who was this produced for" is now answerable, via addressed_to on ReportSummary (and, by inheritance, on Report), and correctly kept off the /ws broadcast, which is SCOPE_ALL and unfiltered. The capability is right; see the first finding below on the tier it landed at.

The retention point stands as I left it — addressed_to_email ages out with the row under the existing agent_reports_retention_days sweep, no action needed.

What I re-checked on the current diff

The core scoping fix holds up on a second read. get_reports_for_client and get_report_for_client are separate accessors; client_email is a required keyword on report_detail; the audience gate reads the column with its own SELECT rather than off _mapping_to_report's whitelist; both gates (audience, then the ent#360 agent check) still run. Off-roster is a uniform 404 through _require_roster → agent_on_roster, and a foreign report id, a foreign-agent id and a foreign-audience id all return the same 404, so the detail route is not an existence oracle. Case handling joins safely for both principal kinds — ReportCreate._normalize_audience lowercases, decode_portal_session lowercases, and the platform branch of get_portal_principal lowercases.

On disclosure specifically: both client-facing projections in agent_page.py are explicit key whitelists, so addressed_to and portal_session_id do not reach the portal. The chat card renders through the shared components/reports/ dispatch with :fallback-component="ReportSummary", matching what PortalAgentPage.vue already does per #2162 — no raw JSON.stringify(payload) is reachable on either client surface. _SUMMARY_COLUMNS is read positionally and the new column was appended, and all three consumers (get_reports_for_agent, get_reports_for_client, get_fleet_reports) select the same tuple, so the positional read is consistent. Migrations are dual-track with matching index pairs in db/migrations.py, Alembic 0046, db/schema.py and db/tables.py; agent_reports is already an AGENT_REFS CASCADE entry so rename and purge cascade unchanged; portal route ordering is fine (/reports is declared before /reports/{report_id}). The rate limiter on create runs before the roster lookup, so the new DB read cannot be driven faster than the existing report cap. On the frontend, PortalDeliverables.vue uses semantic action-primary-* tokens for the badge and otherwise only gray chrome, consistent with the rest of components/portal/; every colour has a dark counterpart and there are no hex literals.

New findings

1. addressed_to landed at a wider tier than the client roster it is derived from (minor, worth resolving before merge)

GET /api/agents/{name}/reports is AuthorizedAgent and GET /api/reports scopes by accessible_agent_names — both of which include any platform user the agent is shared with, not just the owner. Report inherits from ReportSummary, so GET /api/reports/{report_id} (gated by _report_or_404 → can_user_access_agent) carries the field too. Meanwhile the client roster those addresses come from is deliberately owner-only: GET /{agent_name}/shares, /access and /clients are all OwnedAgentByName. So a shared collaborator can now read a subset of the owner-only share list off the reports surface.

Two things keep me from calling this blocking. ExecutionSummary.source_user_email already exposes triggering-user emails on that same AuthorizedAgent route, so this is a broadening of an existing pattern rather than a first breach; and everyone whose address is disclosed is by construction already a member of the same share list as the reader. What tips it into "please decide" rather than "fine" is that the field has no consumer today — the flow doc says the Agent Detail badge is a follow-up — so it is currently paying a disclosure cost for nothing, and an addressed client may be an external Workspace user who has never triggered an execution and therefore appears nowhere else on that surface.

I asked for this capability, so I am not going to block on it; I would just rather it went in at the owner tier. Cheapest options are to drop it from ReportSummary until the badge lands (a two-line revert, keeping the column and the accessor), or to keep it on the per-agent list under an owner check and off the fleet list, which is the widest audience.

2. The audience predicate accepts addresses that can never see the result (minor)

db.email_has_agent_access returns True for any admin's email on the install — if user.get("role") == "admin": return True, before any sharing check — whereas display is gated by service.agent_on_roster, which is shared ∪ owned with no admin bypass (get_shared_roster has no role branch). So an agent may address a report to an admin who neither owns the agent nor is shared it, the publish succeeds, and the report is then undisplayable to anyone. That contradicts the route's own 400 wording ("share the agent with that address first") and the new prompt sentence ("An address that cannot reach you is refused, never silently dropped").

The PR body justifies the predicate by pointing at #848 inline auth, and that citation is accurate — but the closer precedent is ent#364, which this PR cites as its governing rule, and that used client_portal.service.agent_on_roster(agent, email, include_owned=False). Using agent_on_roster(name, audience, include_owned=True) here would make the publish gate and the display gate literally the same function, which is the property the docstrings are claiming. (include_owned=True rather than ent#364's False, since addressing a deliverable to the owner is reasonable in a way that addressing an ask to them was not.)

3. The create response is the one place addressed_to is guaranteed wrong (trivial)

Report now inherits addressed_to, but db.create_report returns the key as addressed_to_email, and the router filters by Report.model_fields — so POST /api/agents/{name}/reports answers addressed_to: null even for a report that was just addressed. reports.ts papers over it by echoing params.audience_email, which works, but means the response to the write that sets the field is the one response that misreports it. Either map the key or leave the field off the create response deliberately.

4. Stale reasoning in get_report_for_client's docstring (trivial)

It argues the gate runs its own SELECT because "_mapping_to_report whitelists the fields it exposes and does not carry addressed_to_email" — but the same commit added addressed_to to that dict. The argument still holds on the merits (different key name, and the separate SELECT avoids reading a 5 MiB payload to answer a gate), but the closing sentence, "It also keeps the audience out of the operator response shape, which no caller asked to change", is now simply untrue. Worth a re-word, because that docstring is doing real work warning the next person off a fail-closed-and-silently-wrong gate.

5. The in-chat deliverables list truncates silently (minor, product call)

fetchSessionDeliverables sends no limit, so the server default of 20 applies. Bounding it is right; the part worth a decision is that a 21st deliverable in a long chat is invisible with no affordance saying so. The agent-page tab has the same shape.

6. A question rather than a finding: consent

The audience is agent-chosen, and roster membership is its only gate — a prompt-injected turn can place content into any co-rostered client's Workspace with no human in the loop. The closest existing agent-initiated placement, #321 proactive messaging, additionally requires the per-share allow_proactive bit. I think the distinction is defensible (a deliverable is pull, a proactive message is push, and ent#364 already set the roster-only precedent for asks on the pull side), but it is going to be asked, and the flow doc is the place to say so explicitly rather than leaving the reader to infer it from the ent#364 citation.

CI

Head is green across the board. The one red check is pytest (base, seed 67890), which is the base-branch arm, and regression diff passed — pre-existing on dev, not this PR.

Process

Body still says "Related to Abilityai/trinity-enterprise#365" rather than Fixes, which is correct for a cross-tracker reference but means ent#365 needs a manual status-in-dev at merge. Note also that #2384 is stacked on this branch, so merge order matters.

Approving. The finding I most want an answer on before this lands is #1 — a one-line decision either way — and #2 is a small change I would take alongside it.

@dolho
dolho merged commit 88efbe7 into dev Aug 25, 2026
26 of 27 checks passed
louisss1016 pushed a commit to louisss1016/trinity that referenced this pull request Sep 13, 2026
…e the review landed (ent#365)

PR Abilityai#2383 merged at 12:57; the re-review posted after. Its findings therefore
live in `dev`, so they are fixed here rather than on the branch.

**Client email addresses reached agent LLM context through MCP `list_reports`.**
`addressed_to` was appended to `_SUMMARY_COLUMNS` so an operator can answer "who
was this produced for" — but `list_reports` returns the backend's rows verbatim
and `filterReportsForAgentScope` filters ROWS by agent, never FIELDS. An agent
holding an `agent_permissions` edge to another agent could call
`list_reports({agent_name: "A"})` and pull A's clients' addresses into its own
context, where none were exposed before. It also contradicted the tool's own
advertised contract ("Returns METADATA only"). Stripped for every principal, not
just agent keys: a tool result is LLM context wherever it lands, and an operator
still gets the field from the REST surface the UI uses.

**The publish gate was broader than the read gate, so a report could be
addressed to someone who could never see it.** `db.email_has_agent_access`
returns True for ANY admin regardless of sharing; the Workspace read gate is
`agent_on_roster` (`agent_sharing` ∪ owned). A report addressed to a platform
admin who neither owns nor is shared the agent stored happily and 404'd in that
admin's Workspace — falsifying the invariant the code comment states. The
publish now gates on the same function the reader uses, which is the only form
that cannot drift.

**In-chat cards never appeared for a synchronous turn.**
`_resolve_portal_session` reads the ent#286 reverse marker, and
`mark_turn_inflight` had exactly one caller — inside `start_portal_turn`. The
`POST .../chat` path never set it, so a report published from a turn that came
through there stored `portal_session_id = NULL` and the card silently never
rendered. Not an edge: `/chat` is ent#83's documented headless surface AND the
browser's fallback when streaming is unavailable. The row is now pre-created on
that path too, exactly as the streaming one does, so there is an id to mark
with — and cleared in a `finally`, because a marker outliving its turn is worse
than none (the UI reattaches to a turn that ended and waits out the TTL).

**The chat card fetched the whole payload.** It called `fetchAgentReport` with
no options, so `rows_limit` was omitted and a tabular deliverable near the 5 MiB
ceiling shipped in full to the browser and rendered every row — inside a chat
card, while the sibling Reports tab pages the identical report through Abilityai#2162's
window. The card now takes a first page and says so; the agent page stays where
a full table is read, which is more honest than paging a preview inside a
conversation.

**The create response's `addressed_to` was always null.** `Report` extends
`ReportSummary`, so the field IS in `model_fields` — the filter was dropping it
because the row carries the DB name `addressed_to_email`. So the same model
meant two different things depending on the route, with the MCP tool papering
over it by echoing back the caller's own argument. Mapped explicitly.

The `test_portal_stamps_the_surface_on_its_executions` assertion is generalised
from a hard count of 2 to "one stamp per creation site", so adding the third is
a decision rather than a broken test.

Related to Abilityai/trinity-enterprise#365
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants