Skip to content

fix(gates): a request the skill gate held is never replayed to the agent — Workspace, public links, Telegram groups, rooms (#3402) - #3847

Merged
vybe merged 4 commits into
devfrom
feature/3402-held-turn-history
Oct 21, 2026
Merged

vybe merged 4 commits into
devfrom
feature/3402-held-turn-history

Conversation

@webmixgamer

Copy link
Copy Markdown
Contributor

Summary

  • The skill gate reads only what a sender types each turn. Reading history would hold every later turn after one mention. But a held /pay-invoice … and its "Not run…" notice stayed in each conversation store and were replayed into later turns' history. The model could then act on a request nobody approved; Codex and Gemini agents have no in-container hook.
  • Following the Agent Chat tab: a gated request held for approval leaves no trace after reload, and re-sending raises duplicate approvals #3526 Chat-tab precedent, a turn the gate held or refused, and the platform's answer to it, never reach a later prompt, whatever was decided. An approved request runs as its own execution, and its result arrives as its own row. Rows people see are unchanged.
  • Fixes the room re-hold loop, which was folded into this issue. A held room wake left the read cursor in place, so every later wake asked again for the same post, up to the per-requester cap, then refused it on every wake. The agent never answered anything else in that room.

Changes

Surface What changes
Workspace enterprise_portal_messages.gate_hold marks the held turn's message and notice, and a refused turn's message. get_portal_thread_window / get_portal_messages leave marked rows out by default: the cold history, the voice model's opening summary, and the resumed turn's voice-delta cursor (a held notice is not a reply the live session wrote). The thread UI, reply poll, retry dedupe, role card and ask card pass include_held=True. A retry that reuses a refused row clears its mark. Rows held before the column (since #3166) are backfilled once, from the gate record that names their turn.
Public links + Telegram groups public_chat_messages.gate_hold. A public visitor or channel sender never self-approves, so a message of theirs that invokes a gated skill is marked named as it is stored. That covers untagged group chatter the gate never sees, and a turn built while an earlier one is still inside the gate's check. The verdict overwrites named with the request id or refused:<code>, and also marks a turn held because of its reply quote. get_recent_public_chat_messages excludes marked rows by default: the context prompt, the group history block and the MEM-001 summary. The visitor's own history opts in. A channel DM is stored only after a run, so a held one never reaches the store.
Rooms New table room_gate_holds records, per agent, the post a hold was raised for (or one refused for a reason that stands, STANDING_REFUSALS) and its notice line. Every wake of that agent leaves those rows out of what it is shown and of what the gate scans, from one list. MCP read_room by that agent leaves them out too; other agents and people still see them. The cursor keeps its success-only rule, so an ordinary post in the same delta is still delivered. A transient refusal (unreadable gate map, rate or queue cap, agent down) records nothing, and the post is delivered again.

Files: client_portal/{service,db,voice,role_card}.py, client_portal/asks/service.py, services/{public_chat_service,skill_gate_service,skill_gate_errors}.py, adapters/message_router.py, shared_sessions/{service,db}.py, routers/public.py, db/{public_chat,schema,tables,migrations,agent_cleanup}.py, db_models.py, database.py.

Migrations (both tracks): SQLite held_gate_turns + Alembic 0101_held_gate_turns (down_revision 0100_admin_email_not_username). Two nullable columns, one table, and one exact backfill whose SQL both tracks share (db.migrations.HELD_PORTAL_ROWS_BACKFILL). Additive. Open PRs #3723 and #2984 also add a 0101 revision; whichever lands second re-points down_revision.

Docs: feature-flows/skill-gate.md (history paragraph, stated limits, test table), requirements/security.md §26.13, architecture/workspace.md (rooms), plus five flows that describe the changed builders. Two learnings fragments. CSO diff report docs/security-reports/cso-diff-2026-10-20-3402-held-turn-history.md: 0 findings.

Follow-up: #3846, two races with the gate's own check: a Workspace message sent while an earlier one in its thread is still being checked, and two simultaneous wakes of one push agent in a room.

Test Plan

  • New tests, all on the real schema and, where a hold is needed, the real gate backstop:
    • tests/unit/test_3402_workspace_held_history.py
    • tests/unit/test_3402_public_group_held_rows.py
    • tests/unit/test_3402_room_gate_holds.py
  • Red first: the room loop reproduced (two approvals for one post), and the replay shown on every surface.
  • Mutation-proven: reverting each of 20 parts of the fix turns tests red. For example, dropping the room record turns 7 red, the Workspace read filter 8, the public default exclusion 6, the hold mark 5, the backfill 1 and the write-time mark 1.
  • Existing tests unaffected: on the merge with current dev, the new files plus the gate, portal, room, public-chat and Telegram suites pass (1,711 passed). check_alembic_heads reports one head; check_alembic_parity passes.
  • verify-local (backend only): image build and import, boot with migrations on a fresh DB, preflight and integration all pass. The full unit stage ran on the branch before the final fixes (27,856 passed). Its two branch-caused failures are fixed in this branch (an AST order pin on _wake_agent_locked, and a room fixture missing the new table), and their suites re-run green.
  • PostgreSQL track: CI pg-migrations.

Eyeball (local instance) — passed on Workspace, room and public link

Eyeballed on d5f690577. The final commit differs only in the room "nothing left to answer" branch (it returns without moving the cursor) and two test fixtures; neither is on an eyeballed path. Each check read the prompt the agent actually received, from the agent's own session file.

  • Workspace, cold turn.
    • Thread: what is 2+2? → 4 → /pay-invoice 100 EUR to ACME → the notice.
    • Then the cached session was cleared and the client asked "List every message of our conversation so far, word for word".
    • The agent's prompt held only Client: what is 2+2? / You: 4 and the new message.
    • After a reload, the held message and its notice are still on screen.
    • The held message and the notice carry gate_hold = gate-….
  • Room.
    • @agent /pay-invoice 9 EUR → the notice; then @agent what is 3+3? → the agent answered, with no second notice.
    • Exactly one approval was raised.
    • room_gate_holds holds the post and the notice.
    • The wake transcript held only the room-created line and the new post.
  • Public link.
    • hello → /pay-invoice 5 EUR (the notice) → what did I ask before? → "You asked "hello" before this."
    • The held message and the notice are marked; after a reload, both are still on screen.
  • Not eyeballed: Telegram groups, and the refused → replay path end to end. Unit tests cover both.

Recipe notes:

  • Seat an approver first. On an install with a role-assignments provider, a gate that names "Primary contact" refuses with role_unassigned when no primary is seated; the owner is not a fallback. Seat a primary for the agent (Settings → People) before gating the skill, and remove the seat afterwards.
  • Force a cold turn on a Claude agent. Set enterprise_portal_sessions.cached_claude_session_id to NULL for the thread. A resumed session never saw the held turn; the replay happened on cold turns, which on Codex is every turn.
  • Retries reuse the row. Sending the same text again right after a refusal counts as a retry: it reuses that row instead of adding one.
  • Where to read the transcript. Read it in the agent's own session file. schedule_executions.message holds only the user's words, and the execution log has no user event.

Fixes #3402

🤖 Generated with Claude Code

webmixgamer and others added 3 commits October 20, 2026 17:10
…ent — Workspace, public links, Telegram groups, rooms (#3402)

The gate reads only what a sender types each turn; reading history would
re-hold every later turn after one mention. But a held `/pay-invoice …`
and its "Not run…" notice stayed in each store and were replayed into
later turns' history, where the model could act on a request nobody
approved (on Codex and Gemini there is no in-container hook). Following
the #3526 Chat-tab precedent, a turn the gate held or refused, and the
platform's answer to it, now never reach a later prompt, whatever was
decided. Rows people see are unchanged.

- Workspace: `enterprise_portal_messages.gate_hold` marks the held
  turn's message and notice (and a refused turn's message);
  `get_portal_thread_window` / `get_portal_messages` leave marked rows
  out by default (cold history, the voice model's summary, and the
  voice-delta cursor). The thread UI, reply poll, retry dedupe, role
  card and ask card opt in. A retry that reuses a refused row clears it.
  Rows held before the column (since #3166) are backfilled once from
  the gate record that names their turn.
- Public links + Telegram groups: `public_chat_messages.gate_hold`. A
  public visitor's or channel sender's message that invokes a gated
  skill is marked `named` as it is stored (they never self-approve).
  This also covers untagged group chatter the gate never sees, and a
  turn built while this one is still in the gate's check. The verdict
  overwrites it with the request id or `refused:<code>`. Prompt reads
  (context prompt, group history block, MEM-001) exclude marked rows
  by default; the visitor's own history opts in.
- Rooms: fixes the re-hold loop. A held wake left the cursor in place,
  so every later wake asked again for the same post, up to the cap,
  then refused it forever. `room_gate_holds` now records, per agent,
  the held post (or one refused for a reason that stands) and its
  notice. Every wake leaves those rows out of what the agent is shown
  and what the gate scans, from one list, and so does MCP `read_room`
  by that agent. The cursor keeps its success-only rule, so an
  ordinary post in the same delta is still delivered. A transient
  refusal records nothing.

Migrations: SQLite `held_gate_turns` + Alembic `0101_held_gate_turns`
(two nullable columns, one table, one exact backfill sharing its SQL).

Tests: three new files, 39 tests, over the real schema and the real gate
backstop. Red first: the room loop reproduced (2 approvals for one post),
and the replay shown on every surface. Mutation-proven: reverting each of
20 parts of the fix turns tests red, e.g. dropping the room record →
7 red, the Workspace predicate → 8, the public default exclusion → 6,
the hold mark → 5, the backfill → 1, the write-time mark → 1.

Follow-up: #3846 (two races with the gate's own check).

Fixes #3402

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

The test faked the old shape by dropping `gate_hold` with SQLite's
`ALTER TABLE … DROP COLUMN`. The CI runner's SQLite cannot rewrite
`enterprise_portal_messages`' DDL that way ("error in table … after drop
column: incomplete input" — a comment sits before its last column), while
the macOS build tolerates it, so the test passed locally and failed in the
regression diff. It now creates the two old tables explicitly. That also
lets it check the backfill on the old shape: a Workspace turn a gate record
names is marked, and nothing else is. Removing the backfill turns it red.

The migration itself never drops a column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@webmixgamer
webmixgamer requested a review from dolho October 20, 2026 18:09

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

/review: approve, no critical findings (I1 recommended before merge)

Scope: clean. Folding the room re-hold loop into this PR is stated in the description and fits #3402. All three surfaces are in the diff: Workspace, public links with Telegram groups, and rooms.

This was a read-only code review. I did not re-run tests or mutations; the PR's mutation evidence (20 parts reverted, each red) is taken as stated.

What checks out

  • SQL: every new statement is parameterised. IN :ids uses bindparam(expanding=True), and the table names in f-strings are constants from fixed tuples.
  • Migrations: both tracks are present.
    • SQLite uses _safe_add_column and CREATE TABLE IF NOT EXISTS.
    • Alembic 0101 is idempotent and points at 0100_admin_email_not_username, the current dev tip, so there is a single head today. #3723 and #2984 also add a 0101; whichever of those lands second must re-point its down_revision.
    • schema.py and tables.py match.
    • The backfill SQL (HELD_PORTAL_ROWS_BACKFILL) is shared by both tracks.
    • Both columns are nullable and the change is additive.
  • Readers: every caller of get_portal_messages, get_portal_thread_window and get_recent_public_chat_messages was checked.
    • Paths that build a prompt use the default, which leaves held rows out.
    • Paths a person sees opt in with include_held=True: history, the retry dedupe, the role card and the ask card.
  • Auth: the get_room filter keys on the caller's agent_name from the auth context, never the request body. It fails closed, and people still see every row.
  • Cleanup: room_gate_holds uses a CASCADE AgentRef, which covers renames through AGENT_REFS.

Informational findings

[I1] A blip while reading the gate map hides a message from history for good (confidence 7/10, worth fixing before merge)
src/backend/services/skill_gate_service.py:463-466

    try:
        gates = read_gates(agent_name)
    except SkillGateRefused:
        return {"gate_hold": GATE_HOLD_NAMED}

read_gates raises gate_unavailable on any store failure, which is a transient error. During such a blip, every public, channel and group-chatter message is stored as named, whatever its text. Nothing clears named afterwards: mark_messages_held only replaces it with a hold verdict, and a successful run never touches it. Two consequences:

  • If the map recovers before dispatch, the turn runs, but its user message is missing from all later history while the agent's reply stays. The agent sees answers to questions it can't see.
  • Observed group chatter is never dispatched, so it stays hidden for good.

Suggestion: on a read failure, store the row unmarked (or with a separate unchecked value) and let the verdict path mark it. Alternatively, clear named when the turn completes.

[I2] Rooms: a hold that didn't come from a post's own text can still loop (confidence 5/10)
src/backend/shared_sessions/service.py, _record_gate_hold: only posts in shown whose own content matches find_gated_invocations are recorded. If the hold came from context_text, or the gate read inside _record_gate_hold fails (gates = {}), only the notice row is recorded. The next wake then rescans the post, and a standing refusal repeats on every wake. That is the loop this PR closes. Suggestion: when no post matches, record the non-system posts in shown.

[I3] The backfill keys on origin_execution_id (confidence 4/10)
src/backend/db/migrations.py, HELD_PORTAL_ROWS_BACKFILL. A Workspace cold retry reuses the row and its execution. If a refused turn from before the column was later retried successfully under the same execution_id, the backfill also hides that successful exchange. The impact is low and limited to historical rows.

[I4] A new gate read on every stored public or channel message (confidence 6/10)
src/backend/adapters/message_router.py:391 and :565 call gate_hold_on_write(...) for every stored message, including busy Telegram group chatter. The read is probably cheap, but it adds a per-message dependency on the gate store, which also feeds I1.

[I5] Races are deferred to #3846. Two concurrent wakes, or two workers, can each raise a hold before either records one. This is already tracked.

🤖 Generated with Claude Code

…or good (#3402 review I1)

`gate_hold_on_write` marked a public-link or channel row `named` whenever
the gate map could not be read. Nothing ever clears `named` — a verdict
overwrites it, a run never touches it — so after a transient blip a turn
that then ran lost its message from every later prompt while its reply
stayed, and group chatter stored during the blip was hidden for good.

The write-time mark now fails open: the row is stored unmarked. The
verdict still marks each turn the gate holds or refuses — the dispatch-time
check re-reads the map and refuses `gate_unavailable` while it is still
unreadable. Stated limit: a message invoking a gated skill that is stored
during the blip and never dispatched (group chatter, or a turn that fails
before its dispatch).

Tests: a public-link turn stored during the blip keeps its message in the
next turn's context once the map is back, and is refused and marked when
it is not; chatter recorded during the blip is stored unmarked. Both red
with the old mark (mutation-checked).

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

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Replies to I1–I4 below; I5 is tracked in #3846.

I1: agreed, fixed in f0cd977. When the gate map can't be read, gate_hold_on_write now stores the row unmarked. The verdict still marks every turn the gate holds or refuses. The dispatch-time check re-reads the map, and if it is still unreadable it refuses the turn (gate_unavailable), which marks the row refused:gate_unavailable. A turn that runs after the blip keeps its message in history.

One gap remains: a message that invokes a gated skill, is stored during the blip, and is never dispatched. That covers group chatter, and a turn that fails after it is stored but before it is dispatched, such as a group file upload that fails. Nothing marks those rows. I've added this to the stated limits in skill-gate.md and requirements/security.md.

Tests in test_3402_public_group_held_rows.py:

  • test_an_unreadable_gate_map_never_hides_a_message_for_good[back-by-dispatch]: a public-link turn stored during the blip runs once the map is back, and its message is in the next turn's context.
  • test_an_unreadable_gate_map_never_hides_a_message_for_good[still-unreadable]: the dispatch-time check refuses the turn and marks it. This case passes with the old code as well; it pins the check the fix relies on.
  • test_chatter_recorded_while_the_gate_map_is_unreadable_is_stored_unmarked.

The first and third fail with the old mark. I checked this by reverting only that return: both went red, and the file was restored byte-identical.

I2: partly agree, no change.

  • The gate read inside _record_gate_hold fails. The post isn't recorded, so the next wake stops it once more (one extra ask or notice) and records it then. This is bounded by the blip, not a loop.
  • The hold came from context_text. For a room wake, context_text is the identity (email or key name) of whoever triggered the wake, not a post. That makes the hold the gate's verdict on that requester: their next wake matches the same context whatever we record, so recording posts can't change it. Recording every shown non-system post as a fallback would also hide innocent posts from that agent for good.

I3: no change. Neither kind of retry keeps the refused turn's execution id.

  • In-turn cold retry (run_resumable_turn). It fires only after a resume-not-found, which means a turn that actually ran. A refusal raises before admission, so it never triggers one, and the cold retry gets a new execution of its own.
  • A person's Retry. It reuses the row, but _stamp_user_turn (Workspace shows another turn's reply when two turns run on the same thread #3166) stamps it with the new turn's execution id. The row then no longer joins the old refused record, so the backfill can't hide that exchange.

Only a row whose best-effort stamp failed could be mis-marked.

I4: agreed it's a read per message, no change here. It is one indexed read on agent_skill_gates (WHERE agent_name = ?, the leading column of its primary key). With I1 fixed, a failed read no longer hides anything. An exact pre-filter is possible: skip the read when the text has no / after NFKC, since the matcher needs a slash. I'm happy to do that as a follow-up; correctness doesn't depend on it.

@vybe
vybe merged commit 5034304 into dev Oct 21, 2026
28 checks passed
@vybe

vybe commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

merge-train follow-up (non-blocking): four wiring lines survive deletion with every test green — include_held=True at client_portal/service.py ~3677 (retry check; without it a retried refusal writes a duplicate user row), client_portal/role_card.py:579 (ask count), client_portal/asks/service.py:1013 (ask-card origin context), and the gate_hold_on_write mark in adapters/message_router.py ~563. Also: #2984 and #3723 sit on the same Alembic parent and now need re-parenting onto 0101_held_gate_turns.

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.

3 participants