Repository navigation
feat(workspace): rate a message, rate a deliverable (ent#366) - #2384
Conversation
/review — self-review of this PR, plus a live pass against a running instanceBranch: 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)
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 oneAn agent-scoped key resolves to its owner, so Fixed structurally, not by adding two more calls: the redaction moved inside Verified live on all three paths after the fix: [C2] The dispatch imported a name that does not exist (Confidence 10/10 — reproduced live) from services.task_execution_service import task_execution_service # no such symbolThere is no module-level singleton — only 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 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 [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 categoriesSQL 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, Live pass against a running instanceThe write path and its refusals The grooming decision, enforced — see the three read paths above. The dispatch, after [C2]
In a browser Tests
Summary
🤖 Review generated with Claude Code |
/review — second pass (the fixes verified, and one thing the first pass missed)Re-ran against Verdict on the first pass's findings[C1] Redaction on one of three read paths — FIXED, and confirmed complete. [C2] Dispatch imported a symbol that does not exist — FIXED, and confirmed by running it. New finding, from this pass[C3] Hiding the words while leaving the rater's identity (Confidence 9/10 — reproduced live) The first fix stripped 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 Live after the fix: One of my own tests asserted object identity ( Residual, stated rather than fixedSystem-scoped keys are not redacted.
Everything else, re-checkedMigrations dual-track, one Alembic head, Tests
Summary
🤖 Review generated with Claude Code |
/review — third pass: the stated residual is now closedRe-ran against On the previous finding: C3 (the rated agent could name the complainant) was already fixed in [C4] The redaction covered the rated agent, not every machine reader — FIXED
The gate keyed on My own justification for leaving this in the last pass was:
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.
Live, all three principal kinds: Remaining residual, deliberately kept
State of the review, across three passes
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
🤖 Review generated with Claude Code |
obasilakis
left a comment
There was a problem hiding this comment.
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_evaluationstill carriesrequire_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_visiblechecks the target against the reader, and all three conditions are there — agent match, client-email match,role == "assistant".client_emailis 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"" == ""becauseportal_auth.py:146403s an account with no email. Unknown kind returnsFalse— 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_nameequality on top is additive — it closes somethingget_report_for_clientdoes not itself check. - The redaction is placed at the single projection point. Threading
current_userinto_to_responseas 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, androuters/evaluations.pyis 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. Andredacted = dict(row)copies before any write, so there's no cross-request mutation. upsert_workspace_ratinguses UPDATE-then-INSERT with anIntegrityErrorretry rather thanON CONFLICT. Worth calling out: a PGON CONFLICTagainst a partial index needs theWHEREpredicate 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_columnand 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 claims0046_report_audienceas a parent. I executed0047'supgrade()anddowngrade()against the realtrinity-postgrescontainer: 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---\nline closes the fence early, and everything after it renders outside the "treat as data" region. The test assertsprompt.count("---") >= 2, which a fence-breaking payload also satisfies. This is the same weakness asrouters/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_idsurvives redaction, and for a deliverable that weakens the identity scrub. It's anagent_reports.idthe rated agent authored and chose theaudience_emailfor, so the agent can re-identify the rater from its own state even thoughevaluatorwas stripped. No API route exposes it (_mapping_to_reportwithholdsaddressed_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_feedbackhands that same agent the verbatim comment — by design, per AC #2, but the framing in the description and inarchitecture.mdreads as absolute. - The background task receives
body.commentraw rather than the service's strippedtext_comment. Equal today at 2000 each, but they're independent constants. PortalRatingRequest.target_kind/ratingare barestr. The service validates and returns 422 (and it's tested), butLiteral[...]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 setstatus-in-devon 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_kinddistinctness hole (identical on both backends, unreachable through the writer sincetarget_kindis typed required); andportal_auth.py:138appliesreject_agent_principalon the platform branch but letsscope='system'through, sotrinity-systemcould 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.
0116b30 to
d0d833f
Compare
42704c8 to
5239ed8
Compare
Code review — re-review at
|
obasilakis
left a comment
There was a problem hiding this comment.
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_flightuntil 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:67mountsPortalRatingwith no:initial-rating, andmy_ratingis attached to messages only (service.py:_attach_own_ratings, keyed on"message").PortalConversation.vue:116passes it correctly. So a rated deliverable always reloads showing unrated, the user can rate it again, and the second comment lands in thealready_dispatchedpath above. This is the statenextRating'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_TEXTandRATINGS_UNAVAILABLE_TEXThave no production consumer.PortalAgentPage.vue:464hardcodes its ownratingsCaptioninstead. Five assertions inportalRatings.spec.jsguard a function nothing calls, and the "No ratings yet." empty state is unreachable because the tile isv-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.mdline 18 ("Interactive accent: action-primary-600 light / 500 dark; hover 700 / 400; focus ring 500@40% / 400@42%"): the Send button isbg-action-primary-600 hover:bg-action-primary-700with no dark override, and the textarea focus isring-action-primary-500/40 focus:border-action-primary-500with no dark half. Separately,PortalAgentPage.vue:68addsdark:text-gray-600, which R1 incheck-design-tokens.mjsstates admits "no judgement and no exceptions" — it passes CI only because that checker iteratesINK_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.jsoncorrectly untouched, and status/action tokens used properly throughout. - Accessibility gaps in the new component.
aria-pressedis there as described, and the thumbs are real buttons witharia-label. The textarea has a placeholder but no label,aria-labeloraria-labelledby, so its accessible name disappears as soon as the user types; and none of the three buttons carry afocus:/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 usingBaseTextarea/BaseButton— consistent with the rest ofcomponents/portal/, which imports noBase*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 subsequentcommentBox.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
disabledattribute alone — there is noif (sending.value) returnre-entrancy check inchoose(). 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_evaluationshas no retention window, and this PR is what makes that table hold client-authored free text. There is noagent_evaluations_retention_daysinRETENTION_OPS_KEYS, no sweep incleanup_service, no#1644guard coverage, and no entry onGET /api/settings/retention. The gap is pre-existing from ent#206 — the same grep againstorigin/devis empty — and theAGENT_REFSCASCADE 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 shipstotal_executions,success_rateand 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 ontotal >= 3would close it cheaply if you want it closed. I also confirmed thatEvaluationCreatehas notarget_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.
5239ed8 to
0665fc0
Compare
Code review — re-review at
|
obasilakis
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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 Trueand 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.
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]>
0665fc0 to
92ef324
Compare
…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
left a comment
There was a problem hiding this comment.
Approving — this clears my earlier CHANGES_REQUESTED.
All four items the last review blocked on are fixed and verified in head:
- Dispatch-claim lifecycle —
claim_capture_feedback_dispatchnow returns the in-flight claim,_settle_capture_feedback_claimcallscomplete()/fail()on both paths, and the router's inaccurate "the agent reads the row" comment is replaced with an accurate one. - Base retargeted to
dev. db/tables.pynow declares the partial UNIQUE as anIndex(..., unique=True, sqlite_where=..., postgresql_where=...)— the rule, not a perf index.- Evaluator carries
operator:vsworkspace:; the tally prefix-matchesworkspace:%so a future kind is excluded by default.
Two things to settle before you merge, neither of which needs another review round:
backend-unit-testandcodeqlhave 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 stillfeature/ent365-workspace-deliverablesand neither workflow triggers on a base change. A no-op push will arm them.- Alembic fork with #2386: this PR's
0047and #2386's0048both declaredown_revision = "0046_report_audience". Whichever lands second forks the graph, and sinceupgrade headresolves its target before applying anything, it applies zero revisions —check_alembic_headsis an unconditional required gate and will catch it, but the fix is analembic mergerevision. 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.
…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]>
…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]>
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_evaluationswith 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
One rating per person per thing
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_principalstripscommentfor an agent-scoped caller and setscomment_withheld, so a reader can tell "no comment" from "not yours to read". Two reasons:Operator surfaces see everything, unchanged.
The comment, and AC #6
The rating and its comment are durable before anything is dispatched.
capture-feedbackrouters/webhooks.pyframing), as its own execution — never a message in the client's threadBoth 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
unavailablerather 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:
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.One thing deliberately not done
The feedback turn is not stamped
source_channel=portal.test_2157_portal_narrationpins 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) + Alembic0047_workspace_ratings. Four nullable columns (target_kind,target_id,comment,updated_at) and the partial UNIQUE, withdb/schema.pyanddb/tables.pyupdated so fresh builds match.Related to Abilityai/trinity-enterprise#366
🤖 Generated with Claude Code