Skip to content

feat(workspace): rate a message, rate a deliverable (ent#366) - #2384

Merged
dolho merged 8 commits into
devfrom
feature/ent366-workspace-ratings
Aug 27, 2026
Merged

dolho merged 8 commits into
devfrom
feature/ent366-workspace-ratings

Conversation

@dolho

@dolho dolho commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

Stacked on #2383 (feature/ent365-workspace-deliverables) — the deliverable card this attaches to exists only there. Merge #2383 first; this then retargets to dev cleanly.

What

One click on the thing being judged: thumbs on an agent message, Useful / Not what I needed on a deliverable card — the affordance ent#365 left that card as the surface for — and a comment box that opens on the negative.

Why this is a platform primitive and not a skill

A capture-feedback skill runs inside the agent, so it can summarise charitably, omit, or fail silently. That is the same reasoning that made agent-authored reports unusable as the evaluation surface and produced agent_evaluations with a write fence (ent#206): the graded agent must never write its own grade, and a user rating is precisely the score that must not pass through the thing being scored.

So this amends that fence rather than working around it — a Workspace principal becomes a legitimate writer, filed under evaluator = workspace:<email>. The rated agent still has no write path. ent#267 (the referee surface) is closed, so the fence is amended once, as the issue's sequencing asks.

The gates

POST …/client-portal/agents/{agent}/ratings
  ├─ roster scope                        (off-roster → 404)
  ├─ target_kind ∈ {message, deliverable}          (else 422)
  ├─ rating ∈ {up, down}                           (else 422)
  └─ target visible TO THIS READER                 (else 404, uniform)
       message     → this agent, this client, and the AGENT's message
       deliverable → ent#365's audience gate (get_report_for_client)
  • Ids prove nothing. Message ids and report ids are global; a route that trusted one would let anyone rate — and comment on — a conversation they have never seen.
  • You cannot rate your own message. Only the agent's are rateable; allowing a user's own would put their self-rating into the agent's tally.
  • A missing target and one that isn't yours return the same 404, so this is not an existence oracle (Invariant security: implement safe tar extraction with symlink/hardlink validation #8).

One rating per person per thing

CREATE UNIQUE INDEX idx_agent_evaluations_rating_target
  ON agent_evaluations(evaluator, target_kind, target_id)
  WHERE target_id IS NOT NULL;

A second thumb is a correction, not a second vote — which is what makes the tally count people rather than clicks. The index carries the rule so two rapid clicks can't race into two rows. Partial, so the graded-run rows a Tier-0 pass writes (no target) are untouched.

The open grooming question — decided

The issue left "whether a rating is readable by the rated agent" open. Decided: tallies yes, the words never.

_redact_for_agent_principal strips comment for an agent-scoped caller and sets comment_withheld, so a reader can tell "no comment" from "not yours to read". Two reasons:

  1. A score the agent can read is a loop it may start optimising for — the issue's own concern.
  2. The comment is untrusted free text written by someone who is, by construction, annoyed. Handing it verbatim to the agent being criticised is a prompt-injection path into it.

Operator surfaces see everything, unchanged.

The comment, and AC #6

The rating and its comment are durable before anything is dispatched.

Agent has capture-feedback What happens What the person is told
yes a background turn runs the skill with the words fenced as data (the routers/webhooks.py framing), as its own execution — never a message in the client's thread "Thanks — passed on to the agent."
no nothing more "Thanks — recorded for the team."

Both statements are true; the acknowledgement is derived from the server's answer, not assumed. Background because it is a whole agent turn, and someone clicking not what I needed should not wait on the agent that just disappointed them.

The tally (AC #4)

Raw counts, never a percentage — one thumbs-down out of one rating renders as "100% negative", a number that looks like evidence and is not. Both figures show so the denominator is on screen, and an unreadable tally reports unavailable rather than a zero it did not measure. Explicitly not NPS, per the issue.

Verified live

Through the real routes on a running stack, then in a browser:

rate up                          → recorded
change to down + comment         → SAME row updated (1 row, quality 0, comment stored)
target that isn't mine           → 404      bad target_kind → 422
agent-page tally                 → {up: 0, down: 1, total: 1}
operator read                    → comment visible
RATED AGENT read                 → quality 0.0 · comment None · comment_withheld true
thumbs rendered on agent messages : 15 up / 15 down
pre-existing rating restored      : aria-pressed=true
clicked Helpful                   → POST {target_kind:"message", rating:"up"}
clicked Not helpful               → comment box opened
sent the comment                  → honest acknowledgement

Tests

  • tests/unit/test_ent366_workspace_ratings.py (21) — who may rate what (four refusal shapes incl. rating your own message), the uniform 404, the evaluator identity, comment trimming vs dropping, a write failure reported rather than reported as success, the redaction in both directions plus non-mutation of the caller's row, the fenced prompt (with an injection string surviving inside the fence), and both degrade paths for the skill lookup.
  • src/frontend/tests/unit/portalRatings.spec.js — vocabulary per target kind, no-op on re-click, prompt only on negative, tally text (incl. "never contains %" and empty-vs-unavailable), acknowledgement honesty, plus source assertions.
  • Related backend suites re-run: 1231 passed.

One thing deliberately not done

The feedback turn is not stamped source_channel=portal. test_2157_portal_narration pins that stamp to exactly the two portal turn-creation sites and it is right: the stamp means "an exchange on the Workspace surface", and this turn has no surface — nobody sees its output and it must not be answering anyone. My first version stamped it and turned that guard red; the guard was correct.

Migrations

Dual-track: _migrate_workspace_ratings (SQLite) + Alembic 0047_workspace_ratings. Four nullable columns (target_kind, target_id, comment, updated_at) and the partial UNIQUE, with db/schema.py and db/tables.py updated so fresh builds match.

Related to Abilityai/trinity-enterprise#366

🤖 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/ent366-workspace-ratings → feature/ent365-workspace-deliverables (stacked)
Files: 18 (+1000/−30) — 9 backend, 5 frontend, 3 docs, 2 test files
Scope: CLEAN. Everything traces to an AC. The one thing outside the issue's letter — deciding the open grooming question — was asked and answered before building.
Plan completion: AC 1–6 all DONE, evidence below.

The review found two real holes, both mine, both now fixed on the branch. One of them is a class this repo has hit three times before, and I committed it in the change whose entire point is that boundary.


Critical

[C1] The redaction covered one of three read paths (Confidence 10/10 — reproduced live)
routers/evaluations.py

_redact_for_agent_principal was applied inside list_agent_evaluations only:

return [_to_response(_redact_for_agent_principal(r, current_user))   # ← one path
        for r in db.list_agent_evaluations(agent_name, limit)]
...
return [_to_response(r) for r in db.list_fleet_evaluations(names, limit)]   # ← not this one
return _to_response(row)                                                    # ← nor this one

An agent-scoped key resolves to its owner, so accessible_agent_names includes the rated agent itself — meaning GET /api/evaluations and GET /api/evaluations/{id} handed the agent its own comments verbatim. That defeats the decision this PR exists to implement, and it is the "defense added to one of N call sites" class already recorded here as #686, #1264 and #1153.

Fixed structurally, not by adding two more calls: the redaction moved inside _to_response, whose current_user is now a required parameter — a new read path cannot compile without deciding. Pinned by a test that asserts the signature has no default and that no call site omits the caller.

Verified live on all three paths after the fix:

agents/{name}/evaluations   → comment: None · withheld: True
evaluations?agent={name}    → comment: None · withheld: True
evaluations/{id}            → comment: None · withheld: True
evaluations/{id} as admin   → comment: "It skipped the due date I asked about."

[C2] The dispatch imported a name that does not exist (Confidence 10/10 — reproduced live)
client_portal/service.py

from services.task_execution_service import task_execution_service   # no such symbol

There is no module-level singleton — only get_task_execution_service(). Every unit test stubbed around the dispatch, so the suite was green while the background task raised ImportError on every negative rating with a comment. The response still said dispatched, so the failure was invisible from the outside too.

This was findable only by running it. Fixed, and now pinned by a test that exercises the real import and call signature with only the execution itself replaced — the smallest stub that still proves the wiring — plus an assertion that the turn does not claim a source_channel (#2157 FR-7).

Informational

[I1] The upsert's UPDATE-then-INSERT can race (Confidence 8/10) — two first-ratings of the same target by the same person (a double-click) both find zero rows to update, both INSERT, and the unique index refuses the loser. Handled: the loser catches IntegrityError and re-runs the UPDATE in a fresh transaction (the first one is poisoned by the failed statement), so the caller experiences "your rating is recorded" rather than a 500. The index stays the authority.

[I2] The tally is fleet-wide per agent, not per-reader (Confidence 9/10) — deliberate: "how did this land with people" is the question a tally answers, and a per-reader count of your own two clicks answers nothing. Worth knowing it is not a privacy surface either — counts only, no evaluator identities cross to the page.

[I3] No un-rate (Confidence 9/10) — clicking the rating you already gave is a no-op, because there is no retract endpoint and clearing locally would show a state the server does not have. Not in the ACs; flagged as a deliberate gap rather than an oversight.

Clean categories

SQL parameterized throughout (SQLAlchemy Core). Auth: one new route, roster-scoped, with the target checked against the reader — ids are global, so this is the load-bearing gate — and a uniform 404 so it is not an existence oracle. Rate-limited per (client, agent). No credential exposure. Migrations dual-track, all four columns nullable-with-no-default, single Alembic head, schema.py/tables.py updated so fresh builds match — test_schema_parity green. Frontend: no v-html, failures land in the control's own error line, no console.error-only path, tokens-only (check:tokens passes), no new bare loading gates.


Live pass against a running instance

The write path and its refusals

rate up                              → recorded
change to down + comment             → SAME row updated (1 row, quality 0, comment stored)
rate the deliverable (ent#365 card)  → recorded
a deliverable not addressed to me    → 404
a message id that isn't mine         → 404 (identical to a missing one)
bad target_kind                      → 422
agent-page tally                     → {up: 1, down: 1, total: 2}

The grooming decision, enforced — see the three read paths above.

The dispatch, after [C2]

capture_feedback                     → dispatched
executions                           → 1 → 2   (a real turn ran)
row                                  → status=success · triggered_by=public · source_channel=(empty)
message                              → "Run the capture-feedback skill. A Workspace user rated one of
                                        your messages as not what they needed…"

source_channel empty is the point: this turn has no client surface, and #2157's guard pins that stamp to exactly the two portal turn-creation sites.

In a browser

thumbs on agent messages          : 15 up / 15 down
pre-existing rating restored      : aria-pressed=true
clicked Helpful                   → POST {target_kind:"message", rating:"up"}
clicked Not helpful               → comment box opened
sent the comment                  → honest acknowledgement rendered

Tests

24 in test_ent366_workspace_ratings.py (up from 21 — the two regressions above added three), 89 passed across the ratings + evaluations suites, 1231 passed across the wider report/portal/eval/schema sweep.

Summary

  • Critical: 2 — found in this review, fixed on the branch, both with tests that would have caught them.
  • Informational: 3, all deliberate.
  • The honest lesson from [C2]: a stub that replaces the thing you are wiring up will pass whatever you wire it to. The dispatch had four tests around it and none of them imported it.

🤖 Review generated with Claude Code

@dolho

dolho commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

/review — second pass (the fixes verified, and one thing the first pass missed)

Re-ran against 470b35b4. The two criticals from the first pass are fixed and confirmed live. The re-review found one new finding, in the fix itself — now also fixed on the branch.


Verdict on the first pass's findings

[C1] Redaction on one of three read paths — FIXED, and confirmed complete.
The redaction now lives inside _to_response, whose current_user is a required parameter. I re-checked completeness rather than assuming it: grep for every reader of evaluation rows outside db/ returns only the three routes, and the MCP surface has no evaluations tool (the one hit in tools/agents.ts is the #668 compatibility "AI evaluation", unrelated). So the router is the only reader, and all three paths go through the hardened projection.

agents/{name}/evaluations   → comment: None · withheld: True
evaluations?agent={name}    → comment: None · withheld: True
evaluations/{id}            → comment: None · withheld: True
same, as an operator        → comment: "Totals used the wrong currency."

[C2] Dispatch imported a symbol that does not exist — FIXED, and confirmed by running it.

capture_feedback → dispatched
executions       → 1 → 2   (a real turn ran)
row              → status=success · triggered_by=public · source_channel=(empty)

New finding, from this pass

[C3] Hiding the words while leaving the rater's identity (Confidence 9/10 — reproduced live)
routers/evaluations.py::_redact_for_agent_principal

The first fix stripped comment and left the row otherwise intact. What the rated agent actually saw:

quality 0.0 | evaluator: 'workspace:[email protected]' | comment: None | withheld: True

So it could not read the complaint, but it could name the complainant — and that is arguably the more actionable half. An agent that knows a specific person rated it down is better placed to change its behaviour toward that person than one that read the text, which is precisely the failure mode the grooming decision exists to prevent. It also attaches a client identity to a judgement, which is a different fact from the identity the agent already has from talking to them.

Fixed: a workspace: evaluator is anonymised to the bare kind workspace for an agent principal. The kind survives deliberately — "a person rated this" is the signal the agent is allowed, and it is what distinguishes a human thumb from a Tier-0 pass. Only the workspace prefix is touched; a platform evaluator name carries no person, and blanking it would cost the agent the ability to tell a machine grade from a human one.

Live after the fix:

RATED AGENT : evaluator 'workspace' · comment None · withheld True
              email anywhere in the payload: False
OPERATOR    : evaluator 'workspace:[email protected]' · comment "Totals used the wrong currency."

One of my own tests asserted object identity (out is row) for a no-comment row, which this correctly breaks — the projection copies now. Rewritten to assert the rule it meant: comment_withheld means "there is text you may not read", never "there was no text".

Residual, stated rather than fixed

System-scoped keys are not redacted. User.agent_name is set only for scope="agent", so trinity-system reads comments and identities. That is not a self-read hole: the portal roster excludes system agents (is_system = 0 in both roster queries), so no rating can target one, and there is no rated system agent to protect. Recorded because it is the kind of thing that looks like a gap on a later read.

comment_withheld reveals that criticism text exists. Intentional — it is what lets a reader tell "no comment" from "not yours to read" — and it adds nothing an agent cannot already infer from the quality: 0.0 sitting beside it.

Everything else, re-checked

Migrations dual-track, one Alembic head, schema.py/tables.py matching (test_schema_parity green). The upsert's double-click race handled via IntegrityError → re-run the UPDATE in a fresh transaction. Rate limit per (client, agent). Uniform 404 on every target-visibility refusal. No v-html, no console.error-only path, tokens clean, no new bare loading gates.

Tests

27 in the ratings suite (three added this pass), 94 passed across ratings + evaluations, 1231 passed across the wider report/portal/eval/schema sweep.

Summary

  • First pass: 2 critical → both fixed and verified live.
  • Second pass: 1 new critical, in the fix → fixed and verified live.
  • The pattern worth naming: both C1 and C3 are the same mistake at different depths — I protected the obvious field on the obvious path, and the boundary was wider than the thing I was looking at. A redaction is only as good as the set of facts it covers and the set of paths that reach them.

🤖 Review generated with Claude Code

@dolho

dolho commented Aug 24, 2026

Copy link
Copy Markdown
Contributor Author

/review — third pass: the stated residual is now closed

Re-ran against 42704c81.

On the previous finding: C3 (the rated agent could name the complainant) was already fixed in 470b35b4 and verified live before the last comment — that comment reports both the finding and its fix. So this pass went after the thing I had stated rather than closed, and it turned out to deserve fixing.


[C4] The redaction covered the rated agent, not every machine reader — FIXED

routers/evaluations.py

The gate keyed on current_user.agent_name, which is set only for scope="agent". trinity-system therefore read both the client's words and the email attached to them — and it bypasses permission checks, so it reads every agent's rows, not merely its own.

My own justification for leaving this in the last pass was:

not a self-read hole: the portal roster excludes system agents, so no rating can target one

That is true, and it is precisely the reasoning this repo's learnings ledger warns about — a safety property that holds only by a fact in a different module, which the function neither states nor enforces. Change the roster query and the protection silently disappears, with nothing failing.

It was also the wrong frame. The risk is not "the rated agent reads its own grade"; it is "a person's words and identity enter a machine context" — and the orchestrator is a machine context.

_is_machine_principal now covers agent and system. A user-scoped MCP key stays unredacted: it is a person's own credential, an operator running a script is still the operator, and redacting there would break the surfaces the eval epic exists to serve. I checked that nothing shipped needs a system-scope read of comments — the Tier-0 evaluator writes server-side, not through this API.

Live, all three principal kinds:

agent      comment None       evaluator 'workspace'                    email leaked: no
system     comment None       evaluator 'workspace'                    email leaked: no
admin JWT  comment "Totals…"  evaluator 'workspace:[email protected]'  full access

Remaining residual, deliberately kept

comment_withheld reveals that criticism text exists. That is the point of the flag — it distinguishes "no comment" from "not yours to read" — and it adds nothing an agent cannot already infer from the quality: 0.0 sitting beside it. Removing it would make the two indistinguishable and the field useless.

State of the review, across three passes

Pass Finding Status
1 Redaction on 1 of 3 read paths fixed — moved into the single projection, caller now required
1 Dispatch imported a non-existent symbol fixed — pinned by a test that does the real import
2 Rater's identity left on the row fixed — workspace: anonymised to the kind
3 Only the rated agent redacted, not every machine reader fixed — agent + system

All four are the same mistake at four depths: I kept protecting the obvious field, on the obvious path, against the obvious reader. The rule that would have caught all of them in one go is "which facts, reaching which callers, through which paths" — asked once, about the boundary rather than about the change.

Verification

29 in the ratings suite (two added this pass), 96 passed across ratings + evaluations, 1233 passed across the wider report/portal/eval/schema sweep. build and schema-parity green.

🤖 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 two focused audits on top: the authorization/redaction surface, and the dual-track migration (the latter verified by execution against a live PostgreSQL 16, not by inspection).

The code here is careful, and several things in it are done the harder, correct way. I want that on the record before the one blocking ask, because it's most of the diff.

What's right

  • The write fence is amended, not widened. create_evaluation still carries require_admin + reject_agent_principal, untouched. The portal is a separate route with its own gates. That is the correct shape for ent#206 — a new writer is admitted, the rule isn't bent.
  • _rating_target_is_visible checks the target against the reader, and all three conditions are there — agent match, client-email match, role == "assistant". client_email is stored lowercased at insert (client_portal/db.py:169), so the .lower() comparison is consistent rather than a coercion hole, and the (x or "") fallbacks can't collapse to "" == "" because portal_auth.py:146 403s an account with no email. Unknown kind returns False — fail-closed. I could not find a path where a foreign message id passes.
  • The deliverable branch reuses ent#365's audience gate rather than reimplementing it, and the agent_name equality on top is additive — it closes something get_report_for_client does not itself check.
  • The redaction is placed at the single projection point. Threading current_user into _to_response as a required positional means all four read paths inherit it and a new one cannot compile without deciding. The commit message names the #686/#1264/#1153 "defense at one of N call sites" class it is avoiding, and it does avoid it — I grepped, and routers/evaluations.py is the only consumer of the three list/get accessors, with no MCP tool.
  • The rater's identity is genuinely stripped, not just claimed: workspace:[email protected] → workspace. And redacted = dict(row) copies before any write, so there's no cross-request mutation.
  • upsert_workspace_rating uses UPDATE-then-INSERT with an IntegrityError retry rather than ON CONFLICT. Worth calling out: a PG ON CONFLICT against a partial index needs the WHERE predicate repeated in the inference clause, which is a classic place the two migration tracks silently diverge. This design sidesteps it entirely.
  • The migration is complete and reversible. All four columns in all four places; SQLite guarded by _safe_add_column and re-runnable (ran it twice on a fresh DB — index SQL byte-identical; ran it against a simulated pre-ent#366 DB with legacy Tier-0 rows — columns added, rows preserved). Alembic chain is linear and resolves to a single head; no other open PR claims 0046_report_audience as a parent. I executed 0047's upgrade() and downgrade() against the real trinity-postgres container: the partial-index predicate matches SQLite exactly, all four uniqueness cases behave identically on both backends, and the downgrade restored the exact pre-migration column set.
  • Three of the four commits exist because you reviewed your own work and found real widening gaps. That is visible in the diff and it improved the result.

Blocking

1. The route bounds the row but not the turn it dispatches

portal_rating : rate_limiter.enforce(f"portal_rating:{email}:{agent_name}", 60, 60)   # one tier, hardcoded
portal_chat   : PORTAL_CHAT_BURST_LIMIT  = 20  / 60s      # env-tunable
                PORTAL_CHAT_HOURLY_LIMIT = 300 / 3600s    # env-tunable

Same principal, same agent, and both paths dispatch a full execute_task — but this route has no hourly tier and no env knob. And the dispatch has no comparison against prior state:

if result["comment_recorded"] and body.rating == "down":

So the partial UNIQUE makes the row idempotent while the side effect is not: re-rating the same message down with a tweaked comment fires a fresh agent turn every time. A rostered client can drive roughly 3600 turns/hour against one agent through the ratings route, versus the 300/hour the platform deliberately allows that same client through chat — about 12× its own stated budget, reached by clicking.

The docstring on the limit reasons about table growth, and the index already handles that. The expensive resource on this route is the turn.

Ask: a two-tier limit matching portal_chat's shape, plus dedup on (evaluator, target_kind, target_id) so a re-rate doesn't re-fire — effect_guard (#1084) is the existing primitive for exactly this, and it's what the sibling sinks use.

2. _is_machine_principal is a denylist over a free-text column

return bool(current_user.agent_name) or (current_user.mcp_scope in _MACHINE_SCOPES)

scope has no CHECK constraint, so this is a snapshot of live values rather than a closed set. Anything the predicate hasn't heard of reads as human and receives comments plus rater emails — connector, portal_delegate, any sixth scope, and also a NULL scope column, which dependencies.py:734 coerces to "user". It isn't reachable today only because those scopes are route-fenced away from /api/evaluations elsewhere in the call graph — which is precisely the "safety property held by a fact somewhere else" that this function's own docstring criticises the earlier version for relying on.

models.py:423-434 documents mcp_scope as existing so guards can be a fail-closed allowlist, and reject_non_interactive_principal is the shape. Suggest inverting: a person is mcp_scope is None or mcp_scope == "user"; everything else is a machine.

architecture.md records the same class from #848 — the !== "connector" check that "admitted every scope it had not heard of".

Non-blocking

  • The fence delimiter is a fixed literal and the comment isn't scanned for it. A comment containing a \n---\n line closes the fence early, and everything after it renders outside the "treat as data" region. The test asserts prompt.count("---") >= 2, which a fence-breaking payload also satisfies. This is the same weakness as routers/webhooks.py, so it isn't a regression — but that path takes operator-configured context and this one is, in the PR's own words, a box filled in by an annoyed stranger. A nonce in the delimiter would close it.
  • target_id survives redaction, and for a deliverable that weakens the identity scrub. It's an agent_reports.id the rated agent authored and chose the audience_email for, so the agent can re-identify the rater from its own state even though evaluator was stripped. No API route exposes it (_mapping_to_report withholds addressed_to_email), but the protection is weaker for deliverables than for messages while the docs describe it uniformly.
  • "The rated agent never reads the words" holds for the read API only. dispatch_capture_feedback hands that same agent the verbatim comment — by design, per AC #2, but the framing in the description and in architecture.md reads as absolute.
  • The background task receives body.comment raw rather than the service's stripped text_comment. Equal today at 2000 each, but they're independent constants.
  • PortalRatingRequest.target_kind / rating are bare str. The service validates and returns 422 (and it's tested), but Literal[...] would enforce at the boundary.
  • The new endpoint is described in architecture.md's evaluations block but isn't in an API endpoint table.
  • The description says "Related to Abilityai/trinity-enterprise#366". A closing keyword (Fixes Abilityai/trinity-enterprise#366) is the right form for the record. The automation is same-repo only, so it won't fire either way — someone needs to set status-in-dev on ent#366 by hand at merge.
  • Two INFO items, neither introduced here and neither needing action in this PR: the partial UNIQUE has a NULL-target_kind distinctness hole (identical on both backends, unreachable through the writer since target_kind is typed required); and portal_auth.py:138 applies reject_agent_principal on the platform branch but lets scope='system' through, so trinity-system could POST a rating as its owner.

Process

All CI green, including pg-migrations, schema-parity, prod-image-smoke and e2e. Security scans clean. Test coverage is strong and overwhelmingly non-happy-path — 27 backend cases naming each refusal shape individually, 22 frontend.

The feature flow uses free-form headings rather than the /validate-pr template and carries no file:line references. Noting rather than asking, since its sibling agent-evaluations.md is written the same way — the repo's convention has drifted from the skill's, and that's a separate conversation.

Separately from the above: this is stacked on #2383, which is currently CONFLICTING with changes requested, and 0047's down_revision is ent#365's 0046_report_audience. So the merge is blocked upstream regardless of what happens here.

@dolho
dolho force-pushed the feature/ent365-workspace-deliverables branch from 0116b30 to d0d833f Compare August 25, 2026 10:39
@dolho
dolho force-pushed the feature/ent366-workspace-ratings branch from 42704c8 to 5239ed8 Compare August 25, 2026 10:43
@dolho

dolho commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Code review — re-review at 5239ed8

Scope: origin/feature/ent365-workspace-deliverables...origin/feature/ent366-workspace-ratings — 25 files, ~2005 insertions.

Both previous blocking items are fixed: the dispatch is now claimed per (evaluator, target_kind, target_id) through the idempotency layer with the comment deliberately not a parameter, the route has portal_chat's two tiers, and _is_machine_principal is a fail-closed allowlist (_HUMAN_SCOPES = (None, "user")) with agent_name checked first and independently.

Five findings remain. The first two are new and neither is cosmetic.

High

1. routers/evaluations.py:156 — client rating comments and rater emails leak to every other client of a shared agent.

_redact_for_agent_principal redacts machine principals. But list_agent_evaluations is gated by get_authorized_agent_by_name → db.can_user_access_agent, which returns True for any user the agent is shared with (is_agent_shared_with_user, matching the user's email against agent_sharing). Workspace clients are exactly that set — service.agent_on_roster is built from agent_sharing — and routers/sharing.py:103/330 auto-adds a shared email to the login whitelist when email auth is on.

Scenario: acme-bot is shared with [email protected] and [email protected]. Bob down-rates a message and writes "your answer was garbage, and my SSN got quoted back at me". Alice signs in with her auto-whitelisted email, calls GET /api/agents/acme-bot/evaluations, and reads Bob's verbatim comment plus evaluator: "workspace:[email protected]". GET /api/evaluations has the same exposure via accessible_agent_names.

The stated model is "operator surfaces see everything" — but a shared non-owner is not an operator. The allowlist fix corrected which principals are machines; this is the orthogonal axis of which humans are operators, and it is currently everyone with access. Suggest narrowing target_id IS NOT NULL rows to owner/admin, or extending redaction to any reader who is neither the agent owner nor an admin.

Medium

2. db/evaluations.py:173 — the IntegrityError retry self-deadlocks on SQLite, which is the default backend.

upsert_workspace_rating opens with get_engine().begin() as conn: (:138), runs an UPDATE (0 rows) and then a failing INSERT — at which point pysqlite holds a RESERVED write lock on that connection, and a constraint violation rolls back the statement, not the transaction. The except IntegrityError: branch then opens a second connection (db/engine.py uses NullPool for SQLite, so it is a genuinely separate handle) and issues an UPDATE, which needs RESERVED and blocks on the first connection's own lock. With connect_args={"timeout": 30.0} that hangs a threadpool worker for 30 s and raises OperationalError: database is locked, which submit_rating turns into a 503 — precisely the "reads as your rating is recorded, not as a 500" outcome the comment says this design prevents.

Deterministic, not a flake, and reachable from two tabs or two devices (the sending guard covers one component instance). It works on PostgreSQL, so the default backend is the broken one. Fix: retry the UPDATE on the same conn after the failed statement, or use db.engine.make_insert(agent_evaluations).on_conflict_do_update(...), which exists for exactly this and is dialect-portable. Worth noting upsert_workspace_rating has no unit test at all — test_ent366_workspace_ratings.py stubs the db layer.

Low

3. PortalDeliverables.vue:67 — a deliverable's existing rating is never restored. PortalRating is mounted without :initial-rating, and there is no server-side equivalent of _attach_own_ratings for reports (agent_page.reports / fetchSessionDeliverables return no my_rating). A client marks a deliverable "Not what I needed", reloads, and both buttons show unpressed; clicking again passes nextRating(null, 'down') === 'down', so it re-POSTs and re-opens the comment box instead of being the documented no-op. The verified-live claim "pre-existing rating restored" holds for messages only.

4. PortalConversation.vue:112 — the reply you just read cannot be rated. Assistant messages appended during a live turn (messages.value.push({role:'assistant', ...}) at :481 and :887) carry no id, and v-if="m.id" hides the thumbs. Nothing reloads the thread after a turn, so the affordance is absent at exactly the moment of judgement and appears only after navigating away and back. Either stamp the message id onto the turn response, or refresh the thread on completion.

5. portalUtils.js:1210 — ratingTallyText is dead code, and its guarantees are tested against nothing shipped. PortalAgentPage.vue renders its own inline up / down spans plus ratingsCaption and never imports it. portalRatings.spec.js asserts the helper "never contains %" and distinguishes empty from unavailable — properties that hold for an unused function while the rendered tally is unguarded. Either use it in PortalAgentPage.vue (which would also give the deliberate per-target-kind wording) or drop it with its tests.

🤖 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-review of the delta since 42704c81, the commit my earlier review targeted.

Scope. This PR is stacked on #2383 (feature/ent365-workspace-deliverables), so everything below concerns only the ent#366 delta on top of that base. Both branches were force-pushed since the last round; #2383 is now MERGEABLE but still carries changes requested, and 0047_workspace_ratings's down_revision is ent#365's 0046_report_audience, so the merge remains blocked upstream regardless of the outcome here. All CI is green, including pg-migrations, schema-parity, prod-image-smoke and e2e.

What I re-checked. The single new commit (5239ed8a), re-verified against the primitives it calls (rate_limiter.enforce, idempotency_service.begin/complete/fail, dependencies.get_current_user); the full authorization and tenancy path end to end; the dual-track migration on both backends; and the frontend delta against design-system-contract.md.

Both earlier blocking findings are fixed

1. The route now bounds the turn. PORTAL_RATING_BURST_LIMIT / PORTAL_RATING_HOURLY_LIMIT mirror portal_chat's two tiers, burst-first, both env-tunable, and claim_capture_feedback_dispatch claims one dispatch per (evaluator, target_kind, target_id). The key deliberately excludes the comment, which is the right call — a key that moves with the text is a rename of the attack, not a dedup. With the per-target claim in place the turn count is now bounded by the number of distinct rateable targets, and since every rateable target is an agent message or a deliverable the agent itself produced, the amplification is roughly 1:1 with work the agent already did. That is a better bound than the one I asked for.

2. _is_machine_principal is now a fail-closed allowlist. _HUMAN_SCOPES = (None, "user") matches dependencies.py:734 exactly — mcp_scope=scope or "user" on the MCP-key branch, None on the JWT branch — and agent_name is still checked first and independently. test_a_scope_nobody_has_heard_of_is_a_machine parameterises over a scope that does not exist, which is the right thing to assert. This is the shape reject_non_interactive_principal uses and it closes the #848 class properly.

I also re-confirmed the parts that were already right and are unchanged: create_evaluation still carries require_admin + reject_agent_principal; _rating_target_is_visible still checks the target against the reader on all three conditions for a message and reuses ent#365's audience gate for a deliverable; the uniform 404 holds; the redaction is still applied at the single projection point in _to_response. I could not find a path by which an agent principal reaches the write. get_portal_principal's platform branch runs reject_agent_principal, and neither the platform nor the portal-session branch admits a rating written by the graded agent.

Blocking

1. The IntegrityError retry deadlocks against its own transaction on SQLite

db/evaluations.py, upsert_workspace_rating. The retry opens a second connection while the outer transaction is still open:

with get_engine().begin() as conn:          # outer transaction open
    ...
    try:
        conn.execute(insert(agent_evaluations).values(**insert_values))
    except IntegrityError:
        with get_engine().begin() as retry_conn:   # a NEW connection, inside the outer block
            applied = _apply(retry_conn)

db/engine.py configures SQLite with poolclass=NullPool and connect_args={"timeout": 30.0}, so the retry is a genuinely separate handle while the loser's own outer connection still holds the write lock taken by the failed INSERT. I reproduced this directly against a temporary SQLite database using the exact index, with the winner's row already committed and its connection closed, so the only lock in play is the loser's own:

outer UPDATE rowcount: 0 (falls through to INSERT)
outer INSERT IntegrityError: UNIQUE constraint failed: ...evaluator, ...target_kind, ...target_id
outer conn still in transaction: True
retry on separate connection FAILED after 2.1s: OperationalError: database is locked

At the production timeout that is a 30-second stall, and because SQLite takes a single database-wide write lock, every other write in the process blocks behind it for the duration. The request then surfaces as ClientPortalError(503, "Could not record that rating — try again.") via submit_rating's except Exception. On PostgreSQL it works, because the winner has committed by the time IntegrityError surfaces.

This matters because the comment above that block states the intent precisely — "it must read as 'your rating is recorded', not as a 500" — and on the default OSS backend, which is supported until 2026-09-01 per #1278, it does the opposite. The trigger is two concurrent first-ratings of the same target by the same person: two open tabs, or a client retrying a slow request, under --workers 2.

The fix is to run the retry after the outer with block has closed rather than inside it. No test currently exercises this path — every DB-layer test in test_ent366_workspace_ratings.py stubs the database, and none names the race or IntegrityError.

2. The dispatch claim is completed immediately, and the stated reason for that does not hold

claim_capture_feedback_dispatch calls complete() on the fresh claim before the background task has run, justified as:

Leaving the claim in_flight until the background task finished would block a legitimate later re-rate for the TTL window on any crash.

begin() returns replay=True for STATE_IN_FLIGHT and for STATE_COMPLETED, and the function returns False on decision.replay either way. So completing early blocks a later re-rate exactly as much as leaving it in flight would; it prevents nothing it claims to prevent. The only lifecycle call that makes a failed first attempt retryable is fail(), which releases the in-flight row, and it is never called.

The consequence is that a dispatch which fails — the agent is stopped, capacity is full, execute_task raises, all of which dispatch_capture_feedback swallows with a warning — is unretryable for the full 24-hour window, and every subsequent re-rate answers already_dispatched, which feedbackAcknowledgement renders as "Thanks — passed on to the agent." The client is told their feedback reached the agent in the one case where it provably did not.

I want to be clear that I asked for this dedup, so this is a consequence of my own request rather than something the PR got wrong on its own terms. But it needs resolving before merge. Keeping the claim in flight and calling complete() on success / fail() on exception from inside dispatch_capture_feedback fixes both the retry gap and the docstring.

There is a second, related case that the same mechanism creates: a client who re-rates the same target down with different words. The row is updated and the new comment is durable, but it is never dispatched, and the router justifies that with "the agent was already told about this target — it reads the row, not this message." It does not read the row — _redact_for_agent_principal, added in this same PR, strips comment for exactly that principal. So those revised words reach operators and never reach the agent, while the UI says otherwise. Either the acknowledgement should be honest for already_dispatched, or a genuinely different comment should be allowed to dispatch under the hourly ceiling that now exists. I do not have a strong preference between those two; the current combination is the one option that is not defensible.

Non-blocking

  • A deliverable rating never restores on reload. PortalDeliverables.vue:67 mounts PortalRating with no :initial-rating, and my_rating is attached to messages only (service.py:_attach_own_ratings, keyed on "message"). PortalConversation.vue:116 passes it correctly. So a rated deliverable always reloads showing unrated, the user can rate it again, and the second comment lands in the already_dispatched path above. This is the state nextRating's own comment forbids: "silently clearing a score locally would show the person a state the server does not have." The live verification in the description ("pre-existing rating restored") holds for messages only.
  • ratingTallyText, RATINGS_EMPTY_TEXT and RATINGS_UNAVAILABLE_TEXT have no production consumer. PortalAgentPage.vue:464 hardcodes its own ratingsCaption instead. Five assertions in portalRatings.spec.js guard a function nothing calls, and the "No ratings yet." empty state is unreachable because the tile is v-if'd away at zero. Either wire the util up or drop it with its tests.
  • Two interactive colours have no dark half, against design-system-contract.md line 18 ("Interactive accent: action-primary-600 light / 500 dark; hover 700 / 400; focus ring 500@40% / 400@42%"): the Send button is bg-action-primary-600 hover:bg-action-primary-700 with no dark override, and the textarea focus is ring-action-primary-500/40 focus:border-action-primary-500 with no dark half. Separately, PortalAgentPage.vue:68 adds dark:text-gray-600, which R1 in check-design-tokens.mjs states admits "no judgement and no exceptions" — it passes CI only because that checker iterates INK_LADDER_SWEPT, which does not list the portal tree. The rest of the new markup is clean: zero raw non-gray classes, zero hex, raw-color-baseline.json correctly untouched, and status/action tokens used properly throughout.
  • Accessibility gaps in the new component. aria-pressed is there as described, and the thumbs are real buttons with aria-label. The textarea has a placeholder but no label, aria-label or aria-labelledby, so its accessible name disappears as soon as the user types; and none of the three buttons carry a focus:/focus-visible: ring (they fall back to the UA default, since nothing resets it). The component also hand-rolls a textarea and two buttons rather than using BaseTextarea/BaseButton — consistent with the rest of components/portal/, which imports no Base* primitives, so noting rather than asking.
  • Layout stability. The comment form is a second root node under v-if, so opening it inserts roughly 60px inline and shifts everything below it in the thread; the subsequent commentBox.focus() then triggers an unmanaged scroll-into-view on the conversation's own scroll container. The tally tile likewise appears in the stat row the moment the first rating lands and is absent at zero, which is a footprint change with no empty state. All user-initiated rather than on data arrival, and the thumb row itself holds stable space from mount.
  • Double-submit is guarded, but by the rendered disabled attribute alone — there is no if (sending.value) return re-entrancy check in choose(). Real clicks are separate tasks so this holds in practice, and the server is an upsert behind a claim, so the blast radius is nil.
  • agent_evaluations has no retention window, and this PR is what makes that table hold client-authored free text. There is no agent_evaluations_retention_days in RETENTION_OPS_KEYS, no sweep in cleanup_service, no #1644 guard coverage, and no entry on GET /api/settings/retention. The gap is pre-existing from ent#206 — the same grep against origin/dev is empty — and the AGENT_REFS CASCADE bounds it per agent deletion, so I am not asking for it here. It is worth a follow-up issue, because a long-lived agent's client comments now never age out.
  • The agent-page tally is fleet-wide across all raters, so a client sees the aggregate of every other client's judgement and can subtract their own at low volumes; _rating_tally's "nothing here says who rated what" is a little stronger than what holds at n=1. I am flagging rather than asking, because the same page already ships total_executions, success_rate and a per-trigger timeline on the same fleet-wide basis — that posture was settled in ent#360 and this is consistent with it, not a new class. Gating the tile on total >= 3 would close it cheaply if you want it closed. I also confirmed that EvaluationCreate has no target_kind/target_id, so admin-written ent#206 rows cannot pollute this number today.

The earlier non-blocking items are unchanged and remain fine to carry: the fixed --- fence delimiter with no nonce, target_id surviving redaction, the background task receiving body.comment rather than the service's trimmed text_comment, the bare str typing on target_kind/rating, and the endpoint's absence from an API endpoint table. One is worth restating only because it has now been promoted into the requirements system of record: FR-5 and the architecture.md block both say the rated agent reads tallies "never the words", while dispatch_capture_feedback hands that same agent the verbatim comment by design. The read API claim is true; the absolute one is not, and requirements is the document future readers will trust.

Verdict

Requesting changes on the SQLite retry deadlock, and on the dispatch-claim lifecycle. Both are small and local. The two findings from the previous round are genuinely resolved, the authorization and tenancy surface holds up under a second pass, and the dual-track migration is complete and verified on both backends — single Alembic head confirmed with the repo's own check_alembic_heads.py, both tracks byte-identical on the partial-index predicate, schema.py/tables.py in step, and agent_evaluations already registered in AGENT_REFS.

@dolho
dolho force-pushed the feature/ent366-workspace-ratings branch from 5239ed8 to 0665fc0 Compare August 25, 2026 13:13
@dolho

dolho commented Aug 25, 2026

Copy link
Copy Markdown
Contributor Author

Code review — re-review at 0665fc0

Both fixes from the last round hold. _operator_for is fail-closed and resolved per agent rather than per row, the shared-non-owner disclosure is closed at the single projection point, and the IntegrityError retry is on the same connection inside a SAVEPOINT — which is the portable form, since SQLite tolerates connection reuse after a constraint violation and PostgreSQL aborts the transaction. The target-visibility gate, uniform 404, self-message refusal and fail-closed scope allowlist all re-read as sound.

Six findings.

Medium

1. client_portal/router.py:801 — a full agent turn runs inside BackgroundTasks, holding the HTTP response cycle open.

background.add_task(service.dispatch_capture_feedback, …) awaits execute_task, bounded only by the agent's execution_timeout_seconds (default 3600s). Starlette runs background tasks inside the response cycle — Response.__call__ awaits self.background() after sending the body — so the client's connection stays occupied for the whole turn and uvicorn's graceful shutdown blocks on it. A client down-rating an agent whose turn takes six minutes pins that browser connection for six minutes, and a deploy restart waits on it.

The portal's own precedent for this exact shape is service.start_portal_turn (service.py:2095): asyncio.create_task plus a strong-ref _INFLIGHT_TURNS set, specifically to avoid this. The PR comment says the dispatch is "handed off", which is the right intent — BackgroundTasks is not the mechanism that delivers it.

2. portalUtils.js:1210 — ratingTallyText is still wired to nothing, and the consequence is a real display defect.

Flagged last round as dead code; re-reading, it is worse than tidiness. grep -rn ratingTallyText src/ tests/ matches only the spec. PortalAgentPage.vue:65-71 hardcodes its own caption, so the tested "distinguishes nobody-rated from could-not-read" behaviour never ships — and when the tally read fails the backend returns {up:0, down:0, total:0, unavailable:true} and the template renders the large 0 / 0 numerals with a small "ratings unavailable" caption underneath. That is precisely the unread-tally-as-a-real-zero that _rating_tally's unavailable flag exists to prevent. Either render the helper, or suppress the numerals when unavailable.

3. portalUtils.js:1229 — already_dispatched says "passed on to the agent", but a revised comment never reaches it.

FEEDBACK_REACHED_AGENT includes already_dispatched, so the acknowledgement is FEEDBACK_SENT_TEXT. A client down-rates with "wrong format" (dispatched), then within the 24h idempotency window reopens the box and sends "actually the data is stale". claim_capture_feedback_dispatch returns False → already_dispatched → the UI says "Thanks — passed on to the agent." The row's comment is updated, but build_capture_feedback_prompt inlines the comment text into the first, now-superseded turn, and nothing re-reads the row — so the agent only ever saw v1.

The router comment ("it reads the row, not this message") describes the intended design; the prompt does the opposite. Either word already_dispatched as "recorded", or point the skill at the row instead of inlining the text.

4. PortalDeliverables.vue:67 — deliverable ratings never restore, which feeds straight into #3.

PortalRating is mounted without :initial-rating, and the deliverable payloads carry no my_rating (only PortalHistoryMessage got one). A client rates a deliverable "Not what I needed", collapses the card and reopens it: both thumbs render unpressed. Because rating is null, nextRating(null, 'down') returns 'down' rather than the no-op it returns for messages — so the click re-POSTs and re-opens the comment box as though this were a first rating, and then reports the false acknowledgement above.

Low

5. routers/evaluations.py:158 — _operator_for is an N+1 on the fleet list. db.can_user_share_agent(username, name) runs get_user_by_username (plus get_agent_owner for non-admins) once per distinct agent per request. GET /api/evaluations defaults to limit=100, so a fleet spanning 50 agents adds 50–100 queries to what was a single-query endpoint. Resolving the user row once outside the loop, or short-circuiting on role == "admin", keeps the fail-closed shape and removes the cost.

6. db/evaluations.py:120 — a down→up flip leaves the negative comment attached to a now-positive row. if comment is not None means a re-rate without a comment preserves the previous text. A client rates down with "this was useless" and then flips to up: the row is quality=1.0 with comment="this was useless", so operator surfaces show a thumbs-up carrying a complaint and the tally counts it positive. The docstring calls the retention deliberate, and the reasoning is good — but nothing at the read boundary distinguishes "kept on purpose" from "stale text from the rating I retracted". At minimum the response should say when the comment predates the current quality.

🤖 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-review at 0665fc04

Rebase first: git diff d0d833f5 5239ed8a and git diff 88efbe7d fe72bc2c are byte-identical as patches (25 files, 2005 insertions each), so the rebase carried no content change — and 5239ed8a is the pre-rebase fe72bc2c, meaning "bound the turn, not the row" was already in the tip I reviewed last round. The only genuinely new commit is 0665fc04.

Your own re-review landed while I was reading. Your findings 2, 4 and 5 match non-blocking items I had already raised, so I am not restating them; your 1, 3 and 6 are yours and I have not independently verified 1 or 6.

Prior blocking findings

1. The IntegrityError retry deadlock — FIXED, and my severity last round was wrong

db/evaluations.py:174 now uses with conn.begin_nested(): with applied = _apply(conn) at :197 — the second connection is gone. I verified it empirically rather than by inspection, isolating the retry branch with a deterministic IntegrityError while the caller holds its write lock:

PRE-FIX  (fe72bc2c == 5239ed8a): 31.04s → OperationalError: database is locked
                                  [SQL: UPDATE agent_evaluations SET quality=?]   ← the retry's own UPDATE
POST-FIX (0665fc04):              0.00s → re-raises the original IntegrityError   ← connection still usable

The SAVEPOINT is doing real work: after the constraint violation, _apply(conn) still executes.

The correction is mine to make. That finding was mine rather than the ticket's, and I overstated its reachability. Measuring again: a 0-row UPDATE does take SQLite's RESERVED lock under journal_mode=delete (a second connection blocked 2.08s, then database is locked). So two concurrent first-ratings serialize at the UPDATE, the loser's UPDATE then matches the winner's committed row, and the IntegrityError branch is unreachable on SQLite. The reachable backend is PostgreSQL, where the pre-fix second connection worked. The fix is correct and strictly better, and the SAVEPOINT is genuinely required for PG portability — but "a 30-second stall in production" was not right, and I am recording that rather than leaving it in the thread.

2. The dispatch claim lifecycle — entirely unchanged, still blocking

client_portal/service.py:3143 still calls idempotency_service.complete(decision, None, {"dispatched": True}) before the background task runs, and :3203-3207 still swallows a failed dispatch with except Exception: logger.warning(...) — fail() is never called anywhere.

The stated reason still does not hold: idempotency_service.py:406-410 (IN_FLIGHT) and :411-415 (COMPLETED) both return replay=True, so completing early blocks a later re-rate exactly as much as leaving the claim in flight would. Only fail() (:476-483) releases the row.

The consequence is unchanged. A dispatch that fails — agent stopped, capacity full, execute_task raises — is unretryable for the full 24-hour window, and every subsequent re-rate answers already_dispatched, which portalUtils.js:1229 maps into FEEDBACK_REACHED_AGENT and renders as "Thanks — passed on to the agent." The client is told their feedback reached the agent in the one case where it provably did not.

Your finding 3 covers the wording half and reaches the same place from the prompt side; the retryability half is the part still unaddressed by either of us. The platform already ships the correct shape: idempotency_service.effect_guard (:380-386) does try/except BaseException: fail(decision); raise, else: complete(...), and distinguishes in-flight (409) from completed (replay). claim_capture_feedback_dispatch hand-rolls a broken subset of it.

Also still true, and now demonstrably so: router.py:809-811 justifies not re-dispatching a revised comment with "the agent was already told about this target — it reads the row, not this message". It does not read the row — routers/evaluations.py:115-120 nulls comment for every machine principal, added in this same PR. Whichever remedy you pick, that comment has to go.

0665fc04 reviewed as new code

"A shared client is not an operator" is real, unrelated to either blocking finding, and it narrows authorization — I looked for widening and found none. list_agent_evaluations was gated by can_user_access_agent, which is true for any shared user, and Workspace clients are exactly that set — so Bob's verbatim comment and workspace:bob@… crossed to Alice. It is now gated on can_user_share_agent (db/agent_settings/sharing.py:274-284, owner ∪ admin — the correct predicate), resolved per agent in _operator_for (routers/evaluations.py:133-161), fail-closed on exception with a frozenset() default, and passed on all four read paths (:208, :221, :234, :264). Ordering is safe: _is_machine_principal is evaluated first at :115, so an agent key whose owner happens to be an operator is still redacted. No callers outside that file, and no frontend consumer of /api/evaluations exists.

The portal-side rating reads were already clean: list_workspace_ratings_for_targets (db/evaluations.py:228-236) is evaluator-scoped and returns target_id → quality only, and workspace_rating_tally (:246-263) returns counts.

New findings

MEDIUM — the race test does not test the race. test_two_people_racing_the_same_target_both_get_a_recorded_rating builds its schema from db/tables.py via agent_evaluations.create(engine) (fixture at tests/unit/test_ent366_workspace_ratings.py:592-606), and tables.py declares zero indexes (grep -c "Index(" → 0), so the partial UNIQUE never exists in the test database. I instrumented it: zero IntegrityErrors are raised and the retry branch is never entered. It passes only because SQLite serializes at the UPDATE. 0665fc04's message claims "a genuine IntegrityError from a genuine INSERT, not a synthesised one", which is not what the test does. One line in the fixture — CREATE UNIQUE INDEX … WHERE target_id IS NOT NULL — fixes it. Separately, the retry's happy path (the loser's UPDATE returns a row), which is the PostgreSQL-reachable one, has no coverage at all.

LOW — _operator_for is an N+1 on the fleet list. :145-161 calls can_user_share_agent once per distinct agent, and each call does get_user_by_username for the same user (sharing.py:276). There is no admin short-circuit despite admin returning True unconditionally (:280-281). The fleet route allows limit=500. This is your finding 5 reached independently; resolving the user row once outside the loop keeps the fail-closed shape.

LOW — doc drift inside the security-critical function. routers/evaluations.py:107-108 says "Quality, target and evaluator stay… an operator surface loses nothing", while :128-129 strips the evaluator, and non-operator humans now lose the comment. The name _redact_for_agent_principal no longer describes what it does either.

INFO — comment_withheld plus a surviving target_id/quality tells a co-shared client that another client rated a shared target down and wrote something. That follows from the docstring's intent; noting only.

INFO — src/backend/enterprise is update = none and unreadable from this clone. If it carries an evaluations read path, it needs the same operator_agents argument.

Base branch and migrations

The base needs retargeting to dev. The PR still targets feature/ent365-workspace-deliverables, which is merged; GitHub is attributing merge commit 88efbe7d as a seventh commit. Merging as-is lands into the stale feature branch rather than dev. There is no diff pollution — ent#365 branched from 36877bd5, so diff(d0d833f5, 0665fc04) and diff(dev, 0665fc04) are identical at 25 files / 2261 insertions — so this is purely the target.

Alembic resolves correctly: scripts/ci/check_alembic_heads.py on an exported copy reports 48 revisions, 1 head (0047_workspace_ratings), and 0047.down_revision = "0046_report_audience", which is now on dev. CI is all green including pg-migrations, schema-parity, prod-image-smoke and e2e; mergeStateStatus: CLEAN.

Regression checks — all intact

create_evaluation's fence (routers/evaluations.py:241, :249); the two rate-limit tiers burst-first (router.py:118-119, :765-772) mirroring portal_chat (:722-728); _HUMAN_SCOPES = (None,"user") at :60 with agent_name checked first and independently (:84-88), matching dependencies.py:734; _rating_target_is_visible's three conditions (service.py:3025-3027) and the deliverable audience gate plus agent equality (:3029-3032); the uniform 404 (service.py:3058-3061 → router.py:780-781); no agent write path (portal_auth.py:141); dual-track migrations (migrations.py:3538/3937, 0047_workspace_ratings.py:12-13, schema.py:694-705/1670-1677, tables.py:613-619); AGENT_REFS registration (db/agent_cleanup.py:211).

Verdict

Requesting changes on two items: the dispatch-claim lifecycle (prior finding 2, unchanged), and retargeting the base to dev. The test-fixture index is a should-fix in the same pass — the fix is proven correct, but the PR currently claims coverage it does not have.

The round-2 blocking findings are otherwise resolved, 0665fc04 closes a real cross-client disclosure without widening anything, and the authorization, tenancy and dual-track migration surfaces hold up under a third pass.

The non-blocking items from last round are all still present: deliverable rating not restored (PortalDeliverables.vue:67-69, service.py:2256-2257); ratingTallyText and its two constants unused with seven spec assertions (portalRatings.spec.js:68-86); missing dark halves (PortalRating.vue:48, :53) and dark:text-gray-600 (PortalAgentPage.vue:68), which R1 forbids with "no judgement and no exceptions" (check-design-tokens.mjs:111-112) and which passes CI only because components/portal is absent from INK_LADDER_SWEPT (:125-144); the textarea with no accessible name and no focus rings (PortalRating.vue:11, :42-49, :53, :58); the comment form as a second v-if root with an unmanaged focus() (:37-62, :134); no agent_evaluations retention window; the fixed --- fence with no nonce (service.py:3164, :3167); target_id surviving redaction; raw body.comment handed to the task rather than the trimmed text_comment (router.py:805); bare str types (models.py:413, :415); the endpoint's absence from an API endpoint table; and FR-5 plus the architecture.md block still saying the rated agent reads tallies "never the words" while service.py:3166 hands it the verbatim comment by design.

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

Fourth pass — 0665fc04

There is no delta. The tip is the same commit my last review targeted; git log origin/feature/ent365-workspace-deliverables..origin/feature/ent366-workspace-ratings still ends at 0665fc04. So this pass is not a re-read of a fix — it is a fresh hunt on unchanged code, plus a re-confirmation of the two items that were blocking. CI is green across the board (pg-migrations, schema-parity, prod-image-smoke, e2e, gitleaks, the three guards).

Prior blocking items — both verbatim unchanged

1. The dispatch-claim lifecycle. client_portal/service.py still completes the claim before the work runs:

decision = idempotency_service.begin(scope, key)
if decision.replay:
    return False
idempotency_service.complete(decision, None, {"dispatched": True})
return True

and dispatch_capture_feedback still ends except Exception: logger.warning(...). fail() appears nowhere in the file. Nothing about the consequence has changed: a dispatch that raises — agent stopped, capacity full — is unretryable for the idempotency window, every later re-rate answers already_dispatched, and portalUtils.js renders that as "Thanks — passed on to the agent." The one case where it provably did not.

idempotency_service.effect_guard is the shape that exists for this: fail(decision); raise on the exception path, complete(...) on the else. claim_capture_feedback_dispatch is a hand-rolled subset of it that keeps only the half that cannot release.

The router comment at the already_dispatched branch — "the agent was already told about this target — it reads the row, not this message" — is still there and still false: routers/evaluations.py nulls comment for every machine principal, so the agent cannot read the row. Whichever remedy you pick, that sentence has to go with it.

2. Base branch. Still targeting feature/ent365-workspace-deliverables. #2383 is now merged, 0046_report_audience is on dev, and git diff --stat origin/dev..0665fc04 is 25 files / 2261 insertions — identical to the diff against the old base, so retargeting costs nothing and merging as-is lands in a stale feature branch.

New this pass

MEDIUM — db/tables.py declares zero indexes, and this PR is the one that makes that a correctness problem.

grep -c "Index(" src/backend/db/tables.py → 0. Every index in the platform lives only in db/schema.py (SQLite) and its Alembic revision (PG), never in the MetaData that migrations/env.py uses as target_metadata. Until now that was cosmetic — a missing performance index in a model is noise. idx_agent_evaluations_rating_target is not a performance index. It is the uniqueness rule, and the PR body says so: "The index carries the rule so two rapid clicks can't race into two rows."

So the first alembic revision --autogenerate anyone runs against this table proposes op.drop_index("idx_agent_evaluations_rating_target"), and if it is accepted, "one rating per person per thing" silently becomes "one row per click" — no error, no test failure, just a tally that counts clicks. Declaring the index on the Table (or an __table_args__-equivalent Index(...) beside it) costs one line and removes the hazard. It is also the direct cause of the next finding, which is the same root seen from the test side.

MEDIUM — a platform principal's rating lands in the client-facing tally, indistinguishable from a client's.

router.py passes include_owned = principal.is_platform into submit_rating, so an owner or admin previewing the Workspace can rate. workspace_evaluator(email) produces the same workspace:<email> shape for them as for a client, and workspace_rating_tally counts every row with target_id IS NOT NULL for the agent, with no principal-kind filter.

Consequence: an owner test-clicking "Not what I needed" on their own agent moves the number every client of that agent sees on the agent page, permanently, with no way to separate operator clicks from customer ones — and _redact_for_agent_principal then anonymises both to the bare kind workspace, so the distinction is unrecoverable downstream too. AC #4's tally is "how did this land with people"; an operator preview is not the audience it is measuring. Either exclude platform-principal rows from workspace_rating_tally, or record the principal kind on the row so the tally can.

I am not asking you to block a platform principal from rating — being able to try the affordance is right, and include_owned is consistent with every other portal route. It is the tally that should not count it.

MEDIUM (restated, now measured from both ends) — the race test cannot enter the branch it claims to test.

The ratings_db fixture builds its schema with agent_evaluations.create(engine, checkfirst=True) from tables.py, and per the finding above tables.py has no indexes at all — so the partial UNIQUE does not exist in the test database, no IntegrityError is possible, and the retry branch is dead code under test. 0665fc04's message claims "a genuine IntegrityError from a genuine INSERT, not a synthesised one"; the test's own docstring hedges on thread interleaving, but the reason it never reproduces is simpler than interleaving — there is no constraint to violate. test_a_second_rating_of_the_same_thing_is_a_correction passes for the same reason and proves nothing about the index either.

One line in the fixture (CREATE UNIQUE INDEX ... WHERE target_id IS NOT NULL) fixes both, and the retry's happy path — the loser's UPDATE returning a row, which is the PostgreSQL-reachable one — then gets its first coverage.

Closed from last pass

The enterprise submodule has no evaluations read path. I left this open as an INFO because the submodule is update = none; it is mounted in this clone, and grep -rn "agent_evaluations\|workspace_rating\|list_agent_evaluations" src/backend/enterprise/ returns documentation only (docs/planning/AGENT_EVAL_STRATEGY.md), no code. So _to_response/_operator_for really is the single projection point across both editions, and nothing private needs the operator_agents argument.

Re-verified as still sound

The write fence (require_admin + reject_agent_principal on create_evaluation); _HUMAN_SCOPES = (None, "user") as a fail-closed allowlist with agent_name checked first; _operator_for fail-closed on exception with a frozenset() default and resolved once per agent; can_user_share_agent taking a username (it does — sharing.py) so the operator set is not silently empty for everyone; _rating_target_is_visible's three message conditions plus the deliverable audience gate; the uniform 404; workspace_evaluator lowercasing on both principal paths (decode_portal_session and the platform branch both lowercase, so the evaluator identity is stable and cannot fork per casing); _attach_own_ratings bounded at the 100-row history default, so the IN (...) clause is nowhere near a variable limit; v-if="m.id" correctly suppressing the thumb on a locally-composed live-turn message; the tally's target_id IS NOT NULL filter keeping Tier-0 rows out; and the dual-track migration on both backends.

Verdict

Requesting changes on the two unchanged items — the dispatch-claim lifecycle and the base retarget. The two new MEDIUMs and the test-fixture index are should-fix in the same pass; none of them is a reason to hold the PR on its own, but the tables.py one is the cheapest permanent fix in the list and it is protecting the property the whole design rests on.

Everything the last three passes confirmed still holds. The authorization, tenancy, redaction and migration surfaces have now survived four independent reads without a hole; what is left is lifecycle and bookkeeping.

dolho and others added 7 commits August 26, 2026 10:24
One click on the thing being judged: thumbs on an agent message, Useful / Not
what I needed on a deliverable card — the affordance ent#365 left that card as
the surface for — and a comment box on the negative.

A rating is a PLATFORM PRIMITIVE, not a skill, and the reason is the eval
epic's: a capture-feedback skill runs inside the agent, so it can summarise
charitably, omit, or fail silently, and a user rating is the one score that must
not pass through the thing being scored. So this AMENDS ent#206's write fence to
admit a `workspace:<email>` evaluator rather than working around it. The rated
agent still has no write path.

Targets are checked against the READER, because message and report ids are both
global: a message must belong to this agent AND this client and be the agent's
message (rating your own is refused — it would put a self-rating in the agent's
tally), and a deliverable reuses ent#365's audience gate so "can rate" and "was
addressed to you" are one question answered in one place. A target that fails
either check returns the same 404 a missing one does, so this is not an
existence oracle.

`UNIQUE(evaluator, target_kind, target_id) WHERE target_id IS NOT NULL` makes a
second thumb a CORRECTION rather than a second vote, which is what makes the
agent-page tally count people rather than clicks. That tally is raw counts and
never a percentage: one thumbs-down out of one rating renders as "100%
negative", a number that looks like evidence and is not.

The issue's open grooming question is decided and implemented: the rated agent
reads its own tallies and never the words. A score an agent can read is a loop
it may start optimising for, and the comment is untrusted text written by an
annoyed stranger — handing it verbatim to the agent being criticised is a
prompt-injection path into it. `comment_withheld` lets a reader tell "no
comment" from "not yours to read"; operator surfaces are unchanged.

The words reach the agent only through `capture-feedback`, fenced as data with
the framing routers/webhooks.py already uses, dispatched as its own background
execution — never as a message in the client's thread, which would be a second
unasked-for reply in the conversation someone just complained about. Absent the
skill the rating and comment are still durable and the UI says "recorded"
instead of promising a follow-up (AC #6).

Verified live end to end: rate, change your mind (one row, updated), a target
that isn't yours 404s, a bad kind 422s, the tally reads 0/1, an operator sees
the comment and the RATED AGENT reads `quality: 0.0` with `comment: None,
comment_withheld: true`. In the browser: 15 thumb pairs, the existing rating
restored from history, the box opening on the negative, and the honest
acknowledgement.

One thing this deliberately does NOT do: stamp the feedback turn with
`source_channel=portal`. `test_2157_portal_narration` pins that stamp to exactly
the two portal turn-creation sites, and it is right — the stamp means "an
exchange on the Workspace surface", and this turn has no surface: nobody sees
its output and it must not be answering anyone.

Stacked on feature/ent365-workspace-deliverables: the deliverable card this
attaches to exists only there.

Related to Abilityai/trinity-enterprise#366

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
**1. The redaction covered one of three read paths.** `_redact_for_agent_principal`
was applied inside `list_agent_evaluations` only, so `GET /api/evaluations` and
`GET /api/evaluations/{id}` still handed the rated agent its own comments — an
agent-scoped key resolves to its OWNER, so `accessible_agent_names` includes the
agent itself. That is the "defense added to one of N call sites" class this repo
keeps re-learning (#686, #1264, #1153), committed by me in the change whose whole
point is that boundary.

Fixed structurally rather than by adding two more calls: the redaction moved
inside `_to_response`, and `current_user` is a REQUIRED parameter of it, so a new
read path cannot compile without deciding. Verified live on all three paths — the
rated agent reads `comment: None, comment_withheld: true` while an operator still
reads the words.

**2. The dispatch imported a name that does not exist.** `from
services.task_execution_service import task_execution_service` — there is no
module-level singleton, only `get_task_execution_service()`. Every unit test
stubbed around the dispatch, so the suite was green while the background task
raised ImportError on every negative rating with a comment. Found by running it
against a live instance, which is the only place it could have been found.

Both now have tests that would have caught them: one asserts the projection's
signature and that no call site omits the caller; the other exercises the real
import and call signature with only the execution replaced, and pins that the
turn does NOT claim a `source_channel` (#2157 FR-7).

Live after the fix: `capture_feedback: dispatched`, a new execution row appears,
`triggered_by=public`, `source_channel` empty, carrying the framed prompt.

Related to Abilityai/trinity-enterprise#366

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

Second review pass. The first one hid the comment and left
`evaluator: "workspace:[email protected]"` on the row — so the rated agent
could not read the complaint but could name the complainant.

That is arguably the more actionable half. An agent that knows a specific person
rated it down is better placed to change its behaviour toward that person than
one that read the words, which is the failure mode the grooming decision exists
to prevent; and it hands the agent a client identity attached to a judgement,
which is a different fact from the identity it already has from talking to them.

The KIND survives (`workspace`), because "a person rated this" is the signal the
agent is allowed — it is what distinguishes a human thumb from a Tier-0 pass.
Only the workspace prefix is anonymised: blanking a platform evaluator name would
cost the agent the ability to tell a machine grade from a human one, and it
carries no person.

Live: the rated agent now reads `evaluator: "workspace"` with no email anywhere
in the payload; an operator still reads both the identity and the words.

One of my own tests asserted object identity (`out is row`) for a no-comment row,
which this correctly breaks — the projection copies now. Rewritten to assert the
rule it meant: `comment_withheld` means "there is text you may not read", never
"there was no text".

Related to Abilityai/trinity-enterprise#366

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

Third review pass, closing the residual the second pass stated instead of
fixing. The gate keyed on `agent_name`, which is set only for `scope="agent"`,
so `trinity-system` read both the client's words and the email attached to
them — and it bypasses permission checks, so it reads EVERY agent's rows, not
just its own.

My argument for leaving it was that no rating can target a system agent (the
portal roster excludes them), which is true and is exactly the reasoning this
repo's learnings ledger warns about: a safety property that holds only by a fact
in a different module, which the function neither states nor enforces. It was
also the wrong frame. The risk is not "the rated agent reads its own grade" — it
is "a person's words and identity enter a machine context", and the orchestrator
is a machine context.

`_is_machine_principal` now covers `agent` and `system`. A `user`-scoped MCP key
stays unredacted: it is a person's own credential, an operator running a script
is still the operator, and redacting there would break the surfaces the eval
epic exists to serve. Checked that nothing shipped needs a system-scope read of
comments — the Tier-0 evaluator writes server-side, not through this API.

Live, all three principal kinds:

  agent      comment None      evaluator 'workspace'                    email leaked: no
  system     comment None      evaluator 'workspace'                    email leaked: no
  admin JWT  comment "Totals…" evaluator 'workspace:[email protected]'  full access

Related to Abilityai/trinity-enterprise#366

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…an allowlist (ent#366)

Two findings from review, both about a guard that was narrower than the thing it
guards.

**The route bounded the row and not the turn it dispatches.** The partial UNIQUE
makes the rating idempotent — a second thumb is a correction — but the side
effect was not: `if result["comment_recorded"] and body.rating == "down"` fired
a fresh `execute_task` on every re-rate, so tweaking the comment and clicking
again was a turn generator. With one 60/min tier and no dedup, a rostered client
could drive roughly 3600 agent turns an hour through this route against the 300
the platform deliberately allows that same client through `portal_chat` — about
12× its own stated budget, reached by clicking. The docstring reasoned about
table growth; the index already handles that. The expensive resource here is the
turn.

So: two tiers with `portal_chat`'s shape and ordering (burst first, so a client
held at the per-minute limit does not also burn their hourly budget), both
env-tunable, hourly equal to chat's — and `claim_capture_feedback_dispatch`,
which claims one dispatch per `(evaluator, target_kind, target_id)` through the
existing idempotency layer. The key is resolved identity ONLY; the function is
not even given the comment, because a key that moves with the text is a rename
of the attack rather than a dedup (`derive_effect_key`'s rule, #1084). Fail-open
on a dedup hiccup — the rate limits are the bound that survives that — and the
words are recorded in full on every re-rate regardless, since the row write
happens first. A suppressed dispatch answers `already_dispatched`, which the UI
reads as "passed on to the agent": true, because it was, on the first one.

**`_is_machine_principal` was a denylist over a free-text column.** `scope` has
no CHECK constraint, so `mcp_scope in ("agent", "system")` is a snapshot of live
values, and anything it had not heard of — `connector`, `portal_delegate`, a
sixth scope, a NULL coerced to `"user"` — read as a PERSON and received the
comment plus the rater's email. It was unreachable only because those scopes are
route-fenced away from `/api/evaluations` elsewhere in the call graph, which is
precisely the safety-property-held-somewhere-else the function's own docstring
objects to. architecture.md records the same class from #848: the
`!== "connector"` check that "admitted every scope it had not heard of".

Inverted to `_HUMAN_SCOPES = (None, "user")` — the JWT branch and a person's own
credential — with `agent_name` still checked first and independently. A scope
added tomorrow is redacted the day it appears.

Related to Abilityai/trinity-enterprise#366
…not deadlock on itself (ent#366)

**One client's words were readable by every other client of the same agent.**
The machine/human split was the right axis and not the only one.
`list_agent_evaluations` is gated by `can_user_access_agent`, which is True for
any user the agent is SHARED with — and Workspace clients are exactly that set
(`agent_on_roster` is built from `agent_sharing`), with `routers/sharing.py`
auto-adding a shared email to the login whitelist when email auth is on. So
Bob's verbatim complaint, and the `workspace:[email protected]` naming him, crossed to
Alice through `GET /api/agents/{name}/evaluations`, and the same way through the
fleet list.

"Operator surfaces see everything" is the right model; a shared non-owner is not
an operator. Owner ∪ admin is, and `can_user_share_agent` is already that exact
predicate. `_operator_for` resolves it once per agent per request — not per row,
which would make a 200-row page 200 lookups — and fails CLOSED, so a lookup that
raises withholds rather than discloses. `operator_agents` defaults to the empty
set for the same reason: a caller that forgets it redacts.

**The `IntegrityError` retry self-deadlocked on SQLite, the default backend.**
It opened a SECOND connection while the first still held the RESERVED write
lock for the life of its transaction, so the retry's UPDATE waited on a lock its
own caller was holding — 30s of `connect_args["timeout"]`, then
`database is locked`, which `submit_rating` turns into the 503 this design
exists to avoid. Deterministic, not a flake, and reachable from two tabs (the
client-side `sending` guard covers one component instance). PostgreSQL tolerated
it, which is why the default backend was the broken one.

The retry now runs on the SAME connection, inside a SAVEPOINT. The savepoint is
load-bearing for portability, not decoration: SQLite lets you reuse a connection
after a constraint violation (verified on SQLAlchemy 2.0.51), PostgreSQL aborts
the transaction — so a bare same-connection retry would have fixed one backend
and broken the other.

The upsert had no test at all. It now has three: a re-rate is a correction on
one row and does not retract the words; two threads racing the same target both
end up recorded; and a structural pin that the retry uses the same connection
inside a savepoint. That last one is deliberately structural — a concurrent
deadlock repro cannot be made reliable in a unit test, and a first attempt at a
timing assertion passed against the BROKEN code (the synthesised failure never
executed an INSERT, so no write lock was ever taken). It is verified to fail on
the pre-fix form and pass after.

The three remaining low findings — a deliverable's rating not restored, the
just-read reply not rateable until a reload, and the unused `ratingTallyText` —
are left for a follow-up; none is a correctness or disclosure defect.

Related to Abilityai/trinity-enterprise#366
…perator previews (ent#366)

Four review findings from @obasilakis.

1. THE CLAIM LIFECYCLE. `claim_capture_feedback_dispatch` completed the claim
   before the work ran, so a dispatch that raised — agent stopped, capacity
   full — was unretryable for the whole idempotency window, and every later
   re-rate answered `already_dispatched`, which the UI renders as "passed on to
   the agent". Exactly the case where it provably was not. The claim is now
   handed to the caller in-flight and settled by `dispatch_capture_feedback`:
   complete on success, fail() on the exception path — the `effect_guard` shape,
   hand-rolled only because the claim spans a BackgroundTasks boundary. The
   settle never raises; a claim that cannot be settled decays with its TTL.

   The router's `already_dispatched` comment claimed the agent "reads the row";
   routers/evaluations.py nulls `comment` for every machine principal, so it
   cannot. That sentence is gone with the behaviour it described — and the
   branch now honestly means "already delivered", since a failure releases.

2. THE UNIQUENESS RULE IS NOW ON THE MODEL. tables.py declared no indexes at
   all, and migrations/env.py autogenerates against that MetaData — so the
   first `--autogenerate` proposes dropping idx_agent_evaluations_rating_target,
   and accepting it turns "one rating per person per thing" into "one row per
   click": no error, no failing test, a tally that counts clicks. Declared with
   the identical partial predicate (verified byte-equivalent DDL). This also
   gives the race test a constraint to violate — the fixture builds its schema
   from this MetaData, so the retry branch was previously unreachable.

3. OPERATOR PREVIEWS ARE RECORDED BUT NOT COUNTED. `include_owned` lets a
   platform principal rate, which is right. Counting it in a number shown to
   every client of that agent is not: an owner test-clicking moved it
   permanently, and the agent-principal redaction anonymises both kinds, so it
   could not be separated afterwards either. The kind now rides on the row
   (`operator:` vs `workspace:`) because nothing else on the table can tell
   them apart. The tally prefix-MATCHES clients rather than excluding
   operators, so a future evaluator kind is excluded by default. The redaction
   covers the new prefix too — otherwise an operator's address would have been
   the one identity still reaching the graded agent.

391 passed across the ratings, evaluations, portal and schema-parity suites.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@dolho
dolho force-pushed the feature/ent366-workspace-ratings branch from 0665fc0 to 92ef324 Compare August 26, 2026 07:25
@dolho
dolho changed the base branch from feature/ent365-workspace-deliverables to dev August 26, 2026 07:25
dolho added a commit that referenced this pull request Aug 26, 2026
…ique (ent#457)

#2384 mints an 0047 off the same parent. Ids are strings so the prefix is only
a human ordering cue, but a duplicate one is what makes a forked graph hard to
read later (ent#443 precedent). Both still declare down_revision = 0046, so
whichever merges SECOND forks the graph and needs an alembic merge revision —
check_alembic_heads fails loudly there rather than silently applying nothing.

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

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

Approving — this clears my earlier CHANGES_REQUESTED.

All four items the last review blocked on are fixed and verified in head:

  1. Dispatch-claim lifecycle — claim_capture_feedback_dispatch now returns the in-flight claim, _settle_capture_feedback_claim calls complete()/fail() on both paths, and the router's inaccurate "the agent reads the row" comment is replaced with an accurate one.
  2. Base retargeted to dev.
  3. db/tables.py now declares the partial UNIQUE as an Index(..., unique=True, sqlite_where=..., postgresql_where=...) — the rule, not a perf index.
  4. Evaluator carries operator: vs workspace:; the tally prefix-matches workspace:% so a future kind is excluded by default.

Two things to settle before you merge, neither of which needs another review round:

  • backend-unit-test and codeql have never run on this branch. The force-push at 09:25 CEST preceded the base change by 7s, so at push time the base was still feature/ent365-workspace-deliverables and neither workflow triggers on a base change. A no-op push will arm them.
  • Alembic fork with #2386: this PR's 0047 and #2386's 0048 both declare down_revision = "0046_report_audience". Whichever lands second forks the graph, and since upgrade head resolves its target before applying anything, it applies zero revisions — check_alembic_heads is an unconditional required gate and will catch it, but the fix is an alembic merge revision. Sequence these two deliberately.

Still open, follow-up-sized, not gating: the retry's PostgreSQL-reachable happy path has no behavioural coverage (the existing test is an inspect.getsource substring assertion); _operator_for is still an N+1 with no admin short-circuit; and _redact_for_agent_principal's docstring still says the evaluator stays while the code strips it.

@dolho
dolho enabled auto-merge August 26, 2026 19:10
@dolho
dolho merged commit 7750450 into dev Aug 27, 2026
24 of 25 checks passed
dolho added a commit that referenced this pull request Aug 27, 2026
…nd converge the migration line (ent#457)

Review finding 4, the half that was left. The claim was downgraded in the
`_resolve_portal` docstring and in `architecture.md`, and left standing in the
two places the reviewer rightly called the ones that matter most:

- `channel-completion-report.md` — "the Workspace polls its threads, so
  'degrades to poll' holds by construction". It is what the next person builds
  on.
- `test_2157_portal_narration.py` — "the assistant message the client reads on
  the next poll … AC #7's 'degrades to poll' is the only mode it has". A
  sentence in a test docstring reads as VERIFIED rather than as claimed, and a
  green suite beside a false one is what makes the gap permanent.

Neither is true: `PortalConversation.vue` loads history on mount and on a prop
change, `stores/clientPortal.js` says outright that `refreshThreads()` is
event-driven rather than periodic, and the Workspace's only interval is the 20s
asks poll, which fetches asks and nothing else. Both now say what actually
happens — the row is durable and arrives at the client's next reload or thread
switch — and neither claims the delivery the follow-up poll would provide.

## The migration fork, now decidable

0047 (#2384, ent#366) and this 0048 both declared
`down_revision = "0046_report_audience"`. That is a fork, and a fork is worse
than it looks: `alembic upgrade head` is singular and resolves its target BEFORE
applying anything, so two heads apply ZERO revisions — not merely the offending
one, but everything merged since the fork — and PostgreSQL boots on a schema
that has silently stopped advancing. `check_alembic_heads` cannot catch it on
either PR alone, which is why both were green.

#2384 merged first, so the order is no longer hypothetical: 0047 is on `dev` and
may already be applied, while this revision is applied nowhere. Re-parenting the
unapplied one onto the applied one converges the line and needs no merge
revision — `alembic merge` is for the case where BOTH forked revisions may exist
in some database, and taking it here would leave a permanent extra node for
nothing. Verified: `check_alembic_heads` goes from FAIL (2 heads, forking at
0046) to PASS (1 head).

Merges `origin/dev`, which also brings 0047 and its SQLite twin; both migration
functions are registered and both ledger entries kept.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dolho added a commit that referenced this pull request Aug 27, 2026
…guard was unreachable (#2335, #2336)

## 1. `run-full.sh` — the api tier ran journeys a second time

`run_tier api` collects `.` with a hand-written `--ignore=` per tier, and
`journeys` was added above without being added below. So a full local run
created and tore down every journey agent twice, paid the container time twice,
and reported one journey failure under two tier names.

Adding `--ignore=journeys` fixes the instance and leaves the class — the ignore
list is a hand-maintained mirror of the tier list, which is the
new-producer-not-in-the-consumer-allowlist shape the reviewer named. So the list
is now DERIVED from `TIER_DIRS` + `NON_TIER_DIRS`, and checked against the tree:
a directory under `tests/` in neither set fails the script by name instead of
being swept silently into `api`. Verified both ways — the derived list contains
`--ignore=journeys`, and an unwired directory exits 1 with the offending name.

## 2. `journey-smoke.yml` — the exit-5 guard could never run

GitHub's default `run:` shell is `bash --noprofile --norc -e -o pipefail {0}`,
and `set -uo pipefail` adds `-u` without clearing the `-e` already in force. A
non-zero pytest therefore aborted the step on the pytest line: `rc=$?` never
executed, the `if` never executed, and the "No journeys collected" annotation
could never appear. The job still went red on exit 5 — through `-e`, not through
the code that documents the guarantee — so the #2029 protection this gate is
required to provide rested on an implicit shell flag while the lines asserting
it were dead. A later editor adding `continue-on-error` would have got no signal.

`|| rc=$?` over `set +e`: a command in a condition is not subject to `-e`, so
the exit code is captured by construction rather than by remembering to disable
a flag. Verified under the real flags: exit 5 now prints the annotation and
fails, exit 1 fails with no false annotation, exit 0 passes. The old shape,
same simulation, exits 5 and prints nothing.

## 3. The drift step no longer depends on constants it never reads

`{"memory": "2g", "cpu": "1"}` forced a recreate only because the fleet defaults
happened to be `4g`/`2` — values this test never read and an operator can move
at runtime through `PUT /api/settings/agent-defaults/resources`. Set the default
to 2g/1 and the PUT is a no-op, no drift, plain-start path, and the journey
silently loses its teeth exactly as it already did twice.

It now GETs the current resources, picks a provably different pair, and asserts
the change took — so "could not force a recreate" fails under its own name
rather than surfacing later as "the restart 500'd", or as a green run that
never exercised the recreate path at all.

## 4. A partial create no longer leaks an agent

The create's `raise` sat above the `try:` whose `finally` deletes, so a create
that provisioned the ownership row and then failed left an agent teardown never
reached — breaking this tier's own re-runnable-after-a-crash rule on the path
where cleanup matters most. Moved inside; `delete_agent_idempotent` was already
safe on an agent that never existed.

## 5. `paths-ignore` deliberately NOT added, and the reason is now in the file

The tax is real, but the obvious fix is the wrong one: a filtered-out PR runs no
workflow, so the check is never REPORTED — and for a check this PR intends to
make required that is not "skipped", it is a PR that can never merge. That
precise failure was diagnosed on #2384 today. The safe shape is
`frontend-e2e.yml`'s (unconditional trigger, cheap `changes` job, `if:`-gated
heavy job, failing OPEN), which wants its own deliberate change rather than a
rushed third copy here — that file says of its sibling that the two "differ ON
PURPOSE". Recorded as a comment so the next person does not add the trap.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants