Skip to content

refactor(operator-queue): the listing engine moves to listing.py, and the poller core into PollerCoreMixin (#3785, PR 2 of 4) - #4037

Merged
vybe merged 23 commits into
devfrom
AndriiPasternak31/issue-3785-pr2
Nov 3, 2026
Merged

vybe merged 23 commits into
devfrom
AndriiPasternak31/issue-3785-pr2

Conversation

@AndriiPasternak31

@AndriiPasternak31 AndriiPasternak31 commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Part of #3785. This is PR 2 of 4: the operator-queue listing engine leaves __init__ for listing.py, and the poller core moves into poller.PollerCoreMixin. PR4, the PR that carries the closing keyword, lands last.

#3785 ships as four PRs instead of six separate units.

Stacking and how it lands

Commits

SHA Subject
0d07feddc refactor(operator-queue): the queue listing engine moves to listing.py (#3785)
d36909583 refactor(operator-queue): the poller core moves into PollerCoreMixin (#3785)

Labels used below

  • S1–S6: the six units refactor: split operator_queue_service.py — hotspot #2, highest complexity in the backend, no covering issue #3785 was built and reviewed in. PR1 = S1 + S2, PR2 = S3 + S4, PR3 = S5, PR4 = S6. "S3" below is 0d07feddc, "S4" is d36909583.
  • O1–O4: the ownership rules stated at the top of the guard, tests/unit/test_3785_operator_queue_package.py. O1: __init__ owns (a) the config block, (b) module state that is rebound or mutated, kept with its only mutators, (c) names read on both sides of the package boundary that tests patch, and (d) the rate_limiter binding. O2: the collaborators are bound once, in deps.py. O3: everything else has one owner module, and siblings read each other through that module. O4: every module logs as services.operator_queue_service.
  • G1–G13: the guard's section headers. G1 size; G2 the import surface; G3 no from-import between package modules; G4 collaborators only in deps; G5 one top-level binding per name; G6 import-time reads defined first; G7 a patch lands where its readers read; G8 one logger; G9 owner-exact qualified reads, nothing unbound; G10–G12 names that cannot collide; G13 import order.
  • E1: the test-edit class used here: a path-keyed census re-keyed to the module the code now lives in. Only the key changes; the rule, the reason text and the staleness checks do not.

What changes

S3: the listing engine moves to listing.py (0d07feddc)

  1. listing.py holds the listing engine. The new src/backend/services/operator_queue_service/listing.py (359 lines) takes the trinity-enterprise#815 block whole, moved byte-for-byte: QueueListError, AGENT_NAMES_MAX, narrow_to_agent_key, _effective_agents, the cursor codec (filter_fingerprint, encode_cursor, decode_cursor and their helpers), the walk-snapshot helpers (_walk_redis, _start_walk_snapshot, _load_walk_snapshot), the two warning templates and list_for_principal.
    • It reads the two package-owned person-prefix tuples as _oq.ABOUT_A_PERSON_ID_PREFIXES and _oq.OWNER_ONLY_ID_PREFIXES (O1 c; a test patches the first on the package, and test_b14 proves that patch still reaches the SQL exclusion). These are the only two changed tokens.
    • It reads the collaborators as deps.X, as before (O2).
    • Its logger is logging.getLogger("services.operator_queue_service"), the literal (O4).
  2. __init__ imports it, then re-exports what is read from outside.
    • from . import listing sits just above the composed class, after every name it reads (the order G6 and G13 pin). Every external import is still above from . import deps.
    • At the end of the file, a re-export block (O3) holds QueueListError and list_for_principal (the router reads both), plus narrow_to_agent_key, encode_cursor, decode_cursor and CURSOR_MAX_BYTES (tests call or compare them; none patches them).
    • Nothing inside the package reads a re-export: the guard's G9 holds that, and the mutation table shows it red.
  3. One test key moves (E1; table below): test_ent715's row-reader census keys list_for_principal on the file the code now lives in.

S4: the poller core moves into poller.PollerCoreMixin (d36909583)

  1. poller.py holds PollerCoreMixin. The new src/backend/services/operator_queue_service/poller.py (288 lines) holds the instance __init__ and all of its state, start / stop, the bug: operator-queue create path has no rate limit or size caps — flooding/operator-fatigue surface (blocking pull default-ON) #1632 leader lease (_leader_ttl, _try_acquire_leadership, _release_leadership), _poll_loop, _poll_cycle and _broadcast_sync. They move over unchanged except for 10 owner-exact qualifications: DEFAULT_POLL_INTERVAL ×1, _LEADER_KEY ×5, _RESERVED_ID_PREFIXES ×2 and _websocket_manager ×2 become _oq.X (O1). Comments and docstrings are not touched.
    • utc_now_iso and the stdlib names are imported in poller.py itself. G9 refuses _oq.utc_now_iso, because __init__ only imports it. No test patches it on the package, and G7 now refuses one: a package patch of a name a submodule binds for itself would miss that submodule's readers (added to the guard in PR1 after S4's review).
    • The one import-time read is the default poll_interval: int = _oq.DEFAULT_POLL_INTERVAL. __init__ binds that name at its config block, well above from . import poller (the order G6 pins).
    • The mixin has no docstring, only a comment, so its class body adds no statement and the AST check stays at 0 differ. The module docstring explains the shape.
  2. The class is composed in __init__: class OperatorQueueSyncService(poller.PollerCoreMixin), with the singleton operator_queue_service = OperatorQueueSyncService() still in __init__ (the db/schedules shape, Invariant Feature/gemini runtime support #2). from . import poller sits directly above the class, after every O1 definition.
    • _apply_sync_state, _apply_delivery_state, _notice_file_channel, _sync_agent, _write_responses_to_agent, _maybe_emit_flood_alert and _end_flood_episode stay on the composed class (PR3 and PR4 move them).
    • The cycle reaches _sync_agent through self., i.e. the MRO.
    • Nothing new is re-exported: no code outside the package reads PollerCoreMixin, and _LEADER_KEY (test_1632:701) stays in __init__.
  3. Three path re-keys (E1; table below).

No change to production behaviour. No docs change: path pointers are swept once, in PR4.

Journey Impact: none: the listing engine moves to a sibling module and the poller's methods move into a mixin of the same class; no route, payload, UI, API or MCP surface changes, and GET /api/operator-queue calls the same function object (list_for_principal.__module__ is now services.operator_queue_service.listing).

Where these numbers come from. Every figure below was measured on a local stack that nobody else can fetch. 4612e7878 is #4021's tip before it merged dev 0f689db80; S1 (19d16d8d7) and S2 (1e4910fee) sat on it as local commits, and S3 and S4 were each built as a diff against 1e4910fee, in parallel. So S4's figures were measured without S3 under it; here the two are sequential commits, and the combined figures at this PR's head are given separately. The pinning sets, the seed runs, the other-shape cases and the mutations ran against an earlier local S1+S2 commit (dbccf1497). That base differs from 1e4910fee only in comment lines in __init__ and deps.py, the guard's tests and its registry row description, and neither pinning set runs the guard; those runs were not repeated on the final base. The guard, AST equivalence and lint were re-run on each final unit tree. The commits here are those trees replayed onto PR1, which sits on db8a58e89: each differs from its local build only by #4021's merge of dev (104 files; none is in the package or its guard, and no test it adds or changes names the module). Re-run on these commits for this body: AST equivalence (173 compared, 0 differ on both, with 4 and 6 submodule header statements dropped), module sizes and radon CC. Everything else is re-derived on the real base when the PR is cut onto dev, and this body is updated. To redo at cut: every SHA and figure below re-derived on the real base. The two result lines at the end of Validation are filled when their runs finish.

Validation:

Python 3.12, -p no:randomly, TRINITY_DB_PATH unset. The two test selections are defined, with their commands, in the first collapsed block below.

S3:

  • Core pinning set (every test file naming the module, 60 files): 2,240 passed, 7 xfailed. The base gives the same.
  • Extended set (the core set plus every unit test importing a consumer, 302 files, -m "not slow"): 8,671 passed, 3 failed, 3 skipped, 7 xfailed. The base gives the same, with the same failing set: the 3 pre-existing test_ent751_gate_callers.py::TestPaidA2A failures. It includes test_ent815_queue_walk, test_ent815_broad_list_agent_scope, test_ent629_agent_reach, test_ent872_fleet_reach and test_3302_queue_list_order.
  • Guard: test_3785_operator_queue_package.py, 29 passed on the final tree. S3 does not edit it.
  • Order: the guard, the edited test_ent715, and the five listing suites above give 330 passed under each of pytest-randomly seeds 12345, 1 and 2 (measured with the 26-test guard of the earlier base).
  • Other shape, empty data (script in a collapsed block below). It runs in a fresh -E -P interpreter on a fresh unit DB with zero queue rows, against a Redis that is really unreachable (a local port nothing listens on; nothing is patched). It drives the real route through FastAPI's TestClient. Base and head print byte-identical output:
    • an agent key, offset mode: 200 with an empty page, count 0, total 0, has_more false, no cursor, both flag counts 0;
    • an agent key with cursor=start: 503 cursor walks need Redis, which is unreachable; retry, or page with offset;
    • an admin JWT with cursor=start: the same 503;
    • an agent key with a garbage cursor: 422 naming cursor;
    • list_for_principal called directly for the agent key: the same empty page;
    • no operator-queue warnings are logged.
  • Lint: tests/lint_sys_modules.py is OK (133 violations against a baseline of 134), identical to the base; ruff check --select F,E9 is clean on the package. Both re-run on the final tree.
  • CC (radon 6.0.1, cc -s -n C, summed per file): __init__.py 298 → 262; listing.py 36 (decode_cursor 23, list_for_principal 13); deps.py 0.
  • Size: __init__.py 2,830 → 2,521 lines; listing.py 359.
  • AST equivalence: 173 compared, 0 differ (4 submodule header statements dropped), re-run on the final tree and on 0d07feddc. The script and its command are in the second collapsed block below.

S4 (measured on S2 alone, without S3 under it):

  • Core pinning set (60 files): 2,240 passed, 7 xfailed. The base gives the same.
  • Extended set (302 files, -m "not slow"): 8,671 passed, 3 failed, 3 skipped, 7 xfailed. The base gives the same, with the same failing set: the 3 pre-existing test_ent751_gate_callers.py::TestPaidA2A failures.
  • Guard: 29 passed on the final tree. S4 does not edit it; every property is derived from the tree.
  • Order: the guard plus the three re-keyed files give 189 passed under each of pytest-randomly seeds 12345, 1 and 2 (measured with the 26-test guard of the earlier base).
  • Other shape, fresh install with no running agents (script in a collapsed block below): every case uses a fresh -E -P interpreter on a fresh SQLite DB, with the real db and the real ask sink. One ask is seeded past its deadline and one still open, both for an agent that is not running. Then one _poll_cycle runs. Base and head give identical outcomes in all four cases:
    • agent_container_states() returns {} (fresh install), and also returns {agent: "exited"}:
      • the due ask expires through the sink (disposed_by = timeout) and gets undelivered:agent_not_running;
      • the open ask is swept to unconfirmed:agent_not_running;
      • one operator_queue_sync trigger is sent, _sync_agent never runs, and nothing is raised or logged at warning level;
    • agent_container_states() returns None, and also raises (Docker unreadable): the due ask still expires and the one trigger is still sent, but nothing is swept. The open row keeps sync_state None and the expired row gets no delivery state. _sync_agent never runs.
    • The cycle that ran was OperatorQueueSyncService._poll_cycle @ __init__.py on base and PollerCoreMixin._poll_cycle @ poller.py on head.
  • The live loop runs through the mixin (script in a collapsed block below). _poll_loop swallows every exception, so the unit tier cannot see a poller that fails every cycle once started. This probe drives the real entry point instead: start() on a running event loop until at least six cycles have run, then stop(). A dict-backed Redis stands in for the breaker client.
    • What it asserts, exiting 1 otherwise: at least 6 cycles; zero Operator queue sync error lines; opqueue:leader held by this worker at every cycle and released by stop(); at least n−1 operator_queue_sync triggers over n cycles; the two running agents synced every cycle and the stopped one never; and, on a tree with poller.py, every executed _poll_loop, _poll_cycle, lease and _broadcast_sync frame is PollerCoreMixin.* @ poller.py.
    • Head and base both pass. On base every such frame is OperatorQueueSyncService.* @ __init__.py.
    • The counts are run-dependent. The loop runs with poll_interval=0 until the probe sees six cycles, so how many cycles run before stop() lands varies from run to run. One head run gave 28 cycles and 27 triggers; only the assertions above are stable.
    • Teeth (--break deletes the package's _websocket_manager): head and base both exit 1, reporting swallowed errors on every changed cycle. One run each gave 24 errors over 25 cycles (head) and 13 over 14 (base); those counts vary in the same way.
    • The same probe, run later on the local integration of this PR with PR3, gave 84 cycles and 0 Operator queue sync error lines (reported in PR4's body).
  • Lint: tests/lint_sys_modules.py is OK (133 violations against a baseline of 134), identical to the base; ruff check --select F,E9 is clean on the package. Both re-run on the final tree.
  • CC (radon 6.0.1, cc -s -n C, summed per file): __init__.py 298 → 287; poller.py 24 (_poll_cycle 24; the PollerCoreMixin class block ranks below C). The composed class's own block rises from 16 to 29, because radon scores a class as its mean method CC plus 1 and the small methods left.
  • Size: __init__.py 2,830 → 2,581 lines; poller.py 288.
  • AST equivalence: 173 compared, 0 differ (4 submodule header statements dropped), re-run on the final tree.

This PR's head, d36909583 (S3 and S4 together; re-run for this body):

  • AST equivalence: 173 compared, 0 differ (6 submodule header statements dropped).
  • Size: __init__.py 2,830 → 2,271 lines; listing.py 359; poller.py 288; deps.py 41.
  • CC (radon, cc -s -n C, summed per file): __init__.py 298 → 251; listing.py 36; poller.py 24.

Runs still in progress (filled in when they finish):

Mutation:

S3

Each mutation ran on a scratch copy of the tree and went red. Every file was restored from an in-memory snapshot. After restore, the guard (26 tests then) plus test_ent715, test_ent872 and test_ent815_queue_walk gave 256 passed, and AST equivalence gave 0 differ. The harness is local and not attached; each row names its edit.

Mutation Red
listing.py raises _oq.QueueListError (the re-export) instead of its own G9 test_qualified_reads_are_owner_exact; AST equivalence: 1 differ
a test patches oqs.narrow_to_agent_key (test_ent872) G7 test_a_patch_of_a_re_exported_name_reaches_its_readers
the move reverted (__init__ back to the base, listing.py deleted) test_ent715: test_every_row_read_is_classified, test_no_stale_row_reader_entries
the block copied back into __init__, with listing.py kept G5 test_every_top_level_binding_lives_in_one_module; G9
test_ent715's key left on __init__ (E1 not done) test_ent715: the same two census tests
QueueListError dropped from the re-export block G2 test_the_import_surface_still_resolves
listing.py from-imports ABOUT_A_PERSON_ID_PREFIXES (a frozen copy) G3; test_ent815_broad_list::test_b14_a_belt_drop_nulls_total_and_warns (the package patch no longer reaches the SQL exclusion)
test_ent815's fixture reverted to list_for_principal.__globals__ the __globals__ clause; 16 test_ent815_queue_walk tests (the patch lands in listing's namespace, which no reader reads, so the walk meets the real, unreachable Redis)

S4

Each mutation ran on a scratch copy of the tree and went red, 11 of 11. Every file was restored from an in-memory snapshot, and after restore the guard (26 tests then) gave 26 passed and AST equivalence 0 differ. The AST and live-loop checks cannot pass by crashing: a crash or a missing script counts as a miss, not a red. The harness is local and not attached; each row names its edit.

Mutation Red
leave _poll_cycle on the composed class too G12 test_no_method_is_defined_on_two_classes_of_the_service; AST-equiv 1 differ
move DEFAULT_POLL_INTERVAL below the submodule imports G6 test_every_import_time_read_is_already_defined; the import fails (AttributeError: partially initialized module … has no attribute 'DEFAULT_POLL_INTERVAL'), which also reds 8 other guard tests
the move reverted (base __init__, no poller.py) test_1920 ×2 (stale allowlist entry, unlisted lock), test_ent467 ×1, test_ent715 ×2 (unclassified reader, stale entry)
the move reverted, poller.py left behind unimported test_1920, test_ent467 and test_ent715 ×1 each; AST-equiv 10 differ
test_1920 lease key left on __init__.py test_1920 ×2
test_ent467 operator_queue_sync key left on __init__.py test_ent467 ×1
test_ent715 _poll_cycle key left on the composed class test_ent715 ×2
poller reads _oq.utc_now_iso (an __init__ import; runs fine) G9 test_qualified_reads_are_owner_exact
poller binds a module-level copy of _oq._websocket_manager test_no_import_time_copy_of_a_package_binding; AST-equiv 2 differ
a literal changed inside the moved _leader_ttl AST-equiv 1 differ
the cycle reads _oq._websocket_mgr, an unbound name (fails every cycle, swallowed) G9; the live-loop probe exits 1 (in that run, 56 swallowed Operator queue sync error lines and 0 triggers; the count is run-dependent)

Test edits

Every one is E1. No assertion, expected value, fixture data or control flow changes. The guard (test_3785_operator_queue_package.py, _oqs_package_scan.py) is not edited.

Unit File Key Before → after
S3 tests/unit/test_ent715_queue_person_fields.py (:940) _ROW_READERS (_OQS, "list_for_principal") → ("services/operator_queue_service/listing.py", "list_for_principal"); the class and reason text are unchanged
S4 tests/unit/test_1920_no_hand_rolled_single_flight.py _ALLOWED (the opqueue:leader lease) services/operator_queue_service/__init__.py → services/operator_queue_service/poller.py
S4 tests/unit/test_ent467_ws_agent_scope.py FLEET_LEVEL_ALLOWLIST (operator_queue_sync) …/__init__.py → …/poller.py
S4 tests/unit/test_ent715_queue_person_fields.py _ROW_READERS (_OQS, "OperatorQueueSyncService._poll_cycle") → ("services/operator_queue_service/poller.py", "PollerCoreMixin._poll_cycle")

Review

S3. Codex (gpt-6.1-sol, high effort, read-only) returned APPROVE with no findings: every moved statement AST-identical after the two sanctioned _oq. reads, every re-export with an outside reader, and the test_ent715 edit a pure re-key. A fresh reviewer (Opus 5.5, high effort) raised two findings that fall outside S3's code:

  • a guard property that the package re-exports only what outside code reads. It was added to the guard in PR1, where every guard property lives (test_every_re_export_has_an_outside_reader), with a mutation red there; it passes on S3's six re-exports.
  • a body a reviewer can re-run: the earlier draft cited scripts that do not ship with the PR, and SHAs from a local stack. This body inlines every script it cites, with its command, and labels the local SHAs.

S4. Codex (gpt-6.1-sol, high effort, read-only) returned APPROVE with no findings: all nine moved methods AST-identical after the sanctioned _oq. qualifications, every self. call reaching its method through the composed class, and the three test edits pure re-keys. A fresh reviewer (Opus 5.5, high effort) raised two findings that fall outside S4's code:

  • a test patch of oqs.utc_now_iso (or any name a submodule binds for itself) would miss poller.py's readers, and the guard stayed green. G7, in the guard in PR1, now refuses it, with a mutation red there and no false red on S4's tree (29 passed).
  • the earlier draft of the body cited scripts that do not ship with the PR, and SHAs from a local stack. This body inlines every script it cites, with its command, and labels the local SHAs.

Unverified:

  • Locally, per unit: only the two pinning sets ran on each unit, plus three seeds on the touched files; the full unit tier ran once, on the final tree (PR4's head), and the --full gate once per head (both in Validation).
  • The nightly seeds: CI runs them.
  • The pinning sets, seeds, the three probes and the mutations on the final local base: run on the earlier base only (see "Where these numbers come from").
  • S4's pinning sets with S3 under it: not run; S4 was measured on S2 alone. This PR's head was checked by AST equivalence, size and CC only, until the full-tier run above reports.
  • verify-local on the unit trees: not run. It was always meant to run once on S3, S4 and S5 together, because _poll_loop swallows its own exceptions. The live-loop probe is the per-unit stand-in; it uses stub collaborators and a dict Redis, not a real agent container or a real Redis. The --full gate above is the first end-to-end run on this PR's head.
  • Python 3.13: not run locally. CI runs 3.13.
  • The enterprise submodule: not mounted. A check at its pinned commit 982735f found no import of this module.
  • Re-merge with PR3: done once, locally, in 6f24efefb (see Stacking). It is redone for real by whichever of the two lands second.
  • Public names no longer on the package surface: AGENT_NAMES_MAX, WALK_SNAPSHOT_TTL_S, CURSOR_KEY_TEXT_MAX, filter_fingerprint and the listing privates now exist only as oqs.listing.X. Nothing in src/backend or tests/ reads them through the package, which is the O3 rule. Three prose citations in docs/memory/feature-flows/operating-room.md (operator_queue_service._effective_agents, ._load_walk_snapshot, ._walk_redis) name a symbol the package no longer has until PR4's pointer sweep re-points them.
  • The three scripts and DATABASE_URL: each child drops DATABASE_URL (which db/connection.py prefers) before it sets TRINITY_DB_PATH, and the commands below also run them with it unset. Unlike S2's script in PR1, they do not assert where db/engine.py points.
The two pinning sets: the selection rule, and the commands that run them

From the repo root, on Python 3.12, with TRINITY_DB_PATH and DATABASE_URL unset:

# Core pinning set: every test file that names the module, minus the shared helper
# `_gate_world.py` (not a test file) and this issue's own guard and its scan helper.
core() {
  grep -rl operator_queue_service tests --include='*.py' |
    grep -v -e '^tests/unit/_gate_world\.py$' \
            -e '^tests/unit/test_3785_operator_queue_package\.py$' \
            -e '^tests/unit/_oqs_package_scan\.py$'
}
# Extended set: the core set, plus every unit test with an import line naming a
# consumer of the package. A consumer inside a package counts as its whole package
# (`client_portal.service` and `client_portal.asks.service` -> `client_portal`;
# `services.git_service.gitignore_sweep` -> `services.git_service`).
X='ask_service|platform_alerts|operator_resume_service|platform_prompt_service|task_execution_service|idempotency_service'
consumers() {
  grep -lE "^[[:space:]]*(import|from)[[:space:]]+(main|routers\.operator_queue|services\.($X)|client_portal|services\.git_service)([.[:space:]]|$)|^[[:space:]]*from[[:space:]]+services[[:space:]]+import[[:space:]].*\b($X|git_service)\b|^[[:space:]]*from[[:space:]]+routers[[:space:]]+import[[:space:]].*\boperator_queue\b" tests/unit/test_*.py |
    grep -v '^tests/unit/test_3785_operator_queue_package\.py$'
}
T=${TMPDIR:-/tmp}
{ core; echo tests/unit/test_ent879_aauth_resource_route.py; } | sort -u > "$T/core.txt"   # 60 files on the local stack
{ core; consumers; } | sort -u > "$T/ext.txt"                                                # 302 files on the local stack
python -m pytest -p no:randomly -q $(cat "$T/core.txt")
python -m pytest -p no:randomly -q -m "not slow" $(cat "$T/ext.txt")

Both rules were checked against the frozen file lists the figures were measured on: on the local base and on every unit's tree, core gives 59 files and, with test_ent879_aauth_resource_route.py added, exactly the frozen 60; { core; consumers; } gives exactly the frozen 302.

Why 60 and 302, not the 59 and 315 counted earlier on f754dfb02:

AST equivalence: the script, and the command that runs it

Save the script below as ast_equiv.py. From the repo root of a checkout with history (CI's fetch-depth: 1 cannot run it, which is why it is here and not in CI), on Python 3.12 or later:

# the last commit that still has the single-file module (db8a58e89 on this stack;
# the figures in this body were measured against 4612e7878, which has the same blob)
BASE=$(git rev-parse "$(git log -1 --format=%H --diff-filter=D HEAD -- src/backend/services/operator_queue_service.py)^")
python ast_equiv.py "$BASE"

It prints N compared, 0 differ (M submodule header statements dropped) and exits non-zero on any difference. This is the one current version of the script, used for every PR of #3785.

"""#3785 owner-exact AST equivalence: base module (a git blob) vs the head package.

Usage (from the repo root):
  python ast_equiv.py <base-sha> [src/backend/services/operator_queue_service]

Every top-level statement and every function and method of the base file must
appear, AST-identical, in exactly one module of the head package. Methods of a
mixin composed into `OperatorQueueSyncService` count as that class's methods.
A qualified read in the head is un-qualified ONLY when its qualifier names the
name's true owner (`_oq.X` for an X `__init__` defines; `deps.X` for a `deps`
binding; `sib.X` for an X `sib` defines), so a read through any other existing
alias shows up as a difference. Imports are excluded; the logger binding is
normalised (`__name__` in the base module IS the literal). A SUBMODULE's own
header — its docstring and its `logger = logging.getLogger("<literal>")`, the
exact form G8 pins — is new by construction and is dropped (and counted) before
comparing; anything else a submodule adds at top level still differs. The
package docstring may only GROW: the head `__init__` docstring must begin with
the base module's docstring verbatim, and the base text is what is compared, so
editing a word of the original still differs while an appended section (the
ownership model the last slice records) does not.
"""
import ast, collections, subprocess, sys
from pathlib import Path

BASE_PATH = "src/backend/services/operator_queue_service.py"
COMPOSED = "OperatorQueueSyncService"
LOGGER = "services.operator_queue_service"


def top_defs(tree, with_imports=False):
    out = set()
    for n in tree.body:
        if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
            out.add(n.name)
        elif isinstance(n, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
            for t in (n.targets if isinstance(n, ast.Assign) else [n.target]):
                out.update(x.id for x in ast.walk(t) if isinstance(x, ast.Name))
        elif with_imports and isinstance(n, (ast.Import, ast.ImportFrom)):
            out.update((a.asname or a.name).split(".")[0] for a in n.names)
    return out


class Unqualify(ast.NodeTransformer):
    def __init__(self, owners):
        self.owners = owners  # {local alias: set of names that alias's module owns}

    def visit_Attribute(self, node):
        self.generic_visit(node)
        if isinstance(node.value, ast.Name) and node.attr in self.owners.get(node.value.id, ()):
            return ast.copy_location(ast.Name(id=node.attr, ctx=node.ctx), node)
        return node


def logger_norm(stmt):
    d = ast.dump(stmt)
    return d.replace("args=[Name(id='__name__', ctx=Load())]", f"args=[Constant(value='{LOGGER}')]")


def units(tree, mixins=()):
    """{key: [dump]} for every non-import top-level statement, function and method."""
    out = collections.defaultdict(list)
    for i, n in enumerate(tree.body):
        if isinstance(n, (ast.Import, ast.ImportFrom)):
            continue
        if isinstance(n, ast.ClassDef):
            owner = COMPOSED if (n.name in mixins or n.name == COMPOSED) else n.name
            header = ast.ClassDef(name=n.name, bases=n.bases, keywords=n.keywords, body=[], decorator_list=n.decorator_list, type_params=[])
            if owner == n.name:
                out[f"class {n.name}"].append(ast.dump(header))
            for m in n.body:
                key = f"{owner}.{m.name}" if isinstance(m, (ast.FunctionDef, ast.AsyncFunctionDef)) else f"{owner}.<stmt>"
                out[key].append(ast.dump(m))
        elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
            out[n.name].append(ast.dump(n))
        else:
            out["<stmt>"].append(logger_norm(n))
    return out


def main():
    base_sha = sys.argv[1]
    pkg = Path(sys.argv[2] if len(sys.argv) > 2 else "src/backend/services/operator_queue_service")
    base = ast.parse(subprocess.check_output(["git", "show", f"{base_sha}:{BASE_PATH}"], text=True))
    mods = {("" if p.stem == "__init__" else p.stem): ast.parse(p.read_text()) for p in sorted(pkg.glob("*.py"))}
    base_doc, head_doc = ast.get_docstring(base, clean=False), ast.get_docstring(mods[""], clean=False)
    if base_doc and head_doc and head_doc != base_doc and head_doc.startswith(base_doc):
        mods[""].body[0].value.value = base_doc  # appended only: compare the original text
        print(f"(package docstring: base text kept verbatim, {len(head_doc) - len(base_doc)} characters appended)")
    owned = {m: top_defs(t, with_imports=(m == "deps")) for m, t in mods.items()}
    # O1(d): `rate_limiter` is a package-owned IMPORT (ask_service reads `oqs.rate_limiter`),
    # so a submodule reads it as `_oq.rate_limiter` (G9 owns it the same way).
    owned[""] |= {"rate_limiter"}
    composed = next(n for n in mods[""].body if isinstance(n, ast.ClassDef) and n.name == COMPOSED)
    mixins = {b.attr if isinstance(b, ast.Attribute) else b.id for b in composed.bases}
    head = collections.defaultdict(list)
    header_logger = f"Assign(targets=[Name(id='logger', ctx=Store())], value=Call(func=Attribute(value=Name(id='logging', ctx=Load()), attr='getLogger', ctx=Load()), args=[Constant(value='{LOGGER}')]"
    dropped = 0
    for m, tree in mods.items():
        if m:  # a submodule's header: its docstring (first statement) and its O4 logger
            body = list(tree.body)
            if body and isinstance(body[0], ast.Expr) and isinstance(getattr(body[0], "value", None), ast.Constant) and isinstance(body[0].value.value, str):
                body.pop(0); dropped += 1
            loggers = [n for n in body if ast.dump(n).startswith(header_logger)]
            assert len(loggers) == 1, f"{m}: expected one header logger binding"
            body.remove(loggers[0]); dropped += 1
            tree.body = body
        aliases = {}
        for n in tree.body:
            if isinstance(n, ast.ImportFrom) and n.module == "services" and any(a.name == "operator_queue_service" for a in n.names):
                aliases.update({a.asname or a.name: owned[""] for a in n.names if a.name == "operator_queue_service"})
            if isinstance(n, ast.ImportFrom) and n.level == 1 and n.module is None:
                aliases.update({a.asname or a.name: owned.get(a.name, set()) for a in n.names})
        tree = Unqualify(aliases).visit(tree)
        if m == "":  # the composed class's own header differs by design (it gains the mixin bases)
            tree.body = [n for n in tree.body if not (isinstance(n, ast.ClassDef) and n.name == COMPOSED)] + [
                ast.ClassDef(name=COMPOSED, bases=[], keywords=[], body=composed.body, decorator_list=[], type_params=[])]
        for k, v in units(tree, mixins).items():
            head[k].extend(v)
    base_units = units(base)
    keys = sorted(set(base_units) | set(head))
    compared = differ = 0
    for k in keys:
        b, h = collections.Counter(base_units.get(k, [])), collections.Counter(head.get(k, []))
        compared += sum(b.values())
        if b != h:
            differ += sum((b - h).values()) or 1
            print(f"DIFFER {k}: {sum((b - h).values())} base-only, {sum((h - b).values())} head-only")
    print(f"{compared} compared, {differ} differ ({dropped} submodule header statements dropped)")
    sys.exit(1 if differ else 0)


if __name__ == "__main__":
    main()
Other shape, empty data: the script, and the command that runs it

Save the script below as issue-3785-s3-empty-data.py, then run it once against a checkout of the base and once against the head, with DATABASE_URL unset, and compare the two outputs byte for byte:

env -u DATABASE_URL python issue-3785-s3-empty-data.py <base checkout> > base.json
env -u DATABASE_URL python issue-3785-s3-empty-data.py <head checkout> > head.json
cmp base.json head.json

It needs Python 3.12 with the backend's dependencies.

"""#3785 S3 other shape — empty data. Run against a tree; compare base and head.

Usage:  python issue-3785-s3-empty-data.py <tree>          (prints one JSON line)

A fresh `-E -P` interpreter, a fresh unit DB with zero queue rows, and a Redis
that is really unreachable (`REDIS_URL` names a local port nothing listens on,
nothing is patched). The real `GET /api/operator-queue` route runs through FastAPI's
TestClient, with only `get_current_user` overridden:
  1. an AGENT key (narrowed through `principal_reach`), offset mode: an empty
     page, `total` 0;
  2. the same agent key with `cursor=start`: the walk needs Redis, so 503;
  3. an admin JWT with `cursor=start`: the same 503;
  4. `cursor=<garbage>`: 422 naming `cursor` (decoded before Redis is read);
  5. `list_for_principal` called directly for the agent key: the same empty page.
The status codes and bodies are the outcome; base and head must print the same.
"""
import json, subprocess, sys

CHILD = r'''
import atexit, json, logging, os, shutil, sys, tempfile
from pathlib import Path
backend = sys.argv[1]
td = tempfile.mkdtemp(prefix="trinity-3785-s3-")
atexit.register(shutil.rmtree, td, True)
for k, v in {"REDIS_PASSWORD": "test", "REDIS_BACKEND_PASSWORD": "test", "AGENT_AUTH_SECRET": "0" * 64,
             "SECRET_KEY": "x" * 32, "INTERNAL_API_SECRET": "y" * 32}.items():
    os.environ.setdefault(k, v)
os.environ["REDIS_URL"] = "redis://test:test@127.0.0.1:1/0"   # nothing listens there: really unreachable
os.environ.pop("DATABASE_URL", None)  # db/connection.py prefers it: never a real database
os.environ["TRINITY_DB_PATH"] = str(Path(td) / "fresh.db")
os.environ["LOG_ARCHIVE_PATH"] = str(Path(td) / "logs")
sys.path.insert(0, backend)

warnings = []
class Capture(logging.Handler):
    def emit(self, record):
        if record.levelno >= logging.WARNING and record.name == "services.operator_queue_service":
            warnings.append(f"{record.levelname}: {record.getMessage()}")
logging.getLogger("services.operator_queue_service").addHandler(Capture())

from fastapi import FastAPI
from fastapi.testclient import TestClient
from models import User
from routers import operator_queue as route
from redis_breaker_util import get_breaker_redis

app = FastAPI()
app.include_router(route.router)
principal = {}
found = set()
def walk(dependant):
    for sub in dependant.dependencies:
        if getattr(sub.call, "__name__", "") == "get_current_user":
            found.add(sub.call)
        walk(sub)
for r in route.router.routes:
    if getattr(r, "dependant", None) is not None:
        walk(r.dependant)
assert found
for call in found:
    app.dependency_overrides[call] = lambda: principal["user"]
client = TestClient(app, raise_server_exceptions=True)

agent_key = User(id=7, username="op-3785", email="op@example.com", role="admin",
                 agent_name="agent-3785", mcp_scope="agent")
admin = User(id=7, username="op-3785", email="op@example.com", role="admin")
from database import db
out = {"redis_reachable": get_breaker_redis() is not None,
       "rows_in_db": len(db.list_operator_queue_items(limit=10))}

def get(who, **params):
    principal["user"] = who
    resp = client.get("/api/operator-queue", params=params)
    return {"status": resp.status_code, "body": resp.json()}

out["agent_key_offset"] = get(agent_key)
out["agent_key_cursor_start"] = get(agent_key, cursor="start")
out["admin_cursor_start"] = get(admin, cursor="start")
out["agent_key_bad_cursor"] = get(agent_key, cursor="not-a-token!")
from services import operator_queue_service as oqs
out["direct_agent_key"] = oqs.list_for_principal(
    agent_key, accessible=route._accessible_set(agent_key), exclude_about_a_person=True,
    project=lambda rows: rows, filters={}, limit=50)
out["log_warnings"] = warnings
print("\n__EMPTY__" + json.dumps(out, sort_keys=True))
'''


def main():
    tree = sys.argv[1]
    proc = subprocess.run([sys.executable, "-E", "-P", "-c", CHILD, f"{tree}/src/backend"],
                          capture_output=True, text=True, timeout=600, cwd=tree)
    tail = proc.stdout.rsplit("\n__EMPTY__", 1)
    if proc.returncode != 0 or len(tail) != 2:
        sys.exit(f"exit {proc.returncode}\n{proc.stderr[-3000:]}")
    print(tail[1])


if __name__ == "__main__":
    main()
Other shape, fresh install with no running agents: the script, and the command that runs it

Save the script below as issue-3785-s4-fresh-install.py, then run it once against a checkout of the base and once against the head, with DATABASE_URL unset, and compare each case's out (its where differs by design):

env -u DATABASE_URL python issue-3785-s4-fresh-install.py <base checkout>
env -u DATABASE_URL python issue-3785-s4-fresh-install.py <head checkout>

It prints one JSON line per case and needs Python 3.12 with the backend's dependencies.

"""#3785 S4 other shape: a fresh install with no running agents. Compare base and head.

Usage:  python issue-3785-s4-fresh-install.py <tree>     (prints one JSON line per case)

Each case runs in its own fresh `-E -P` interpreter on its own fresh SQLite DB,
with the REAL db and the REAL ask sink (no mocks on either). Two rows are
seeded for an agent that is not running: one ask already past its deadline
(`due`) and one still open (`open`). `get_breaker_redis` is pinned to None (the
lease fails open, as it does with no Redis), and `agent_container_states` is
owned through `sys.modules` (the #1446 rule). Then one `_poll_cycle`:

  * zero_agents     `agent_container_states()` returns {} (fresh install)
  * agent_stopped   it returns {"agent-3785": "exited"}
  * docker_none     it returns None (Docker unreadable)
  * docker_raises   it raises (also "could not look")

Expected on both trees: every case expires `due` through the sink and sends
ONE thin trigger, and `_sync_agent` never runs. Only when Docker was readable is
`open` swept to `unconfirmed:agent_not_running`; with Docker unreadable nothing
is swept. The outcome dict is compared; `where` (the defining class of the
cycle that ran) is printed beside it and differs by design.
"""
import json, subprocess, sys

CHILD = r'''
import asyncio, atexit, json, logging, os, shutil, sys, tempfile
from pathlib import Path
from types import SimpleNamespace
backend, case = sys.argv[1], sys.argv[2]
td = tempfile.mkdtemp(prefix="trinity-3785-s4-")
atexit.register(shutil.rmtree, td, True)
for k, v in {"REDIS_URL": "redis://test:test@redis:6379", "REDIS_PASSWORD": "test",
             "REDIS_BACKEND_PASSWORD": "test", "AGENT_AUTH_SECRET": "0" * 64,
             "SECRET_KEY": "x" * 32, "INTERNAL_API_SECRET": "y" * 32}.items():
    os.environ.setdefault(k, v)
os.environ.pop("DATABASE_URL", None)  # db/connection.py prefers it: never a real database
os.environ["TRINITY_DB_PATH"] = str(Path(td) / "fresh.db")
os.environ["LOG_ARCHIVE_PATH"] = str(Path(td) / "logs")
sys.path.insert(0, backend)

from services import operator_queue_service as oqs
from database import db

AGENT = "agent-3785"
def seed(rid, expires_at):
    return db.create_operator_queue_item(AGENT, {
        "id": rid, "type": "approval", "status": "pending", "priority": "high",
        "title": "Approve", "question": "Go?", "options": ["approve", "reject"],
        "context": {}, "created_at": "2026-09-01T10:00:00Z", "expires_at": expires_at})
ids = {"due": seed("due-1", "2026-09-01T11:00:00Z"), "open": seed("open-1", "2999-01-01T00:00:00Z")}

oqs.deps.get_breaker_redis = lambda: None
def states():
    if case == "docker_raises":
        raise RuntimeError("docker socket unreadable")
    return {"zero_agents": {}, "agent_stopped": {AGENT: "exited"}, "docker_none": None}[case]
sys.modules["services.docker_service"] = SimpleNamespace(agent_container_states=states)

sent = []
class WS:
    async def broadcast(self, payload):
        sent.append(json.loads(payload))
oqs.set_websocket_manager(WS())

records = []
class Capture(logging.Handler):
    def emit(self, record):
        if record.levelno >= logging.WARNING:
            records.append(f"{record.levelname}: {record.getMessage()}")
logging.getLogger("services.operator_queue_service").addHandler(Capture())

svc = oqs.OperatorQueueSyncService()
synced = []
async def _sync_agent(name):
    synced.append(name)
svc._sync_agent = _sync_agent
try:
    asyncio.run(svc._poll_cycle())
    raised = None
except Exception as e:  # recorded: the case expects nothing to raise
    raised = repr(e)

F = ("status", "disposed_by", "sync_state", "sync_detail", "delivery_state", "delivery_detail")
rows = {k: {f: db.get_operator_queue_item(v).get(f) for f in F} for k, v in ids.items()}
fn = type(svc)._poll_cycle
out = {"raised": raised, "leader": svc._is_leader, "changed": svc._changed_this_cycle,
       "broadcasts": sent, "synced": synced, "rows": rows, "log_warnings": records}
where = f"{fn.__qualname__} @ {Path(fn.__code__.co_filename).name}"
print("\n__S4__" + json.dumps({"case": case, "where": where, "out": out}, sort_keys=True))
'''

CASES = ("zero_agents", "agent_stopped", "docker_none", "docker_raises")


def main():
    tree = sys.argv[1]
    for case in CASES:
        proc = subprocess.run([sys.executable, "-E", "-P", "-c", CHILD, f"{tree}/src/backend", case],
                              capture_output=True, text=True, timeout=600, cwd=tree)
        tail = proc.stdout.rsplit("\n__S4__", 1)
        if proc.returncode != 0 or len(tail) != 2:
            sys.exit(f"{case}: exit {proc.returncode}\n{proc.stderr[-3000:]}")
        print(tail[1])


if __name__ == "__main__":
    main()
Live loop: the script, and the command that runs it

Save the script below as issue-3785-s4-live-loop.py, then run it against a checkout, with DATABASE_URL unset. It exits 0 when every assertion holds; --break is the teeth control and must exit 1:

env -u DATABASE_URL python issue-3785-s4-live-loop.py <checkout>
env -u DATABASE_URL python issue-3785-s4-live-loop.py <checkout> --break

It prints one JSON line. Its cycle and trigger counts vary between runs; the exit code is the result.

"""#3785 S4: the background loop really runs its cycle through `PollerCoreMixin`.

Usage:  python issue-3785-s4-live-loop.py <tree> [--break]     (prints one JSON line)

`_poll_loop` swallows every exception from `_poll_cycle` and only logs
`Operator queue sync error`, so a unit test that calls `_poll_cycle` directly
cannot see a poller that fails every cycle once started. This drives the REAL
entry point instead: `operator_queue_service.start()` on a running event loop,
for at least six cycles, then `stop()`. A dict-backed Redis stands in for the
breaker client so the #1632 lease is really taken, refreshed and released, and
a profiler records which code object each `_poll_cycle` call ran.

Asserted (exit 1 otherwise): >= 6 cycles; zero `Operator queue sync error`
records; the lease `opqueue:leader` held by this worker at every cycle and gone
after `stop()`; one thin trigger per changed cycle; every running agent synced
every cycle and the stopped one never; and, on a tree that has `poller.py`,
every executed `_poll_cycle`/`_poll_loop`/lease frame came from `poller.py`
(`PollerCoreMixin.*`).

`--break` is the teeth control: the package's `_websocket_manager` binding is
deleted, so `_broadcast_sync` raises on every changed cycle — the "fails every
cycle, stays green" shape. The probe must then report the swallowed errors and
exit 1.
"""
import json, subprocess, sys

CHILD = r'''
import asyncio, atexit, json, logging, os, shutil, sys, tempfile
from pathlib import Path
from types import SimpleNamespace
backend, broken = sys.argv[1], sys.argv[2] == "1"
td = tempfile.mkdtemp(prefix="trinity-3785-s4-loop-")
atexit.register(shutil.rmtree, td, True)
for k, v in {"REDIS_URL": "redis://test:test@redis:6379", "REDIS_PASSWORD": "test",
             "REDIS_BACKEND_PASSWORD": "test", "AGENT_AUTH_SECRET": "0" * 64,
             "SECRET_KEY": "x" * 32, "INTERNAL_API_SECRET": "y" * 32}.items():
    os.environ.setdefault(k, v)
os.environ.pop("DATABASE_URL", None)  # db/connection.py prefers it: never a real database
os.environ["TRINITY_DB_PATH"] = str(Path(td) / "fresh.db")
os.environ["LOG_ARCHIVE_PATH"] = str(Path(td) / "logs")
sys.path.insert(0, backend)

from services import operator_queue_service as oqs
LEADER = "opqueue:leader"

class FakeRedis:
    def __init__(self):
        self.d = {}
    def set(self, k, v, nx=False, ex=None):
        if nx and k in self.d:
            return None
        self.d[k] = v
        return True
    def get(self, k):
        return self.d.get(k)
    def expire(self, k, ttl):
        return k in self.d
    def delete(self, k):
        self.d.pop(k, None)
fake = FakeRedis()
oqs.deps.get_breaker_redis = lambda: fake

svc = oqs.OperatorQueueSyncService(poll_interval=0)
cycles, lease_held = [], []
def expire():
    cycles.append(1)
    lease_held.append(fake.get(LEADER) == svc._worker_id)
    return SimpleNamespace(rows=[{"id": f"u{len(cycles)}", "agent_name": "a"}])
oqs.deps.ask_service = SimpleNamespace(expire=expire)

class DB:
    def mark_operator_queue_unconfirmed(self, *a, **k):
        return 0
    def mark_operator_queue_undelivered_for_stopped_agents(self, *a, **k):
        return []
oqs.deps.db = DB()
sys.modules["services.docker_service"] = SimpleNamespace(
    agent_container_states=lambda: {"a": "running", "b": "running", "c": "exited"})
gate = SimpleNamespace()
async def _sweep():
    return None
gate.sweep = _sweep
import services
services.skill_gate_service = gate
sys.modules["services.skill_gate_service"] = gate

synced = []
async def _sync_agent(name):
    synced.append(name)
svc._sync_agent = _sync_agent

sent = []
class WS:
    async def broadcast(self, payload):
        sent.append(json.loads(payload)["type"])
oqs.set_websocket_manager(WS())
if broken:
    del oqs._websocket_manager

errors = []
class Capture(logging.Handler):
    def emit(self, record):
        if record.levelno >= logging.ERROR:
            errors.append(record.getMessage())
logging.getLogger("services.operator_queue_service").addHandler(Capture())

ran = set()
WATCH = {"_poll_cycle", "_poll_loop", "_try_acquire_leadership", "_release_leadership", "_broadcast_sync"}
def prof(frame, event, arg):
    if event == "call" and frame.f_code.co_name in WATCH:
        ran.add(f"{frame.f_code.co_qualname} @ {Path(frame.f_code.co_filename).name}")

async def main():
    svc.start()
    deadline = asyncio.get_running_loop().time() + 30
    while len(cycles) < 6 and asyncio.get_running_loop().time() < deadline:
        await asyncio.sleep(0.01)
    task = svc._task
    svc.stop()
    try:
        await task
    except asyncio.CancelledError:
        pass

sys.setprofile(prof)
asyncio.run(main())
sys.setprofile(None)

n = len(cycles)
has_poller = (Path(backend) / "services/operator_queue_service/poller.py").exists()
problems = []
if n < 6: problems.append(f"only {n} cycles")
sync_errors = [e for e in errors if e.startswith("Operator queue sync error")]
if sync_errors: problems.append(f"{len(sync_errors)} swallowed 'Operator queue sync error' lines: {sync_errors[0]}")
if not all(lease_held): problems.append(f"lease not held at every cycle: {lease_held}")
if LEADER in fake.d: problems.append("lease not released by stop()")
if sent.count("operator_queue_sync") < n - 1: problems.append(f"{sent.count('operator_queue_sync')} triggers for {n} changed cycles")
if synced[: 2 * (n - 1)] != ["a", "b"] * (n - 1) or "c" in synced: problems.append(f"synced {synced[:8]}")
if has_poller and not all(r.endswith("@ poller.py") and r.startswith("PollerCoreMixin.") for r in ran):
    problems.append(f"a core frame ran outside poller.py: {sorted(ran)}")
out = {"cycles": n, "sync_errors": len(sync_errors), "lease_held_every_cycle": all(lease_held),
       "lease_released": LEADER not in fake.d, "triggers": sent.count("operator_queue_sync"),
       "ran": sorted(ran), "problems": problems}
print("\n__LOOP__" + json.dumps(out, sort_keys=True))
sys.exit(1 if problems else 0)
'''


def main():
    tree = sys.argv[1]
    broken = "1" if "--break" in sys.argv[2:] else "0"
    proc = subprocess.run([sys.executable, "-E", "-P", "-c", CHILD, f"{tree}/src/backend", broken],
                          capture_output=True, text=True, timeout=600, cwd=tree)
    tail = proc.stdout.rsplit("\n__LOOP__", 1)
    if len(tail) != 2:
        sys.exit(f"exit {proc.returncode}\n{proc.stderr[-3000:]}")
    print(tail[1].strip())
    sys.exit(proc.returncode)


if __name__ == "__main__":
    main()

… seam

create_bounded_alert(_outcome) keep their signatures and outcome contract
and become a thin delegate of platform_alerts.observe, which already
composes the per-(agent, type) budget inside its one locked create. The
registered type names its kind; the key is read back from the item's id
and context by derive_legacy_subject and must resolve to that same kind,
else ALERT_FAILED_CREATE. The two kinds whose ids carry no subject
(gitignore, problem report) are keyed by the request id minus the kind's
prefix. observe's "updated" and "snoozed" pass through; "failed" maps to
ALERT_FAILED_CREATE; every refused or failed arm logs [#1677 budget].
ALERT_FAILED_COUNT stays importable and is no longer returned.

The budget episode reports through observe as kind alert_budget keyed by
the budgeted type: one alert_budget:<type> row per agent, re-read by a
later refusal outside the cooldown, ended by its 14-day lifetime. The
bucketed id and its own operator_queue_new broadcast are gone; observe
sends the thin operator_queue_sync trigger.

Ratchet: create_bounded_alert_outcome and _maybe_emit_alert_budget_episode
leave EMITTERS_NOT_YET_ON_SEAM; alert_budget gets a NO_CLEAR_SITE reason.
Census: both leave _ALLOWED_CALLERS (no direct create left in either).

#3254 re-pins (asserted outcomes unchanged):
- test_1677_operator_alert_budget: write-observation point. The harness
  stands in for the seam's create with the same budget arithmetic and
  runs what observe spawns. Id shape in
  test_deterministic_bucketed_id_with_reserved_prefix,
  test_cooldown_knob_zero_never_raises (the subject replaces the bucket)
  and test_under_cap_creates_item_and_notification (the seam's id). The
  episode raise now stays in its spawned task, so
  test_episode_helper_raise_swallowed_refusal_stands reads the delegate's
  WARNING marker; test_ws_broadcast_failure_swallowed checks the thin
  operator_queue_sync payload.
- test_3130_flood_guard, test_1632_operator_queue_caps: write-observation
  point. The flood alert still rides the delegate, so its writes, the
  typed budget read and the I1 fault injection move to the seam's create.
- test_3243_atomic_asks::test_a_cap_hold_never_fires_the_flood_alert:
  write-observation point. Watched at observe, since the oqs.db assertion
  alone would now pass whether or not the alert fired.

Known until the problem report moves in its own commit: nine
test_3521_problem_report_comment cases are red here. The delegate files
an event-kind row under the seam's id, which the old _attach_comment
(keyed on the pre-seam request id) cannot find.

New: tests/unit/test_3254_budgeted_alerts.py (registry parity, reach-back
imports, the delegate's outcome table over all five budgeted types, the
episode's seam properties, R1 for alert_budget).

Part of #3254
…s with its episode

OperatorQueueSyncService._maybe_emit_flood_alert reports through
platform_alerts.observe as kind queue_flood keyed by the reason: one
pending row per (agent, reason), rewritten in place, budgeted by the
seam. #3130's outcome rule is kept on observe's strings: a failed write
releases the episode and is retried after the cooldown (I1); created,
updated, snoozed and refused consume it.

While an episode lasts it is re-read at most every 6 hours, so the kind's
14-day lifetime ends only a row nobody re-read, never a condition that
still holds. The refresh time per (agent, reason) is a dict the method
creates on the instance for itself; __init__ is unchanged. The flood's
own operator_queue_new broadcast (which carried the title) is gone;
observe sends the thin operator_queue_sync trigger.

The two _sync_agent statements where an episode ends
(_flood_episodes.discard for oversize_file and ingestion_cap) become
calls to the new _end_flood_episode, which ends the episode and, only
when one was running, ends its alert as the platform through
platform_alerts.clear. A cycle with no episode costs no read.

Ratchet: _maybe_emit_flood_alert leaves EMITTERS_NOT_YET_ON_SEAM;
queue_flood's clear site is _end_flood_episode.

No re-pin in this commit: the #3130 and #1632 harnesses were moved to
the seam's create in the previous commit and keep their results.

Tests: the flood through the real _sync_agent poll for 30 simulated days
with the real expiry sweep (one row, re-read every 6 hours, ended as the
platform when nothing is held), no read without an episode, two reasons
two subjects, I1 on the real seam, a person's ending standing through the
re-read and the clear, the thin trigger, R1 for queue_flood.

Part of #3254
…ugh the seam

_on_unguarded_effect reports a refused effect through
platform_alerts.observe as kind effect_unguarded keyed
"<effect_type>:<reason>": one row per agent, effect and reason,
rewritten by each further refusal, ended by its lifetime (nothing
observes an agent starting to send ids). The send is refused whatever
the alarm's outcome.

_alert_skill_not_found reports through observe as kind skill_not_found
keyed by the truncated command: one row per agent and command, re-read by
each scheduled run. The paired notification is sent only on "created": a
repeat of a pending command is an "updated" reading and already had one;
refused, failed and snoozed wrote no new row. The pre-create dedup read
stays and now matches only a pending pre-#3246 row (no subject), which
keeps standing for its command until the upgrade sweep stamps it; a seam
row is re-read through observe, where a repeat is never refused at the
cap.

task_execution_service.py: only _alert_skill_not_found changes. Its
module-level utc_now_iso import is now unused and is left in place.

Ratchet: _on_unguarded_effect and _alert_skill_not_found leave
EMITTERS_NOT_YET_ON_SEAM; skill_not_found gets a NO_CLEAR_SITE reason
(only the dispatch path could see a command resolve, and there the
detector cannot tell "resolved" from "not a slash command").

#3254 re-pins (asserted outcomes unchanged):
- test_1677_operator_alert_emitters::
  test_skill_not_found_emitter_is_routed_not_allowlisted: the module must
  call platform_alerts.observe naming "skill_not_found" (AST), the seam
  that composes the budget, instead of mentioning create_bounded_alert.
- test_2392_effect_guard_fail_closed: write-observation point and id
  shape. The alarm is recorded at platform_alerts.observe instead of a
  sys.modules stub of operator_queue_service, which lacks the names the
  seam reaches back for. The id prefix is asserted on the kind; the
  at-budget case returns the seam's refused_at_budget.
- test_ent879_aauth_resource_route (the refused-call case): the dead
  create_bounded_alert patch moves to platform_alerts.observe.

Tests: the effect refusal's seam properties and lifetime; the missing
skill's one row per command, no notification on a repeat, a pre-seam row
still standing, no notification at the cap; R1 for both kinds; the other
shape, the clock 30 days ahead: a full skill_not_found budget frees
itself through the real expiry sweep and a new command files.

Part of #3254
_emit_gitignore_untracked_alert reports through platform_alerts.observe
as kind gitignore_untracked, which stops being an event kind
(platform_alerts.py: event=True dropped). It is a must-act kind: no
lifetime, never ended by the platform.

It is keyed by the change itself: a 32-hex digest of the canonical,
direction-tagged set of paths the Push untracked and newly un-ignored
(sorted removed paths, the exact removed count, sorted un-ignored paths).
A repeat of the same set collapses onto one row; a different set, a
different total behind a capped list, or the same path in the other
direction is a different row. Keying per agent would let a later Push
overwrite an earlier Push's path list on a pending must-act alert, which
#2529 calls the surface that outlives the session. The legacy prefix
keeps its _no_subject parser, so pre-existing rows stay pending until a
person acts.

Ratchet: _emit_gitignore_untracked_alert leaves EMITTERS_NOT_YET_ON_SEAM.

#3254 re-pins (asserted outcomes unchanged):
- test_2529_gitignore_precedence: write-observation point and id shape.
  The alert is watched at platform_alerts.observe (the two
  create.await_count == 0 checks would otherwise have gone vacuous); the
  per-agent id prefix is asserted on the kind, with the 32-hex key.
- test_3246_platform_alerts_leaf::test_event_kind_has_no_subject:
  gitignore_untracked is a condition now, so it is asserted keyed and the
  problem report stays the event example.

Tests: a repeated set is one row that never expires; distinct sets and a
capped list with another total stay distinct; the direction tag holds;
a person's ending stands; the 30-day case now also shows the gitignore
row still pending.

Part of #3254
… and day

raise_problem_report reports through platform_alerts.observe as kind
workspace_problem_report, which stops being an event kind (event=True
dropped). It is keyed by the 32-hex digest _problem_report_id already
computes: one row per person per target per UTC day, the "never
duplicates" rule its docstring states. A person must act on it, so it
never expires and the platform never ends it. The workspace-problem- id
prefix is kept, so ent#866's owner-only rule and the machine-key "about a
person" exclusion still hold. It returns True when the row was created or
updated, False when snoozed, refused or failed.

#3521's words-only rule moves under the seam's lock. observe gains
keep_text (passed through database.create_platform_operator_queue_item to
create_platform_item and _touch): with keep_text and a pending row, the
reading only counts (last_seen_at, seen_count, expires_at) and the title,
question, priority and context stand. The bare click passes keep_text, a
reading with words does not. The click and the comment are two background
requests that meet on one row inside the per-agent lock, so either order
ends with the words. With no pending row the reading files as usual.

update_pending_problem_report (database.py, db/operator_queue.py) and the
nested _attach_comment are removed: one write path.

Ratchet: raise_problem_report leaves EMITTERS_NOT_YET_ON_SEAM, which
fixes the nine test_3521 cases the delegate commit left red.

#3254 re-pins (asserted outcomes unchanged):
- test_3521_problem_report_comment: the acknowledgement fixture goes
  through ask_service.answer (fixture shape; a raw status UPDATE carries no
  person ending for the snooze to read); the accessor test asserts the
  same type guard at the seam (a foreign row under the report's old id is
  never written); the lost-race test injects the bare click's whole
  reading, in its own thread, before the comment's locked create.
- test_ent499_problem_report: write-observation point. The fake moves from
  create_bounded_alert to platform_alerts.observe; the routing AST test
  asserts the call to observe.
- test_ent715_queue_person_fields: update_pending_problem_report leaves
  _NON_ROW_ACCESSORS (the accessor census forbids a stale entry).
- test_3246_platform_alerts_leaf::test_event_kind_has_no_subject: no
  built-in kind is an event any more, so the property is pinned on a kind
  registered for the test, and both former events are asserted keyed.
test_ent866_problem_report_owner_only is unchanged.

Tests: keep_text at the sink, both interleavings keeping the words, one
must-act row per person, target and day, the owner-only prefix, the
delegate and the emitter landing on one subject, a person's ending not
rewritten or reopened; the 30-day case now also shows the report still
pending; the five-type admission test asserts every kind keyed.

Part of #3254
…e's lock

observe checks the snooze before the create's lock. Two moments let a
person's ending slip past that check: an acknowledgement after observe
read the pending row but before the locked create (the locked find then
misses), and one between the locked find and _touch's compare-and-set
(the lock covers creates, not respond_to_item, so the CAS loses). Either
way the create fell through to an insert, and the alert a person had just
ended was back at once. Before this batch most of the moved writers had a
deterministic id that could not re-file after an ending, so the moves
would otherwise ship that regression.

create_platform_item gains snooze_since and a snoozed predicate. On the
insert path, after a missed find or a lost CAS and inside the same locked
transaction, it reads the newest person-ended row for the subject through
the transaction's own connection (the public lookup opens another one)
and returns {"outcome": "snoozed"} without inserting when the predicate
says so. observe passes the standard 7-day window, computed on its own
rather than from the pre-lock check's conditionally assigned cutoff, and
lambda ended: _snoozed_by(kind, ended, priority, context). The pre-lock
check stays as the fast path. A caller that passes neither keeps the old
behaviour.

The statement behind the public find_person_ended_by_subject becomes
_find_person_ended_by_subject(conn, ...), shared by both reads.

Tests: a person's acknowledgement through ask_service.answer, landed (a)
between observe's read and the locked create and (b) between the locked
find and the CAS, yields "snoozed" and no new row, for the problem
report, an inbox collision as registered on dev, and the flood alarm's
6-hourly re-read. All six cases were red before this commit (a fresh row
was created) and pass with it. On SQLite, BEGIN IMMEDIATE holds every
other writer, so moment (b) lands the ending first and hands both finds
the row as it stood just before it; two real workers are not exercised.

Review fixes carried here (the earlier commits are left as they are):
- OperatorQueueSyncService._maybe_emit_flood_alert: the cooldown is
  stamped before every reading, the 6-hourly re-read included. A failed
  re-read released the episode with the cooldown stamp still 6 hours
  old, so it was retried on the next 5-second cycle. New test: a failed
  re-read is retried no sooner than the cooldown (red before the fix).
- test_3521_problem_report_comment (the lost-race re-pin): asserts the
  bare click's own request returned True and left a pending, comment-free
  row before the comment's locked create ran, so the test cannot pass
  without the interleaving it claims.
- gitignore_sweep: states that past the probe's 2,000-line cap the key is
  the capped list plus the exact total (a full-set digest needs the
  in-container probe, outside this change).
- test_1677_operator_alert_emitters: the census's guidance for an
  agent-influenceable emitter now points at platform_alerts.observe, not
  the delegate the #3246 ratchet counts as off the seam.
- test_3254_budgeted_alerts: the frozen clock also covers
  db.operator_queue's ent#815 commit-lag check, which logged spurious
  errors against the real clock.

Part of #3254
… end still clears the alert

Fresh review of the #3254 budgeted slice (two findings):

- A failed 6-hourly re-read of a persisting flood released the episode.
  If the condition then cleared before the retry, `_end_flood_episode`
  found no episode and the pending alert waited out its 14-day lifetime,
  although the code had seen the condition clear (AC 2). A failed re-read
  now keeps the episode, whose alert an earlier reading filed, and the
  re-read is retried once the cooldown has passed. A failed first reading
  still releases the episode (#3130 I1). New test:
  test_a_failed_reread_keeps_the_episode_so_its_end_still_clears_the_alert
  (red with the old release branch put back).
- AC 8 for two kinds had no "a person's ending is never overwritten" test:
  `skill_not_found` (the next run is snoozed and sends no notification)
  and `alert_budget` (a later refusal re-reads the episode and the
  acknowledgement stands). Both added.
…running methods read

In the full serial unit tier, test_1595_sync_health_signals evicts
`database` and every `db.*` module from sys.modules and restores only
some of them. Afterwards `database.db` and `ask_service.db` run on an
older `db.operator_queue` module than the one this suite's clock fixture
imports and patches, so the seam's create, the expiry sweep and the
answer's compare-and-set read the real clock: rows filed at the frozen
T0 read as long expired (five cases red, `AskConflict: expired`, a
second flood row). The fixture now also freezes `utc_now_iso` and
`datetime` in the globals of the live operations class (R6: patch what
the running method reads). Red before: test_1595 followed by this file,
7 failed; green after: 66 passed; the file alone: 55 passed.
…ontent unchanged (#3785)

The 2,840-line module moves to services/operator_queue_service/__init__.py
byte for byte (100% similarity), the first step of the Invariant #1 split.
Every `from services.operator_queue_service import X` and
`from services import operator_queue_service` resolves as before.

Six path-keyed guards name the file by its path, so their key moves with it
(the PR #2487 precedent): _NOT_EMITTERS (test_3246), _ALLOWED_CALLERS
(test_1677), _ALLOWED (test_1920), _OQS (test_ent715), FLEET_LEVEL_ALLOWLIST
(test_ent467), and the source read in test_ent499. Only the key changes; the
rule, the reason text and every assertion are untouched.

Part of #3785
…split (#3785)

tests/unit/test_3785_operator_queue_package.py pins what S2–S6 must keep
while they move code out of __init__, each property derived from the tree
so no later slice edits it: modules under 800 lines (__init__ exempt, with
a staleness check); the import surface src/backend and tests/ read still
resolves; no from-import between package modules; one top-level binding per
name; import-time reads defined first and the _MARKER_UNCHANGED default the
owner's object; a patch of a re-exported name lands where its readers read;
one logger identity; owner-exact qualified reads; no submodule named like a
package attribute; one rate_limiter; no method on two classes of the
composed service; external imports before the first submodule import,
and a failed first import, injected at that line, leaves no stale submodule.
The AST scans live in _oqs_package_scan.py (pure stdlib, never imports src).

The other shape, a fresh install: each consumer imported first in its own
interpreter on an empty database raises a bounded alert (created; only main
binds a WebSocket manager, and then exactly one thin operator_queue_sync
trigger goes out). Outcomes equal on the base.

Part of #3785
…eps.py (#3785)

db, _queue_db, principal_reach, get_breaker_redis, ask_service, AgentClient
and the audit sink _audit_sync move to services/operator_queue_service/deps.py,
bound once and read as deps.X everywhere in the package. They are no longer
attributes of the package, so a stale monkeypatch.setattr(oqs, "db", ...)
raises AttributeError instead of patching a copy nothing reads (Invariant
#1(a), the PR #2487 rule). rate_limiter stays on the package: ask_service
reads oqs.rate_limiter.check.

Tests that patched a collaborator on the package now patch oqs.deps.X; no
assertion, expected value, fixture or control flow changes. The package guard
gains G4 (deps binds exactly the collaborators, no other module imports one
from its source under any alias or holds one by identity, the package has
none) and refuses any reach of a package function's __globals__.

Part of #3785
#3785)

QueueListError, narrow_to_agent_key, the cursor and walk-snapshot helpers and
list_for_principal (trinity-enterprise#815) move whole from __init__ to
services/operator_queue_service/listing.py. The two package-owned prefix
tuples are read as _oq.X, collaborators as deps.X. The package re-exports
exactly the six names read from outside (the router's list_for_principal and
QueueListError; narrow_to_agent_key, encode_cursor, decode_cursor and
CURSOR_MAX_BYTES, which tests call or compare).

test_ent715's row-reader census re-keys list_for_principal to listing.py; no
assertion changes.

Part of #3785
…3785)

The instance state, start/stop, the Redis leader lease, _poll_loop,
_poll_cycle and _broadcast_sync move into PollerCoreMixin in
services/operator_queue_service/poller.py. OperatorQueueSyncService is now
composed in __init__ from the mixin and keeps its singleton there (the
db/schedules shape). Package-owned names (DEFAULT_POLL_INTERVAL, _LEADER_KEY,
_RESERVED_ID_PREFIXES, _websocket_manager) are read as _oq.X; the default
poll_interval still binds 5 at import.

Three path-keyed censuses re-key their poller entries to poller.py
(test_1920's lease, test_ent467's operator_queue_sync trigger, test_ent715's
_poll_cycle); no assertion changes.

Part of #3785

@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 via /review (pre-landing structural review).

/review Report

Branch: AndriiPasternak31/issue-3785-pr2 → AndriiPasternak31/issue-3785-pr1 (stacked on #4036 at d2c724b15; merge-base = #4036's head)
Files Changed: 6 (+678/-590)
Scope: CLEAN
Plan Completion: #3785 AC for this slice: 1 done / 0 partial / 0 not done / 0 changed / 1 unverifiable

Earlier reviews: none on this PR, so there is nothing to carry forward.

Scope check

  • Intent (#3785, PR 2 of 4): move the ent#815 listing engine to listing.py and the poller core to poller.PollerCoreMixin, with no behaviour change.
  • Delivered:
    • 0d07feddc moves the listing block whole. It reads the two person-prefix tuples as _oq.X and re-exports the six names that outside code reads.
    • d36909583 moves __init__, start/stop, the leader lease, _poll_loop, _poll_cycle and _broadcast_sync into the mixin. The 10 package-owned reads become _oq.X.
    • Three E1 census re-keys.
  • No drift.

Plan completion (#3785 acceptance criteria, as they apply to PR 2)

  • DONE: "behind the existing public functions, so callers do not change".
    • routers/operator_queue.py:231,251 reads operator_queue_service.list_for_principal / .QueueListError, and both are re-exported (__init__.py:2264).
    • The tests read narrow_to_agent_key, encode_cursor, decode_cursor and CURSOR_MAX_BYTES, and all four are re-exported.
    • I grepped every top-level name defined in listing.py/poller.py against src/ and tests/ (attribute reads, from-imports and string-literal setattr targets). No outside reader of an un-re-exported name exists.
  • UNVERIFIABLE: the CC target. The PR body gives radon __init__ 298 → 251, which is still above 200; PR 3/4 continue the split.
  • Test edits are E1 path re-keys only (test_1920, test_ent467, test_ent715). I read all three: only the key changed.

Execution coverage (Step 2.5)

changed symbol / test file executed by live consumer verdict
listing.list_for_principal / narrow_to_agent_key / cursor codec / walk snapshot test_ent815_queue_walk, test_ent815_broad_list_agent_scope, test_ent872_fleet_reach routers/operator_queue.py:231 (GET /api/operator-queue) ✅ executed
listing reads _oq.ABOUT_A_PERSON_ID_PREFIXES (listing.py:294) test_ent815_broad_list_agent_scope::test_b14_a_belt_drop_nulls_total_and_warns (patches it on the package) same route ✅ executed. Mutation verified, see below.
PollerCoreMixin.__init__ / lease / _poll_cycle / _broadcast_sync test_1632_operator_queue_caps, test_3313_operator_queue_sync_error_logged, test_2742_sync_health_leader_lock, test_3274_gate_wiring main.py:604 operator_queue_service.start() (the singleton, __init__.py:2254) ✅ executed
3 E1 re-keys themselves path-keyed census guards 🛡 guard

Fix mutation: not applicable (refactor). Evidence that behaviour is preserved:

  • AST equivalence. I ran my own comparison of the base operator_queue_service.py (db8a58e89) against __init__ + deps + listing + poller at d36909583. Methods were keyed by class, with the mixin folded into OperatorQueueSyncService, and _oq./deps. normalised.
    • Result: 172 units, 0 missing, 0 extra.
    • The only differences are the expected ones: the new base (PollerCoreMixin) on the composed class, and the logger literal (same logger).
  • Lint. ruff --select F,E9 is clean on the package, so there is no unbound name in either new module.
  • Mutation. I ran it in a scratch worktree, not the PR checkout. I replaced listing.py's _oq.ABOUT_A_PERSON_ID_PREFIXES read with an import-time copy. Two tests went red: test_3785::test_no_import_time_copy_of_a_package_binding and test_ent815_broad_list_agent_scope::test_b14_a_belt_drop_nulls_total_and_warns. So the O1 live-read rule has both a guard and a behavioural test behind it.
  • Tests. I ran them locally with Python 3.12 and -p no:randomly: the guard, the 3 edited files, both ent815 suites, test_ent872, test_1632, test_3313, test_2742 and test_3274. Result: 435 passed.

Behaviour-preservation checks

  • Monkeypatch targets (Invariant #1(a))
    • Every patch of a moved poller method in tests/ is on an instance (setattr(svc, "_try_acquire_leadership", …), test_1632:717, test_2742:286,301, test_3313:42). An instance or composed-class patch still shadows the mixin method through the MRO.
    • No test patches a moved listing name on the package. G7 refuses one going forward, including oqs.utc_now_iso now that poller.py binds its own utc_now_iso.
  • Import cycles / partial init
    • listing.py/poller.py do from services import operator_queue_service as _oq while the package is mid-import. This resolves through the sys.modules fallback.
    • The one import-time read, poll_interval: int = _oq.DEFAULT_POLL_INTERVAL (poller.py:34), sits after the config block. from . import poller is at __init__.py:1262, and G6 pins that order.
    • The default was evaluated at class-definition time before the move as well, so its semantics are unchanged.
  • Duplicated state
    • _websocket_manager, _LEADER_KEY, _RESERVED_ID_PREFIXES and DEFAULT_POLL_INTERVAL are read as _oq.X (live), not copied.
    • Instance state is initialised only in the mixin __init__, and the composed class defines no __init__ of its own.
  • Package-attribute collisions: the base module never bound listing or poller (only comments mention "the poller"), so importing the submodules shadows nothing.
  • Function identity: list_for_principal.__module__ is now …operator_queue_service.listing. No code in src/ reads __module__/__qualname__ of these.

Critical Findings (block merge)

None.

Informational Findings (review required)

[I1] Process: no backend unit tier has run on this stacked PR in CI (Confidence: 8/10)
File: .github/workflows/backend-unit-test.yml (pull_request: branches: [dev, main])

  • Issue: the base is AndriiPasternak31/issue-3785-pr1, so only changes/gitleaks/prod-image-smoke/schema-parity/verify-* ran.
  • Suggestion: same as #4036. Merge after the retarget to dev runs backend-unit-test green. This matters most at the PR 2 / PR 3 rebase, because both edit the from . import … block, the class base list and the re-export block in __init__.

Clean Categories

  • SQL & data safety: no SQL or schema change. The deps.db.* calls are identical.
  • Race conditions: the leader lease (poller.py _try_acquire_leadership/_release_leadership) is moved token-for-token apart from _oq._LEADER_KEY. The test_1920 single-flight allowlist is re-keyed to poller.py with the same reason text.
  • Auth boundaries: narrow_to_agent_key and _effective_agents are moved unchanged. The route still raises and catches the same QueueListError class object, so the router's except operator_queue_service.QueueListError keeps matching.
  • WS broadcast (#918): _broadcast_sync still sends the thin operator_queue_sync trigger. The test_ent467 fleet-level allowlist is re-keyed to poller.py.
  • Credential exposure / enterprise disclosure: none, and no docs/ change.
  • Enum completeness: no new value.
  • Docs staleness: the path pointers to the old single file are deferred to PR 4's sweep (stated in the PR body). Accepted as planned.

Summary

  • Critical: 0 (none found)
  • Informational: 1 (review recommended)
  • Scope: clean

Verdict: APPROVE. This is a clean, mechanical move. I verified it with AST equivalence, lint, a red mutation on the one semantic seam (the live _oq. prefix read), and a green local run. Before merging, wait for the unit tier on dev after the retarget.

AndriiPasternak31 and others added 2 commits October 28, 2026 22:29
…after an acknowledgement (#3254)

A person's ending of a `queue_flood`, `alert_budget` or `gitignore_untracked`
row snoozed every later reading of the subject for 7 days, because none of
the three kinds had a material key, so `_snoozed_by` was vacuously true. A
runaway agent's second flood, a second budget-full episode and a second
untracking Push of the same paths were all silent (review C1; dolho on
operator_queue_service.py:2800 and gitignore_sweep.py:335).

Each reading now carries an episode marker that the kind lists in its
`material_keys`:
- queue_flood: `episode_started_at`, stamped when the in-memory episode
  starts. Re-reads of one episode share it; an episode that starts after the
  condition cleared does not.
- alert_budget: `filled_by`, a digest of the ids of the pending rows filling
  the budget. Re-reads of the same full budget share it; once a slot frees
  and a new row fills it, it differs.
- gitignore_untracked: `push_id`, one per call. The emitter runs once per
  Push, so every untracking Push after an acknowledgement files; repeats
  still collapse onto a pending row.

So the snooze silences re-reads of the acknowledged episode for the snooze
window and a new episode files at once, which makes the
`_maybe_emit_flood_alert` docstring's #3130 edge-trigger claim true again.
The budget episode's read of the filling rows is classified in the ent#780
row-reader census as internal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
…ooldown; the oversize end is pinned (#3254)

Review follow-ups on the flood alarm:
- dolho on operator_queue_service.py:2778 (webmixgamer agreed): the 6-hourly
  re-read of one reason's episode stamped the per-agent
  `_flood_alert_cooldown`, so the other reason's first alert could wait up to
  one cooldown. The cooldown spaces episodes and a re-read is not one, so it
  is now stamped only before an episode's first reading. A failed re-read's
  retry spacing already comes from its refresh time.
- webmixgamer I3: the 6-hour re-read spacing is one constant,
  `OPERATOR_QUEUE_FLOOD_REREAD_SECONDS`, read by the gate and by the failed
  re-read's retry arithmetic, so the two cannot drift.
- webmixgamer I1: a `_sync_loop` case serves an oversized file and then a
  sane one and asserts the row ends as the platform. It goes red when
  `_sync_agent`'s `_end_flood_episode(agent_name, "oversize_file")` is
  replaced by a bare episode discard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
@AndriiPasternak31

AndriiPasternak31 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

On I1 in the review (no backend-unit-test run on this stacked PR): agreed. backend-unit-test.yml runs only for PRs based on dev or main, and only on open, push or reopen (a retarget alone does not start it). So this PR merges only after #4036 lands, it is retargeted to dev and dev is merged in, and that run is green. That run is also the one that covers the PR 2 / PR 3 merge in __init__.

AndriiPasternak31 and others added 6 commits October 31, 2026 12:09
Resolves the conflict in tests/unit/test_1677_operator_alert_emitters.py:
both sides deleted different entries from the same allowlist block (dev,
#4018: retention_guard.announce_refusal and the two skills entries; this
branch: create_bounded_alert_outcome and _maybe_emit_alert_budget_episode).
Both sides' deletions are kept, so none of the five entries survive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
…flood episode marker (#3254)

The episode marker is worker-local. With Redis down the leader lease fails
open, so each worker stamps its own episode_started_at and another worker's
re-read can file past a person's ending, at most one extra row per extra
worker per re-read window. Docstring only; no behaviour change (review L1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
…1/issue-3785-pr1

Carries #4021's review fixes (87ae20f, e3c4b8b), its merge of dev
0b11bd5 and its docstring commit b2ebb02 into the package.

Git applied every hunk of the old single-file module to `__init__.py`
through the rename, with no textual conflict. One hunk needed a fix that
git cannot see: #4021's budget-episode digest (87ae20f) reads the
collaborator as `db.list_operator_queue_items`, and this PR binds `db`
only in `deps` (S2). As merged it is an unbound name inside a broad
`except`, so `filled_by` would be None on every reading. It now reads
`deps.db.list_operator_queue_items`, like the other 35 read sites. Ruff
F821, the guard's `test_no_unresolved_module_scope_names` and
`test_a_new_budget_episode_after_a_person_ending_files_again` each go red
without it.

AST equivalence of the package against the module at b2ebb02:
177 compared, 0 differ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
Review I1 (dolho): the file-level `# ruff: noqa: F401` switched off
unused-import detection for all of `__init__`, so a dead import left behind
by a later slice or feature would go unflagged. At this PR's head
`__init__` still reads every name in its import block, so the waiver hid
nothing: `ruff check --select F401` gives 0 findings with it removed. It is
dropped, and the block's comment now says that a name `__init__` stops
reading keeps its line with a per-line waiver naming why (G13, or read as
`oqs.X` from outside). PR2, PR3 and PR4 add those per-line waivers where
their moves leave a name unread.

`deps.py` keeps its file-level waiver: it is a binding module whose
imports are its bindings, so there is no import there F401 could rightly
flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
…785-pr2

Carries #4021's head (b2ebb02, via PR1's merge of it) and PR1's lint
change up to the listing+poller slice.

Two conflicts, both where this slice moved code that #4021's dev merge
changed:
- `__init__.py`: dev's trinity-enterprise#980 added `is_addressee_only`
  and `is_addressed_to` next to `is_owner_only`, and an `addressee_email`
  filter to `list_for_principal`. The two predicates stay in `__init__`
  beside `is_owner_only`, which this slice does not move. The listing
  block is dropped from `__init__` again, and its three #980 hunks (the
  parameter, its docstring paragraph, the WHERE condition) are applied to
  `listing.py` by a three-way merge of the old block, the new block and
  `listing.py`. The config read is owner-exact, as G9 wants:
  `_oq.ADDRESSEE_ONLY_ID_PREFIXES`, like `_oq.OWNER_ONLY_ID_PREFIXES`
  beside it.
- `test_ent715_queue_person_fields.py` `_ROW_READERS`: keeps #4021's new
  `_maybe_emit_alert_budget_episode` entry (still in `__init__`) and this
  slice's `listing.py` key for `list_for_principal`.

AST equivalence of the package against the module at b2ebb02:
177 compared, 0 differ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
…eading (#3785)

Review I1 on #4036: PR1 dropped `__init__`'s file-level F401 waiver. This
slice's moves leave four of its imports unread in `__init__`; each now
carries its own `noqa: F401` with the reason, so F401 keeps checking every
other line:
- `asyncio`, `base64`, `uuid`: kept for G13, because `listing` and `poller`
  import them at module level.
- `from . import listing`: loads the submodule at its G6 point; the names
  callers read come from the re-export block.

`ruff check --select F services/operator_queue_service/` is clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
@vybe

vybe commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-11-02): #4036 is merged as 9a3118a60, and this PR is off the train and needs a re-cut. Nothing is wrong with the design. Merging dev here is not mechanical: operator_queue_service/__init__.py conflicts across whole moved blocks, because #4021 and #4148 changed code this stack moves. Carrying those edits into the new modules by hand is a re-apply over your restructure, so it comes back to you.

Suggested: re-cut 4037, 4038 and 4039 on dev as fresh moves, since the branches also still carry the #4021 slice commits. #4037 and #4038 are retargeted to dev. #4039 still bases on issue-3785-pr2-pr3 until it is re-cut, and it should keep Fixes #3785. Two follow-ups for the stack are in my last comment on #4036: test_1595's module list, and the unpinned AgentClient and _audit_sync bindings.

Label status-needs-fix set; your next push clears it.

@vybe vybe added the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 2, 2026
@vybe
vybe changed the base branch from AndriiPasternak31/issue-3785-pr1 to dev November 2, 2026 05:46
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

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

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

Conflicts were resolved as a three-way merge against PR1's head (ec97b7a),
the base this branch was cut from, so dev's own edits apply on top of the moves:
#4148's `ADDRESSEE_REACH_ID_PREFIXES`, `is_addressee_reach` and the three
`_WORKSPACE_PROJECT_*` keys stay in `__init__`, beside `is_addressee_only` and
`_PLATFORM_CONTEXT_KEYS`, which this slice does not move. #4021 was already here
through PR1.
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

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

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

@github-actions github-actions Bot removed the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Nov 2, 2026

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

merge-train 2026-11-02: validated at bcc6d69.

@vybe
vybe merged commit 3d67f66 into dev Nov 3, 2026
24 checks passed
@vybe

vybe commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-11-02 note (non-blocking, merged): tests/unit/test_1595_sync_health_signals.py:49-63 (_STUBBED_MODULE_NAMES) pops services.operator_queue_service but not its submodules, so a narrow run of test_1595 → test_ent815 leaves stale listing/deps bound to the popped package (test_b14 newly fails that way; full CI is unaffected). A prefix pop fixes it — natural home is PR4 (#4039), along with the architecture docs that still name a single operator_queue_service.py.

AndriiPasternak31 added a commit that referenced this pull request Nov 4, 2026
…to filechannel

dev's #4037 moved the listing engine and poller core out of __init__, and
#4186 added the credential branch to `_clamp_ingested_item` plus the
`_primary_addressee` helper beside `_validated_addressee`. This branch moves
both of those into `filechannel.py`, so the resolution keeps the combined
__init__ (both moves applied) and re-applies the fence where the clamp now
lives. `_primary_addressee` is not re-exported (Invariant #1(a)).

An AST comparison of every function, method and module-level assignment in
dev's package against this tree finds 0 missing and 0 changed after module
qualification.
vybe added a commit that referenced this pull request Nov 17, 2026
* feat(subscriptions): an agent's share of a subscription, enforced at every door (#4180)

* feat(subscriptions): admission policy seam for a per-agent usage share (A)

One edition-agnostic point where a registered policy may stop an agent's
turn before it is admitted, on every door. With no policy registered
nothing changes. The first intended policy is an agent's share of its
subscription's usage, registered through this seam by an optional module.

- services/admission_policy.py: register / enforce / notice. A policy
  refuses with chat_signals.AdmissionRefused (code, plain-words message,
  frees_at); any other policy error is logged and the turn is admitted.
- /chat (admit_chat_request) and /task (dispatch_parallel_task) call it
  after the skill gate, before the idempotency claim: a refused request
  claims, uploads, writes and acquires nothing.
- execute_task step 1c covers every other door: the row closes SKIPPED
  with the message (not FAILED: no schedule failure count, no breaker),
  error_code usage_share, and the refusal on the result.
- routers/chat.py maps it to 429 + X-Trinity-Error-Code + Retry-After;
  a sync /task refused inside execute_task releases its claim and gets
  the same answer; the Workspace shows the message as category `limit`,
  not retryable.
- ExecutionContext.usage_notice renders the policy's notice as a
  `- **Usage**:` line via compose_system_prompt's auto-fill.

Tests: tests/unit/test_ent1059_admission_policy_seam.py (18). Each seam
call, the SKIPPED write, the router mapping, the Workspace branch, the
notice fill and the fail-open re-raise were removed one at a time and a
named test went red each time. test_2638's pre-dispatch allowlist gains
`policy_denied` with its reason.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(subscriptions): usage-share refusal survives the task backlog drain (B)

A share that ran out while a sync /task waited in the backlog: the drain
closes the row SKIPPED, and a long-poll that reads the terminal back from
the row (another worker drained it, or the wait timed out) rebuilt a
success-shaped result from a SKIPPED row. It now answers the seam's own
refusal.

- execute_task's policy gate stores the row error as `[usage_share] text`
  (the #3114 pull-sink shape), so a reconstruct can tell a share stop
  from any other SKIPPED; the in-memory result keeps the plain message.
- _dispatch_sync_backlog's reconstruct branch rebuilds AdmissionRefused
  from a SKIPPED row carrying that code; _map_task_failure then releases
  the claim and the router answers 429 usage_share (no Retry-After: the
  row has no frees_at, the message says when).

Tests: test_ent1059_admission_policy_seam.py +2 (20). The reconstruct
removed -> the drain test red; the prefix removed -> the SKIPPED-row test
red; each restored from a copy.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(subscriptions): usage share card and breakdown column (C)

An agent's share of its subscription's usage, as its owner reads and
changes it. Both surfaces render only when the instance is entitled to
`usage_share`; an unentitled build calls nothing.

- Settings > Guardrails gains a "Usage share" section (UsageShareCard):
  the rolling 7-day and 5-hour windows as used / budget with a meter, the
  warning line drawn at warn_pct, Warning / Stopped badges in words, when a
  stopped window frees, whether a stop ask is pending, the line the agent
  reads on its next turn, and where each number comes from. The owner
  changes it inline through the PUT; an empty field is the platform
  default and all three empty clears the override. Bounds are named
  client-side before a request; a refused PUT keeps the form open with an
  InlineError. Applies from the next turn, no restart.
- Settings > Subscriptions per-agent breakdown gains "Share used (7d · 5h)":
  each agent's own percent, warning/danger tone from the share's own
  threshold; a share the reader cannot see renders a dash, never 0%.
- stores/agents.js: getUsageShare / setUsageShare (single API client).
  stores/subscriptions.js: fetchAgentShares, per-agent isolated.

Tests: src/frontend/tests/unit/usageShareCard.spec.js (22, mounted under
jsdom). Mutations each turned it red and were restored from a copy:
breakdown ungated (1 red), at_budget ignored (2), client validation
bypassed (5), Guardrails section ungated (1). Raw-colour ratchet: no
existing file grew; the new card carries 0 raw non-gray.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(execution): every door answers an admission-policy refusal; a refused loop iteration is skipped, not failed (abilityai/trinity-enterprise#1059 fix)

Review C2, H1, the test_3274 sweep red and I5 on the pre-admission policy
seam.

C2: a turn an admission policy stopped inside `execute_task` is a SKIPPED
row `[usage_share] <sentence>`, and `_admission_policy_gate` returned it as
a result rather than raising — so every `dispatch_and_await_terminal` caller
that branched on failed/cancelled only answered success-shaped with an
empty reply. On the paid door that attached the execution to the claim,
logged verify-ok and SETTLED a charge for a turn that never ran.

- `chat_signals.admission_refusal_of(result, agent_name)` is the one rule:
  the in-memory attribute when the gate ran in this process, else a rebuild
  from the row's `skipped` + code shape. `result_from_execution_row`
  attaches it, so a turn refused on another worker (the backlog drain, a
  long-poll reading the row back) carries the same refusal; the separate
  rebuild in `_dispatch_sync_backlog` is that call now.
- One branch per door, before failed/cancelled: paid releases the claim and
  neither attaches nor settles (no charge; `payment.reason` is the
  sentence); MCP inline chat answers 429 with the sentence and
  `X-Trinity-Error-Code`; a channel sends the sentence and returns before
  step 12 so no empty assistant turn is persisted; the public link answers
  429 (sync) or stores the sentence as the reply (async); `portal_chat`
  reads status + code as well as the attribute; a room posts the policy's
  sentence and keeps its resume handle and cursor; A2A maps `skipped` to
  `rejected` with the message on the inline path as `_ROW_STATE` already
  did for the row; a refused validation turn is an ERROR verdict. The
  scheduler (`internal.py`), fan-out and operator-resume doors already
  record the skipped row with its message and need no branch; voice and
  the brain orb call `execute_task` directly and close SKIPPED.

H1: `loop_service._close_run` counted a policy-refused SKIPPED as a failed
run (only a gate-held SKIPPED was exempt), so `failed_runs` rose,
`on_failure` applied, and an at-budget loop kept ticking to `max_runs`. It
now reads the refusal off the row (`_split_error_code` + the predicate),
closes the run `skipped`, counts nothing, and stops the loop with the code
as `stop_reason`.

Sweep: `usage_notice` joins the platform-controlled list in
`test_3274_gate_context` — the line is composed by a policy from platform
numbers and never reads requester text. I5: `fetchAgentShares` runs at most
six reads in flight.

Docs: `requirements/security.md` §20.5d and `architecture/execution.md`
state the result-not-worker rule and each door's branch.

Red before the fix, with the door code reverted and the predicate kept:
all ten door tests in `test_ent1059_refusal_doors.py` (the paid one read
`settled`, the Workspace one DID NOT RAISE, A2A read `failed`) and both
loop variants beside the ent#751 hold test (`('failed', 'error')`);
restored byte-identical.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(completion-report): a refused turn's report shows the policy's sentence, not its [usage_share] code (abilityai/trinity-enterprise#1059 re-review N1)

An admission-policy refusal closes the row SKIPPED with `[usage_share] <sentence>`,
and the completion report (Workspace, Slack, Telegram) posted that text as-is.
The report now strips a known `[code]` prefix from a non-success terminal before
sanitising; an unknown `[...]` and any success text stay as the agent wrote them.
`_split_error_code` moves to the cycle-free `execution_envelope` leaf as
`split_error_code` so the report uses the same parser; the old names stay
importable from `task_execution_service`.

Also adds an executing spec for `fetchAgentShares`' six-lane cap (re-review N3):
a deferred `getUsageShare` over 15 names, high-water mark 6, every name written,
a failed read as `{ error: true }`. Mutation-checked: with the cap at 100 it
fails (expected 15 to be 6).

Red before the fix: test_the_workspace_report_shows_the_sentence_without_the_code,
test_the_channel_report_shows_the_sentence_without_the_code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(workspace): a credential handed in the chat — ask by name, masked field, stored in the agent's .env (trinity-enterprise#1066) (#4186)

* feat(asks): a credential ask kind the agent raises by name and only the secret field answers (trinity-enterprise#1066)

An agent that needs a secret asks for it BY NAME: `type: credential` with
`context.credential_name`. The ask sink validates the name through a new
policy leaf (`services/credential_ask_policy.py`: the agent reader's variable
charset, at most 64 characters, never a name the agent runtime refuses from
`.env` or one the platform writes — mirrored from the agent image's
`execution_env` and held in parity by test), refuses `options`
(`invalid_options`), and refuses the kind unless exactly one person is
resolved (`no_person`). The value never travels through an ask: `answer()`
takes `via_credential_sink`, and a credential row answered any other way
raises `CredentialAnswerRefused` → 422 `credential_answer_via_field` on both
doors (operator respond, Workspace answer). Dismiss is unchanged. The
Workspace projection carries `credential_name` only; the wake prompt names
the variable and says to read it from the environment, never a value.

Mutations recorded: removing the `via_credential_sink` check turns
TestAnswerRefusal (2) and TestOperatorDoor (1) red; disabling the `no_person`
check turns the three no-person cases red; both restored byte-identical.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(workspace): the secret field's sink stores the credential on the agent and answers the ask by name only (trinity-enterprise#1066)

A `credential` ask is answered through ONE new Workspace door,
`POST /api/enterprise/client-portal/asks/{id}/credential` (a person only —
`get_portal_principal` fences agent keys out before the row is read, a system
or ops key is 403 `person_required`; the same uniform 404 as the answer route,
which here also covers an ask of another kind). The service runs the answer
route's door checks (own ask, pending, not expired, not diverged) BEFORE the
value is handled, then hands it to the one secret-handling leaf,
`services/credential_sink.py`:

* the NAME re-checked against the ask policy (a file-channel row validates
  nothing) and the value checked by shape only (`invalid_value`: empty, below
  the scrub's floor, over 32 KiB, a line break or NUL);
* STAGED into the runtime identity scrub FIRST, fail-closed — 503
  `scrub_unavailable` when the store is down, so nothing is delivered that
  the scrub cannot see;
* the agent must be running (409 `agent_not_running`, naming the state);
* one sink write per agent at a time through a short Redis lease (409
  `env_busy`; a lease the store cannot grant is the same fail-closed 503);
* `.env` read through the agent's own `GET /api/credentials/read`, one line
  set in place through `agent_env_patch.set_keys` (the #2023 quoting the
  agent's reader reverses; duplicates collapsed; every other byte kept —
  round-tripped in test against the agent image's `parse_env_file`), refused
  over 256 KiB (`env_too_large`), written back through
  `POST /api/credentials/inject` (503 `agent_unreachable` on either leg);
* audit `credentials` / `chat_provide` with the name, the ask id and the file
  — never the value — and the requirements report cache dropped.

Only then does the ask sink end the row `provided` with `via_credential_sink`;
a compare-and-set lost after the write is 409 `already_resolved` with
`credential_written: true` and nothing is rolled back. The value appears in no
log line, no audit field, no refusal message, no response body and no wake
prompt — asserted in test on every path, and pinned by an AST guard over the
module: `value` may be measured, staged, patched into the file or passed on,
never formatted, logged, concatenated or raised.

Verified from the code, not the plan: the inject path is a whole-file
read-modify-write, so the lease is what keeps two sink writes from dropping
each other's key across workers. The owner's Credentials-tab inject and the
Nevermined bind (ent#966, "no agent-side lock, D8") do not take it and keep
their last-writer-wins contract — a documented residual of this change, not
closed by it.

Mutations recorded, each restored byte-identical: dropping `stage_secret`
(4 red), the running check (2), the lease (2), the file cap (1), the
line-break/NUL check (3), the kind check in the service (1), the person check
on the route (2), `via_credential_sink` (6), and a `logger.info` that formats
the value (the AST guard and the leak test, 2).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(workspace): a secret pasted as a plain chat message is refused before admission (trinity-enterprise#1066)

Both Workspace chat routes (`POST …/agents/{name}/chat` and `/chat/stream`)
refuse a message that LOOKS like a credential with 422 `secret_in_message`
after the roster and rate-limit gates and before anything else: no reply
context, no title decision, no session row, no execution row, and on the
streaming route no Idempotency-Key consumed (the ent#403 rule for a refused
model). The refusal names the SHAPE that matched and points at the secret
field a `credential` ask opens; it never carries the text.

The detector, `utils/credential_sanitizer.secret_shape`, runs over
`SECRET_VALUE_PATTERNS` — the one list the execution-log redaction already
uses — which gains two service-token shapes (`ops_…`, `dop_v1_…`) in BOTH
the backend and the agent-image copy, so logs learn them in the same change.
Two deliberate differences from redaction: `Bearer` / `Basic` are excluded
(in a chat message they are prose about an API, and a false refusal teaches
people to route around the guard), and a sensitive `KEY=value` pair counts
only with a value of 8+ characters (the identity scrub's own floor) under the
#3311 harmless-word blanking (`author=…` is not a credential). Every pattern
in the list is either named or excluded, and the test pins that partition
complete so a new shape cannot silently escape the guard.

Mutations recorded, each restored byte-identical: dropping the guard call on
the sync route (11 red), on the stream route (11), the `ops_` shape from the
redaction list (the both-copies redaction test), the `ops` entry from the
guard's names (3), the `KEY=value` branch (6), the value floor (3 prose
cases), and `Bearer` from the excluded set (the partition pin).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(mcp): ask_for_credential — an agent asks the person in the chat for a secret by name (trinity-enterprise#1066)

A one-purpose MCP tool over the credential ask kind: `ask_for_credential(name,
why, request_id?, expires_at?)` raises `type: credential`, titled "Needs NAME",
with `context.credential_name`, addressed to primary and carrying the turn id
so it reaches the person of the conversation. The body is built from the
declared fields only — a value, an agent name or options passed alongside
never travel. Left out, request_id is derived from the name and the turn, so
a retry in the same turn replays instead of asking twice. Refusals come back
named (no_person, invalid_credential_name). The description (1.6k characters,
under the 2,048 cap) says to ask only in a conversation with the person, never
to ask for a secret in a plain message, and to read the value from the
environment without repeating it. Registered in TOOL_ACCESS_POLICY as
self-acting; the documented tool count moves to 176.

Red first: the new describe block in operator_queue.test.ts failed on the
missing tool (TypeError reading execute/description) before the tool existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(workspace): a masked secret field in the thread for a credential ask (trinity-enterprise#1066)

`PortalCredentialField.vue` is what a `credential` ask renders as in
PortalAsks, wherever the card is mounted (thread, Inbox, rail, agent page): the
variable's name, a masked input (`type=password`, autocomplete/spellcheck off,
password-manager hints off) with Show/Hide, and Send. Send posts once through
the new store action `provideCredential` → `POST /asks/{id}/credential` with the
value in the body only, and the field is emptied BEFORE the request goes out,
so no component state holds the value whatever the server answers; unmounting
empties the element too. Nothing touches the drafts or storage, nothing is
logged, and each refusal the sink names (agent_not_running,
scrub_unavailable, asks_unavailable, already_resolved with or without
credential_written, the server's own invalid_value words) is said in an
InlineError. Discuss is hidden on the kind: a discussion chat is a composer.

The shared kind rule gains `credential` (`queueResponseKind`, label "Needs a
credential"), so the Operating Room card, the detail panel and /m show no
respond box or acknowledge for it — one line saying it is answered in the
person's Workspace. The thread's history row reads "NAME provided" and the
card "You provided NAME", never the stored response.

The composer, on a 422 `secret_in_message` from either chat route, drops the
failed bubble (a Retry would only re-send it), never hands the text back to
the composer, clears any draft still holding it, and shows the server's
pointer above the composer until the next send.

Design system: primitives only (BaseInput, BaseButton, InlineError), the card's
own ink, no raw colour — the new file starts at zero.

Red first: the three new mount specs failed on the missing component, the
`acknowledge` kind, the quoted "provided" answer and the visible respond box,
and on the secret staying in the thread. Mutations recorded: removing the
`secret` branch of settleDelivery turns 2 composer cases red; removing the
field's pre-request clear turns 6 field cases red; both restored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(workspace): build the credential-field fixtures at run time (trinity-enterprise#1066)

The two new specs carried token-shaped literals; the backend guard's tests
build theirs by concatenation so no token-shaped string sits in the tree.
Same here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(credentials): a credential handed in the chat — requirements, architecture, flow, user docs (trinity-enterprise#1066)

- requirements/credentials.md §3.10: the capability — ask by name, masked
  Workspace field, one `.env` line, "NAME provided", only the field answers,
  named refusals, what is out of scope.
- requirements/security.md §20.11: the one door, the one leaf (scrub first,
  fail closed; lease; one line; audit by name), the answer refusal, the name
  policy, the paste guard and the composer keeping no copy, and the stated
  residuals (channel adapters, non-sink `.env` writers last-writer-wins, live
  stream).
- architecture/backend.md: `credential_sink.py` and `credential_ask_policy.py`
  in the services catalog; the credential kind on the `ask_service` entry.
- architecture/mcp-server.md: `ask_for_credential` on the operator_queue.ts row.
- feature-flows/credential-in-chat.md (new) + index rows.
- user docs: how a person answers a credential ask and what happens when a
  secret is pasted into the chat (credential-management.md), the card and the
  tool in approvals.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(credentials): the secret sink never treats an unread .env as empty (trinity-enterprise#1066)

The sink rewrites the agent's whole `.env`. The agent's read endpoint
omitted the file from `files` in three cases that are not "no file": it
held a non-UTF-8 byte (returned in `files_b64`, which the sink never
read), the read raised (swallowed into a warning), or the path was not a
regular file. The sink mapped all of them to "" and the inject then
replaced the file with one line, deleting every other credential with a
success response.

The agent read endpoint now lists a path in `missing` only when lstat
raises FileNotFoundError, and reads from `_HOME` rather than a hard-coded
home. The sink treats `.env` as empty only when it is in `missing`; under
`files_b64` it is 409 `env_unreadable` (reason `not_utf8`), and absent
from all three maps (a read error, or an agent image older than the
list) it is 409 `env_unreadable` (reason `unconfirmed`). Nothing is
written in either case.

Red first: with the sink unfixed, a .env with other keys plus a Latin-1
byte and a .env mode 000 were both overwritten through the agent image's
real read/inject router over a tmp home (DID NOT RAISE), and so was an
omitted file from an older image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(credentials): the ops_ shape matches the service-account token, not snake_case (trinity-enterprise#1066)

`ops_[A-Za-z0-9_-]{20,}` matched any identifier of 20+ characters after
`ops_` — this platform's own `ops_context_critical_threshold` setting,
lease keys, function names. Because the shape sits in
SECRET_VALUE_PATTERNS, such an identifier was both refused as a pasted
secret in the Workspace chat and redacted from every persisted log, in
the backend and the agent image.

The token's real form is `ops_` + a base64url JSON document, which always
begins `eyJ`. Both copies now use `ops_eyJ[A-Za-z0-9_-]{40,}` (the guard's
name map with them; the partition test pins the three together).

Red first: three ops_ identifiers were refused by `secret_shape` and
redacted by `sanitize_text` in both copies (6 red); they now pass through
both, are admitted on both chat routes, and a realistic token is still
refused and redacted in both copies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(asks): a credential ask is addressed to primary only, on every door (trinity-enterprise#1066)

The MCP tool sent `to: primary`, but `_validated_ask` never looked at `to`
for the kind, so `POST /api/agents/{self}/operator-queue` accepted
`type: credential` addressed to `viewer`, `approver` or `role:<id>` as
long as one person filled it — handing a viewer a field that writes into
the agent's environment.

- `_validated_ask` refuses any role but primary for the kind with 422
  `invalid_to` (the REST door, which the MCP tool calls). `to: operator`
  is now refused there too, before addressing.
- The file channel never reaches `_validated_ask`: its clamp resolves the
  addressee from the entry's `addressed_to_email`. For the kind, an
  addressee who is not the agent's single primary person is dropped, so
  the item is ingested unaddressed (an operator item no Workspace field
  opens for). Fails closed on a resolution error, never raises (#1632).

Red first: `to` viewer / approver / role:finance were created or refused
with the wrong code (6 red), and the file-channel clamp kept a viewer as
the addressee (1 red).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(credentials): a refused credential write takes its value back out of the scrub (trinity-enterprise#1066)

The sink stages the value into the runtime identity scrub before it
checks the agent, takes the lease or touches the file. A refusal after
that (agent not running, env busy, lock store down, read unreachable,
env unreadable, file too large) left the value staged in Redis for 24 h
while the person was told "nothing was stored".

- `runtime_secret_scrub.stage_secret` now returns whether THIS call added
  the value; `unstage_secret` removes one (best-effort, never raises).
- The sink runs steps 3-5 in `_deliver` and, on a `CredentialSinkError`
  that left the agent's file untouched, unstages what it staged. A value
  staged earlier by something else keeps its protection.
- The inject leg is the exception: the agent may have written before
  failing, so the value stays staged and the message now says it may or
  may not be stored, instead of implying nothing was.
- Every pre-inject refusal message says nothing was stored, and now that
  is true of the scrub too.

Red first: the seven pre-inject refusal arms left the value staged and/or
did not say nothing was stored (7 red); the inject arms and the
already-staged case are pinned alongside.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(workspace): a credential card names the asking agent and quotes its reason (trinity-enterprise#1066)

A credential ask can be raised from any turn — a schedule's ask reaches
the owner's Inbox — and the card showed the agent's name only on
surfaces that pass `showAgent`, with the agent's `why` drawn as the
card's own body. A person could not always tell who was asking, or that
the reason was the agent's claim.

For the kind, the card now always says "<agent> is asking you for NAME"
(the agent's display label, else its name) and quotes the reason in a
blockquote under "In <agent>'s words:", or says it gave no reason. The
reason is drawn once, attributed, not also as the generic question. No
colour of its own (the raw-colour ratchet is unchanged).

Red first: the mount spec over the real PortalAsks and store found no
asker line and no attributed quote (2 red).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(workspace): pin the drafts-clearing loop in dropSecretMessage (trinity-enterprise#1066)

The review found no spec reached the loop: the composer watch already
clears THIS thread's draft when the send empties the field. The loop is
not redundant — it clears the same text left as a draft in ANOTHER
conversation (pasted there first, then sent here), which sits in local
storage. That case is now seeded and asserted, with an unrelated draft
kept.

Mutation: with the loop deleted from PortalConversation.vue the new case
goes red (1 failed); restored byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(credentials): the review fixes in the flow and the backend catalog (trinity-enterprise#1066)

Primary-only addressing (REST door and file channel), `env_unreadable`
and the agent read endpoint's `missing` list, unstaging on a refusal
before the inject, the attributed card, the tightened `ops_` shape, and
the owner-reach residual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

* chore(enterprise): bump the submodule pointer to main (bacec40 -> 448cdbc) (#4190)

Three enterprise commits, all on enterprise main: ent#982 (steward
proposes members and task owners), ent#1061 (a task reaches its owner
from the project record), ent#1070 (the per-agent usage share policy,
the private half of #4180).

Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

* feat(agents): a tag in github:owner/repo@ref pins the clone; purge_agent_now removes an agent at once, audit first (#4183)

* feat(subscriptions): admission policy seam for a per-agent usage share (A)

One edition-agnostic point where a registered policy may stop an agent's
turn before it is admitted, on every door. With no policy registered
nothing changes. The first intended policy is an agent's share of its
subscription's usage, registered through this seam by an optional module.

- services/admission_policy.py: register / enforce / notice. A policy
  refuses with chat_signals.AdmissionRefused (code, plain-words message,
  frees_at); any other policy error is logged and the turn is admitted.
- /chat (admit_chat_request) and /task (dispatch_parallel_task) call it
  after the skill gate, before the idempotency claim: a refused request
  claims, uploads, writes and acquires nothing.
- execute_task step 1c covers every other door: the row closes SKIPPED
  with the message (not FAILED: no schedule failure count, no breaker),
  error_code usage_share, and the refusal on the result.
- routers/chat.py maps it to 429 + X-Trinity-Error-Code + Retry-After;
  a sync /task refused inside execute_task releases its claim and gets
  the same answer; the Workspace shows the message as category `limit`,
  not retryable.
- ExecutionContext.usage_notice renders the policy's notice as a
  `- **Usage**:` line via compose_system_prompt's auto-fill.

Tests: tests/unit/test_ent1059_admission_policy_seam.py (18). Each seam
call, the SKIPPED write, the router mapping, the Workspace branch, the
notice fill and the fail-open re-raise were removed one at a time and a
named test went red each time. test_2638's pre-dispatch allowlist gains
`policy_denied` with its reason.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(subscriptions): usage-share refusal survives the task backlog drain (B)

A share that ran out while a sync /task waited in the backlog: the drain
closes the row SKIPPED, and a long-poll that reads the terminal back from
the row (another worker drained it, or the wait timed out) rebuilt a
success-shaped result from a SKIPPED row. It now answers the seam's own
refusal.

- execute_task's policy gate stores the row error as `[usage_share] text`
  (the #3114 pull-sink shape), so a reconstruct can tell a share stop
  from any other SKIPPED; the in-memory result keeps the plain message.
- _dispatch_sync_backlog's reconstruct branch rebuilds AdmissionRefused
  from a SKIPPED row carrying that code; _map_task_failure then releases
  the claim and the router answers 429 usage_share (no Retry-After: the
  row has no frees_at, the message says when).

Tests: test_ent1059_admission_policy_seam.py +2 (20). The reconstruct
removed -> the drain test red; the prefix removed -> the SKIPPED-row test
red; each restored from a copy.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(subscriptions): usage share card and breakdown column (C)

An agent's share of its subscription's usage, as its owner reads and
changes it. Both surfaces render only when the instance is entitled to
`usage_share`; an unentitled build calls nothing.

- Settings > Guardrails gains a "Usage share" section (UsageShareCard):
  the rolling 7-day and 5-hour windows as used / budget with a meter, the
  warning line drawn at warn_pct, Warning / Stopped badges in words, when a
  stopped window frees, whether a stop ask is pending, the line the agent
  reads on its next turn, and where each number comes from. The owner
  changes it inline through the PUT; an empty field is the platform
  default and all three empty clears the override. Bounds are named
  client-side before a request; a refused PUT keeps the form open with an
  InlineError. Applies from the next turn, no restart.
- Settings > Subscriptions per-agent breakdown gains "Share used (7d · 5h)":
  each agent's own percent, warning/danger tone from the share's own
  threshold; a share the reader cannot see renders a dash, never 0%.
- stores/agents.js: getUsageShare / setUsageShare (single API client).
  stores/subscriptions.js: fetchAgentShares, per-agent isolated.

Tests: src/frontend/tests/unit/usageShareCard.spec.js (22, mounted under
jsdom). Mutations each turned it red and were restored from a copy:
breakdown ungated (1 red), at_budget ignored (2), client validation
bypassed (5), Guardrails section ungated (1). Raw-colour ratchet: no
existing file grew; the new card carries 0 raw non-gray.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(execution): every door answers an admission-policy refusal; a refused loop iteration is skipped, not failed (abilityai/trinity-enterprise#1059 fix)

Review C2, H1, the test_3274 sweep red and I5 on the pre-admission policy
seam.

C2: a turn an admission policy stopped inside `execute_task` is a SKIPPED
row `[usage_share] <sentence>`, and `_admission_policy_gate` returned it as
a result rather than raising — so every `dispatch_and_await_terminal` caller
that branched on failed/cancelled only answered success-shaped with an
empty reply. On the paid door that attached the execution to the claim,
logged verify-ok and SETTLED a charge for a turn that never ran.

- `chat_signals.admission_refusal_of(result, agent_name)` is the one rule:
  the in-memory attribute when the gate ran in this process, else a rebuild
  from the row's `skipped` + code shape. `result_from_execution_row`
  attaches it, so a turn refused on another worker (the backlog drain, a
  long-poll reading the row back) carries the same refusal; the separate
  rebuild in `_dispatch_sync_backlog` is that call now.
- One branch per door, before failed/cancelled: paid releases the claim and
  neither attaches nor settles (no charge; `payment.reason` is the
  sentence); MCP inline chat answers 429 with the sentence and
  `X-Trinity-Error-Code`; a channel sends the sentence and returns before
  step 12 so no empty assistant turn is persisted; the public link answers
  429 (sync) or stores the sentence as the reply (async); `portal_chat`
  reads status + code as well as the attribute; a room posts the policy's
  sentence and keeps its resume handle and cursor; A2A maps `skipped` to
  `rejected` with the message on the inline path as `_ROW_STATE` already
  did for the row; a refused validation turn is an ERROR verdict. The
  scheduler (`internal.py`), fan-out and operator-resume doors already
  record the skipped row with its message and need no branch; voice and
  the brain orb call `execute_task` directly and close SKIPPED.

H1: `loop_service._close_run` counted a policy-refused SKIPPED as a failed
run (only a gate-held SKIPPED was exempt), so `failed_runs` rose,
`on_failure` applied, and an at-budget loop kept ticking to `max_runs`. It
now reads the refusal off the row (`_split_error_code` + the predicate),
closes the run `skipped`, counts nothing, and stops the loop with the code
as `stop_reason`.

Sweep: `usage_notice` joins the platform-controlled list in
`test_3274_gate_context` — the line is composed by a policy from platform
numbers and never reads requester text. I5: `fetchAgentShares` runs at most
six reads in flight.

Docs: `requirements/security.md` §20.5d and `architecture/execution.md`
state the result-not-worker rule and each door's branch.

Red before the fix, with the door code reverted and the predicate kept:
all ten door tests in `test_ent1059_refusal_doors.py` (the paid one read
`settled`, the Workspace one DID NOT RAISE, A2A read `failed`) and both
loop variants beside the ent#751 hold test (`('failed', 'error')`);
restored byte-identical.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(completion-report): a refused turn's report shows the policy's sentence, not its [usage_share] code (abilityai/trinity-enterprise#1059 re-review N1)

An admission-policy refusal closes the row SKIPPED with `[usage_share] <sentence>`,
and the completion report (Workspace, Slack, Telegram) posted that text as-is.
The report now strips a known `[code]` prefix from a non-success terminal before
sanitising; an unknown `[...]` and any success text stay as the agent wrote them.
`_split_error_code` moves to the cycle-free `execution_envelope` leaf as
`split_error_code` so the report uses the same parser; the old names stay
importable from `task_execution_service`.

Also adds an executing spec for `fetchAgentShares`' six-lane cap (re-review N3):
a deferred `getUsageShare` over 15 names, high-water mark 6, every name written,
a failed read as `{ error: true }`. Mutation-checked: with the cap at 100 it
fails (expected 15 to be 6).

Red before the fix: test_the_workspace_report_shows_the_sentence_without_the_code,
test_the_channel_report_shows_the_sentence_without_the_code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agents): a dotted tag in github:owner/repo@ref pins the clone

The ref after `@` was checked against [A-Za-z0-9_-/] only, so a release tag
such as v1.2.0 failed the check and was dropped without a word: the agent was
created on main while the caller believed it pinned. The ref is now taken
whole when it is a valid branch or tag name (dots allowed, minus the git
ref-format shapes '..', a leading-dot component, a trailing '.' or '.lock'),
and an unusable ref is a named 400 instead of a silent fall-back to main.
The charset stays a shell-safety barrier for startup.sh's eval-built clone.

Red first: tests/unit/test_4165_github_ref_tag.py — the five dotted refs
returned url_branch=None and the ten unusable refs did not raise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(agents): purge_agent_now removes an agent at once, audit first (abilityai/trinity-enterprise#1055)

Agent delete is a soft delete (#834): rows, volumes and the MCP key stay for
the retention window. Removing an invited member's agent, or rolling back a
half-created one, must leave nothing but the audit trail, so the retention
sweep's hard purge becomes an immediate, edition-agnostic primitive with no
route of its own:

- the agent_lifecycle:purge audit row is written while the agent still
  exists and outlives it; if it cannot be written nothing is destroyed (503)
- a person caller must pass assert_admin (an agent key carrying an admin
  owner's role is refused); actor=None is the platform itself
- container, queued and in-flight work, Redis state, the #816 cascade
  (sharing, permissions both ways, MCP key) and the data volumes under both
  identities of a renamed agent (#1664) go; a base another agent claims
  stays; a Docker fault never stops the row purge
- system agents (403) and ephemeral agents (409) are refused; no row is a no-op

Red first: tests/unit/test_ent1055_purge_agent_now.py (module absent). Each
of five mutations turns it red: admin gate removed (2), fail-closed removed
(1), soft-delete-before-purge removed (7), base-claim guard removed (1),
audit moved after the container removal (2).

Docs: requirements/core-agent.md §1.4.1 and §4.2 ref pinning (trinity#4165);
architecture/agent-lifecycle.md pointer. Registry: both new test files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agents): a tag in github:owner/repo@ref survives the three ref-existence checks (trinity#4165, abilityai/trinity-enterprise#1055 review C1)

The parser accepted a dotted tag and stored it in `source_branch`, but every
check that consumed that value before the clone asked for a BRANCH of that
name: `provisioning.check_remote_branch_exists` ran `ls-remote --heads
refs/heads/<ref>`, `ref_probes._ref_arg` prefixed `refs/heads/`, and the
PAT path asked `GET /repos/{repo}/branches/{ref}`. So a tag passed the
parser and was refused with "Branch 'v1.2.0' not found" on every path; the
public doc claimed it pinned the clone.

Now all three accept a branch or a tag, the ref still a value after the URL
and never an option: the anonymous check asks for `refs/heads/<ref>
refs/tags/<ref>` with no `--heads`; the probes ask for both and take the
branch first (as `git clone -b` does), peeling an annotated tag to its
commit; the REST path answers a 404 on `/branches/{ref}` with
`/git/ref/tags/{ref}` before calling the ref missing. The refusal names
both: "Branch or tag '…' not found".

Red first: `tests/unit/test_4165_ref_existence_checks.py` drives the real
`check_remote_branch_exists`, `probe_anonymous_ref`,
`probe_tokened_repo_access` and `_validate_github_access` on all three
paths against a fake `ls-remote` that filters like git (so a check that
asks for heads only cannot see the tag) — 9 of 15 red before the change,
all green after. Three pins on the old branch-only contract moved with it
(`test_3725_*`: the argv now carries both refs and a same-named tag answers
when no branch does; `test_ent123_tokenless_clone`: the wording).

Docs: `requirements/core-agent.md` §4.2 names the three checks and the
precedence; the two flow rows that quoted `--heads` / the old wording
follow. Registry entry added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(agents): a ref in github:owner/repo@ref may not begin with '-' (trinity#4165, abilityai/trinity-enterprise#1055 review I5)

`_GITHUB_REF_RE` admitted `-foo`. Safe today — every live site passes the
ref as a value (`git clone -b <ref>` takes the next token whatever it
starts with; the probes prefix `refs/…`) — but `startup.sh` also runs
`git checkout "${SOURCE_BRANCH}"`, where a leading `-` IS parsed as an
option, benign only because the clone already checked the ref out. One
shell edit away from not. The regex gains `(?!-)`; the 400 names it.

Red first: `TestRefRefused[-foo]` — DID NOT RAISE. Upgrade-safe: the parser
has one caller (creation); no stored `source_branch` is re-parsed on boot,
pull or reset, so existing agents are untouched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(agents): an annotated tag in @ref resolves to its commit, not the tag object (trinity#4165)

`ref_probes` asked `ls-remote` for `refs/heads/<r>` and `refs/tags/<r>` and
took a peeled `refs/tags/<r>^{}` line when one was listed. git never listed
one: it shows a ref only when a pattern names it, and the peeled line's name
ends in `^{}`. So an annotated tag resolved to the TAG OBJECT, and the raw
template read was pinned to an id that is not the commit the clone checks
out. The probe now also asks for `refs/tags/<r>^{}` by name.

The unit fake listed `^{}` lines for a bare tag pattern, which is why the old
test passed. It now lists a ref only when a pattern names it, and a new file
runs the probes against a real bare repository over file:// (a lightweight
tag, an annotated tag, a branch and an annotated tag sharing a name).

Red first: test_4165_ref_probes_real_git.py — the annotated-tag and tokened
cases returned the tag object id; 4 others passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agent-server): a tag-pinned agent's pull cycle is a named skip, not a failure every tick (trinity#4165)

`github:owner/repo@<tag>` clones with `git clone -b <tag>` in source mode,
which leaves the agent on a detached HEAD: pinned to that release, by design.
Pull sync is on for every `github:` agent, and `_run_pull_once` recorded
`failed: detached HEAD: nothing to pull onto` on every cycle, a failure
streak for an agent doing what it was asked to.

A detached HEAD now records `skipped` with the reason named. A detached HEAD
left by a rebase stopped part-way (its rebase-merge/rebase-apply directory
exists) stays `failed`, so a stuck tree still shows. The push cycle is
unchanged: it is off by default for a source-mode agent, and an owner who
turns it on for a pinned agent gets an honest failure.

Red first: test_4165_pull_cycle_pinned_tag.py::test_every_cycle_is_a_named_skip_not_a_failure
— 'failed' == 'skipped'. Real repos, the agent cloned -b v1.0.0 (annotated).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>

* fix(credentials): keep the credential read inside the agent home and make the paste guard linear (#4191)

* fix(agent-server): the credential read stays inside the agent home (trinity-enterprise#1066)

CodeQL flagged the `os.lstat` this branch added to `GET /api/credentials/read`
(path depends on a user-provided value). The finding is real at the guard,
not at any current caller:

- the guard (`lstrip("/").lstrip(".")`, a `".." in` test on the stripped
  string, `str(resolved).startswith(str(home))`) let a single leading `../`
  through, and its prefix compare had no separator, so `../home2/.env`
  READ a file in a sibling directory whose name extends the home's;
- the new `lstat` ran before any containment check, so `../<anything>`
  came back in `missing` — an existence probe one level above the home.

Not reachable before this fix through the platform: the route sits behind
the agent's per-agent auth middleware (#1159) and every backend caller sends
fixed relative paths (`.env`, `.mcp.json`, `.credentials.enc`) or the agent's
own `/list` output.

Fixed at the root with one helper, `_contained_read_target`: refuse absolute
paths and any `..` component, then require both the normalised lexical path
and the link-resolved path to sit under the home with a trailing separator.
`lstat` runs on the contained lexical path (the absence proof); the read goes
through the contained resolved path, so a link is followed only to a target
that is itself inside.

Red first: tests/unit/test_ent1066_credential_read_containment.py — 5 of 13
red at the previous guard (sibling read, `../` oracle, absolute path, link to
a sibling file, linked parent directory), all green with the fix; the fix
reverted from a scratch copy turns the same 5 red.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sanitizer): the paste guard's KEY=value walk is linear by construction (trinity-enterprise#1066)

CodeQL flagged the two regex calls in `secret_shape` (py/polynomial-redos,
"may run slow on many repetitions of '!'"). Origin: the patterns pre-exist
on dev — `_KV_LINE_RE` / `_KV_PAIR_RE` are the redaction's #1661/#3311 walk —
but these two alerts are introduced by this branch, which feeds them a
Workspace chat message (user-provided text) through the new guard.

Measured before the change, CPython was already linear on every shape tried
(`!`*n, `=`+`!`*n, `!`*n+`=`, `!=`*n, `k=!`*n, an unclosed quote, sensitive
keys with short values): 1M characters took 0.04-1.1 s, scaling ~10x per
10x. The lookbehind pins each key to the start of its run — the engine
detail CodeQL's model does not see (#1661 says the same). The route caps a
message at 100k characters.

The guard no longer rests on that detail. It finds each `=` with
`str.find`, walks back to the key start (never past the previous `=`, so
no character is visited twice), and checks the value with one fixed-width
match — an optional opening quote and eight non-space, non-quote
characters. No length cap, so nothing at the end of a long message is
dropped. One deliberate widening: the closing quote is no longer required,
because a truncated paste is still the secret. The redaction path is
unchanged.

Red first: tests/unit/test_ent1066_secret_guard_linear.py — red before the
change on the no-unbounded-regex pin and the unclosed-quote case (2 of 43);
the timing bound (1M < 3 s, 10x input < 30x time) and both-way detection
were green before and after. The change reverted from a scratch copy turns
the same 2 red. The 1661/2208/2398/3840 sanitizer suites and the paste-guard
suite stay green (608 passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* chore(enterprise): bump the submodule pointer to main (448cdbc -> f347a02) (#4193)

Picks up abilityai/trinity-enterprise#1072 (member_agents module, ent#1055),
which composes the purge_agent_now primitive from #4183.

Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* revert: an agent's share of a subscription (#4180) (#4199)

* Revert "feat(subscriptions): an agent's share of a subscription, enforced at every door (#4180)"

This reverts commit 9eedbbb6e0be8d5b73ccb5e8f0217a33a987b089.

* chore(enterprise): bump the gitlink to the ent#1070 revert (trinity-enterprise#1076)

Lands with the #4180 revert so dev never carries the usage_share module
without the admission_policy seam it imports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sub-003): the agent's auth answer outranks a prompt-length mention, and the turn-limit anchor is pinned (#4123) (#4197)

* fix(workspace): keep a room's content inside the Inbox reading pane (#4160) (#4169)

Every agent bubble renders PortalMarkdown's sr-only live region, which is
position:absolute. The reading pane's scroll box was not positioned, so
those regions resolved against the page, escaped the overflow box, and a
long room stretched the document: the wheel scrolled the whole Workspace.
Make the scroll box `relative`, as the list column's already is.

Adds a mount spec pinning the containment structure for a long room, a
room with many messages, and a thread.

Fixes #4160

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(operator-queue): the listing engine moves to listing.py, and the poller core into PollerCoreMixin (#3785, PR 2 of 4) (#4037)

* fix(operator-queue): the #1677 helper delegates to the platform-alert seam

create_bounded_alert(_outcome) keep their signatures and outcome contract
and become a thin delegate of platform_alerts.observe, which already
composes the per-(agent, type) budget inside its one locked create. The
registered type names its kind; the key is read back from the item's id
and context by derive_legacy_subject and must resolve to that same kind,
else ALERT_FAILED_CREATE. The two kinds whose ids carry no subject
(gitignore, problem report) are keyed by the request id minus the kind's
prefix. observe's "updated" and "snoozed" pass through; "failed" maps to
ALERT_FAILED_CREATE; every refused or failed arm logs [#1677 budget].
ALERT_FAILED_COUNT stays importable and is no longer returned.

The budget episode reports through observe as kind alert_budget keyed by
the budgeted type: one alert_budget:<type> row per agent, re-read by a
later refusal outside the cooldown, ended by its 14-day lifetime. The
bucketed id and its own operator_queue_new broadcast are gone; observe
sends the thin operator_queue_sync trigger.

Ratchet: create_bounded_alert_outcome and _maybe_emit_alert_budget_episode
leave EMITTERS_NOT_YET_ON_SEAM; alert_budget gets a NO_CLEAR_SITE reason.
Census: both leave _ALLOWED_CALLERS (no direct create left in either).

#3254 re-pins (asserted outcomes unchanged):
- test_1677_operator_alert_budget: write-observation point. The harness
  stands in for the seam's create with the same budget arithmetic and
  runs what observe spawns. Id shape in
  test_deterministic_bucketed_id_with_reserved_prefix,
  test_cooldown_knob_zero_never_raises (the subject replaces the bucket)
  and test_under_cap_creates_item_and_notification (the seam's id). The
  episode raise now stays in its spawned task, so
  test_episode_helper_raise_swallowed_refusal_stands reads the delegate's
  WARNING marker; test_ws_broadcast_failure_swallowed checks the thin
  operator_queue_sync payload.
- test_3130_flood_guard, test_1632_operator_queue_caps: write-observation
  point. The flood alert still rides the delegate, so its writes, the
  typed budget read and the I1 fault injection move to the seam's create.
- test_3243_atomic_asks::test_a_cap_hold_never_fires_the_flood_alert:
  write-observation point. Watched at observe, since the oqs.db assertion
  alone would now pass whether or not the alert fired.

Known until the problem report moves in its own commit: nine
test_3521_problem_report_comment cases are red here. The delegate files
an event-kind row under the seam's id, which the old _attach_comment
(keyed on the pre-seam request id) cannot find.

New: tests/unit/test_3254_budgeted_alerts.py (registry parity, reach-back
imports, the delegate's outcome table over all five budgeted types, the
episode's seam properties, R1 for alert_budget).

Part of #3254

* fix(operator-queue): the flood alarm reports through the seam and ends with its episode

OperatorQueueSyncService._maybe_emit_flood_alert reports through
platform_alerts.observe as kind queue_flood keyed by the reason: one
pending row per (agent, reason), rewritten in place, budgeted by the
seam. #3130's outcome rule is kept on observe's strings: a failed write
releases the episode and is retried after the cooldown (I1); created,
updated, snoozed and refused consume it.

While an episode lasts it is re-read at most every 6 hours, so the kind's
14-day lifetime ends only a row nobody re-read, never a condition that
still holds. The refresh time per (agent, reason) is a dict the method
creates on the instance for itself; __init__ is unchanged. The flood's
own operator_queue_new broadcast (which carried the title) is gone;
observe sends the thin operator_queue_sync trigger.

The two _sync_agent statements where an episode ends
(_flood_episodes.discard for oversize_file and ingestion_cap) become
calls to the new _end_flood_episode, which ends the episode and, only
when one was running, ends its alert as the platform through
platform_alerts.clear. A cycle with no episode costs no read.

Ratchet: _maybe_emit_flood_alert leaves EMITTERS_NOT_YET_ON_SEAM;
queue_flood's clear site is _end_flood_episode.

No re-pin in this commit: the #3130 and #1632 harnesses were moved to
the seam's create in the previous commit and keep their results.

Tests: the flood through the real _sync_agent poll for 30 simulated days
with the real expiry sweep (one row, re-read every 6 hours, ended as the
platform when nothing is held), no read without an episode, two reasons
two subjects, I1 on the real seam, a person's ending standing through the
re-read and the clear, the thin trigger, R1 for queue_flood.

Part of #3254

* fix(execution): the effect guard and missing-skill alarms report through the seam

_on_unguarded_effect reports a refused effect through
platform_alerts.observe as kind effect_unguarded keyed
"<effect_type>:<reason>": one row per agent, effect and reason,
rewritten by each further refusal, ended by its lifetime (nothing
observes an agent starting to send ids). The send is refused whatever
the alarm's outcome.

_alert_skill_not_found reports through observe as kind skill_not_found
keyed by the truncated command: one row per agent and command, re-read by
each scheduled run. The paired notification is sent only on "created": a
repeat of a pending command is an "updated" reading and already had one;
refused, failed and snoozed wrote no new row. The pre-create dedup read
stays and now matches only a pending pre-#3246 row (no subject), which
keeps standing for its command until the upgrade sweep stamps it; a seam
row is re-read through observe, where a repeat is never refused at the
cap.

task_execution_service.py: only _alert_skill_not_found changes. Its
module-level utc_now_iso import is now unused and is left in place.

Ratchet: _on_unguarded_effect and _alert_skill_not_found leave
EMITTERS_NOT_YET_ON_SEAM; skill_not_found gets a NO_CLEAR_SITE reason
(only the dispatch path could see a command resolve, and there the
detector cannot tell "resolved" from "not a slash command").

#3254 re-pins (asserted outcomes unchanged):
- test_1677_operator_alert_emitters::
  test_skill_not_found_emitter_is_routed_not_allowlisted: the module must
  call platform_alerts.observe naming "skill_not_found" (AST), the seam
  that composes the budget, instead of mentioning create_bounded_alert.
- test_2392_effect_guard_fail_closed: write-observation point and id
  shape. The alarm is recorded at platform_alerts.observe instead of a
  sys.modules stub of operator_queue_service, which lacks the names the
  seam reaches back for. The id prefix is asserted on the kind; the
  at-budget case returns the seam's refused_at_budget.
- test_ent879_aauth_resource_route (the refused-call case): the dead
  create_bounded_alert patch moves to platform_alerts.observe.

Tests: the effect refusal's seam properties and lifetime; the missing
skill's one row per command, no notification on a repeat, a pre-seam row
still standing, no notification at the cap; R1 for both kinds; the other
shape, the clock 30 days ahead: a full skill_not_found budget frees
itself through the real expiry sweep and a new command files.

Part of #3254

* fix(git-sync): the gitignore sweep's alert is one row per change set

_emit_gitignore_untracked_alert reports through platform_alerts.observe
as kind gitignore_untracked, which stops being an event kind
(platform_alerts.py: event=True dropped). It is a must-act kind: no
lifetime, never ended by the platform.

It is keyed by the change itself: a 32-hex digest of the canonical,
direction-tagged set of paths the Push untracked and newly un-ignored
(sorted removed paths, the exact removed count, sorted un-ignored paths).
A repeat of the same set collapses onto one row; a different set, a
different total behind a capped list, or the same path in the other
direction is a different row. Keying per agent would let a later Push
overwrite an earlier Push's path list on a pending must-act alert, which
#2529 calls the surface that outlives the session. The legacy prefix
keeps its _no_subject parser, so pre-existing rows stay pending until a
person acts.

Ratchet: _emit_gitignore_untracked_alert leaves EMITTERS_NOT_YET_ON_SEAM.

#3254 re-pins (asserted outcomes unchanged):
- test_2529_gitignore_precedence: write-observation point and id shape.
  The alert is watched at platform_alerts.observe (the two
  create.await_count == 0 checks would otherwise have gone vacuous); the
  per-agent id prefix is asserted on the kind, with the 32-hex key.
- test_3246_platform_alerts_leaf::test_event_kind_has_no_subject:
  gitignore_untracked is a condition now, so it is asserted keyed and the
  problem report stays the event example.

Tests: a repeated set is one row that never expires; distinct sets and a
capped list with another total stay distinct; the direction tag holds;
a person's ending stands; the 30-day case now also shows the gitignore
row still pending.

Part of #3254

* fix(workspace): the problem report is one seam row per person, target and day

raise_problem_report reports through platform_alerts.observe as kind
workspace_problem_report, which stops being an event kind (event=True
dropped). It is keyed by the 32-hex digest _problem_report_id already
computes: one row per person per target per UTC day, the "never
duplicates" rule its docstring states. A person must act on it, so it
never expires and the platform never ends it. The workspace-problem- id
prefix is kept, so ent#866's owner-only rule and the machine-key "about a
person" exclusion still hold. It returns True when the row was created or
updated, False when snoozed, refused or failed.

#3521's words-only rule moves under the seam's lock. observe gains
keep_text (passed through database.create_platform_operator_queue_item to
create_platform_item and _touch): with keep_text and a pending row, the
reading only counts (last_seen_at, seen_count, expires_at) and the title,
question, priority and context stand. The bare click passes keep_text, a
reading with words does not. The click and the comment are two background
requests that meet on one row inside the per-agent lock, so either order
ends with the words. With no pending row the reading files as usual.

update_pending_problem_report (database.py, db/operator_queue.py) and the
nested _attach_comment are removed: one write path.

Ratchet: raise_problem_report leaves EMITTERS_NOT_YET_ON_SEAM, which
fixes the nine test_3521 cases the delegate commit left red.

#3254 re-pins (asserted outcomes unchanged):
- test_3521_problem_report_comment: the acknowledgement fixture goes
  through ask_service.answer (fixture shape; a raw status UPDATE carries no
  person ending for the snooze to read); the accessor test asserts the
  same type guard at the seam (a foreign row under the report's old id is
  never written); the lost-race test injects the bare click's whole
  reading, in its own thread, before the comment's locked create.
- test_ent499_problem_report: write-observation point. The fake moves from
  create_bounded_alert to platform_alerts.observe; the routing AST test
  asserts the call to observe.
- test_ent715_queue_person_fields: update_pending_problem_report leaves
  _NON_ROW_ACCESSORS (the accessor census forbids a stale entry).
- test_3246_platform_alerts_leaf::test_event_kind_has_no_subject: no
  built-in kind is an event any more, so the property is pinned on a kind
  registered for the test, and both former events are asserted keyed.
test_ent866_problem_report_owner_only is unchanged.

Tests: keep_text at the sink, both interleavings keeping the words, one
must-act row per person, target and day, the owner-only prefix, the
delegate and the emitter landing on one subject, a person's ending not
rewritten or reopened; the 30-day case now also shows the report still
pending; the five-type admission test asserts every kind keyed.

Part of #3254

* fix(operator-queue): decide a platform alert's snooze under the create's lock

observe checks the snooze before the create's lock. Two moments let a
person's ending slip past that check: an acknowledgement after observe
read the pending row but before the locked create (the locked find then
misses), and one between the locked find and _touch's compare-and-set
(the lock covers creates, not respond_to_item, so the CAS loses). Either
way the create fell through to an insert, and the alert a person had just
ended was back at once. Before this batch most of the moved writers had a
deterministic id that could not re-file after an ending, so the moves
would otherwise ship that regression.

create_platform_item gains snooze_since and a snoozed predicate. On the
insert path, after a missed find or a lost CAS and inside the same locked
transaction, it reads the newest person-ended row for the subject through
the transaction's own connection (the public lookup opens another one)
and returns {"outcome": "snoozed"} without inserting when the predicate
says so. observe passes the standard 7-day window, computed on its own
rather than from the pre-lock check's conditionally assigned cutoff, and
lambda ended: _snoozed_by(kind, ended, priority, context). The pre-lock
check stays as the fast path. A caller that passes neither keeps the old
behaviour.

The statement behind the public find_person_ended_by_subject becomes
_find_person_ended_by_subject(conn, ...), shared by both reads.

Tests: a person's acknowledgement through ask_service.answer, landed (a)
between observe's read and the locked create and (b) between the locked
find and the CAS, yields "snoozed" and no new row, for the problem
report, an inbox collision as registered on dev, and the flood alarm's
6-hourly re-read. All six cases were red before this commit (a fresh row
was created) and pass with it. On SQLite, BEGIN IMMEDIATE holds every
other writer, so moment (b) lands the ending first and hands both finds
the row as it stood just before it; two real workers are not exercised.

Review fixes carried here (the earlier commits are left as they are):
- OperatorQueueSyncService._maybe_emit_flood_alert: the cooldown is
  stamped before every reading, the 6-hourly re-read included. A failed
  re-read released the episode with the cooldown stamp still 6 hours
  old, so it was retried on the next 5-second cycle. New test: a failed
  re-read is retried no sooner than the cooldown (red before the fix).
- test_3521_problem_report_comment (the lost-race re-pin): asserts the
  bare click's own request returned True and left a pending, comment-free
  row before the comment's locked create ran, so the test cannot pass
  without the interleaving it claims.
- gitignore_sweep: states that past the probe's 2,000-line cap the key is
  the capped list plus the exact total (a full-set digest needs the
  in-container probe, outside this change).
- test_1677_operator_alert_emitters: the census's guidance for an
  agent-influenceable emitter now points at platform_alerts.observe, not
  the delegate the #3246 ratchet counts as off the seam.
- test_3254_budgeted_alerts: the frozen clock also covers
  db.operator_queue's ent#815 commit-lag check, which logged spurious
  errors against the real clock.

Part of #3254

* fix(operator-queue): a failed flood re-read keeps the episode, so its end still clears the alert

Fresh review of the #3254 budgeted slice (two findings):

- A failed 6-hourly re-read of a persisting flood released the episode.
  If the condition then cleared before the retry, `_end_flood_episode`
  found no episode and the pending alert waited out its 14-day lifetime,
  although the code had …
vybe added a commit that referenced this pull request Nov 17, 2026
…4622)

* feat(agents): a tag in github:owner/repo@ref pins the clone; purge_agent_now removes an agent at once, audit first (#4183)

* feat(subscriptions): admission policy seam for a per-agent usage share (A)

One edition-agnostic point where a registered policy may stop an agent's
turn before it is admitted, on every door. With no policy registered
nothing changes. The first intended policy is an agent's share of its
subscription's usage, registered through this seam by an optional module.

- services/admission_policy.py: register / enforce / notice. A policy
  refuses with chat_signals.AdmissionRefused (code, plain-words message,
  frees_at); any other policy error is logged and the turn is admitted.
- /chat (admit_chat_request) and /task (dispatch_parallel_task) call it
  after the skill gate, before the idempotency claim: a refused request
  claims, uploads, writes and acquires nothing.
- execute_task step 1c covers every other door: the row closes SKIPPED
  with the message (not FAILED: no schedule failure count, no breaker),
  error_code usage_share, and the refusal on the result.
- routers/chat.py maps it to 429 + X-Trinity-Error-Code + Retry-After;
  a sync /task refused inside execute_task releases its claim and gets
  the same answer; the Workspace shows the message as category `limit`,
  not retryable.
- ExecutionContext.usage_notice renders the policy's notice as a
  `- **Usage**:` line via compose_system_prompt's auto-fill.

Tests: tests/unit/test_ent1059_admission_policy_seam.py (18). Each seam
call, the SKIPPED write, the router mapping, the Workspace branch, the
notice fill and the fail-open re-raise were removed one at a time and a
named test went red each time. test_2638's pre-dispatch allowlist gains
`policy_denied` with its reason.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(subscriptions): usage-share refusal survives the task backlog drain (B)

A share that ran out while a sync /task waited in the backlog: the drain
closes the row SKIPPED, and a long-poll that reads the terminal back from
the row (another worker drained it, or the wait timed out) rebuilt a
success-shaped result from a SKIPPED row. It now answers the seam's own
refusal.

- execute_task's policy gate stores the row error as `[usage_share] text`
  (the #3114 pull-sink shape), so a reconstruct can tell a share stop
  from any other SKIPPED; the in-memory result keeps the plain message.
- _dispatch_sync_backlog's reconstruct branch rebuilds AdmissionRefused
  from a SKIPPED row carrying that code; _map_task_failure then releases
  the claim and the router answers 429 usage_share (no Retry-After: the
  row has no frees_at, the message says when).

Tests: test_ent1059_admission_policy_seam.py +2 (20). The reconstruct
removed -> the drain test red; the prefix removed -> the SKIPPED-row test
red; each restored from a copy.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(subscriptions): usage share card and breakdown column (C)

An agent's share of its subscription's usage, as its owner reads and
changes it. Both surfaces render only when the instance is entitled to
`usage_share`; an unentitled build calls nothing.

- Settings > Guardrails gains a "Usage share" section (UsageShareCard):
  the rolling 7-day and 5-hour windows as used / budget with a meter, the
  warning line drawn at warn_pct, Warning / Stopped badges in words, when a
  stopped window frees, whether a stop ask is pending, the line the agent
  reads on its next turn, and where each number comes from. The owner
  changes it inline through the PUT; an empty field is the platform
  default and all three empty clears the override. Bounds are named
  client-side before a request; a refused PUT keeps the form open with an
  InlineError. Applies from the next turn, no restart.
- Settings > Subscriptions per-agent breakdown gains "Share used (7d · 5h)":
  each agent's own percent, warning/danger tone from the share's own
  threshold; a share the reader cannot see renders a dash, never 0%.
- stores/agents.js: getUsageShare / setUsageShare (single API client).
  stores/subscriptions.js: fetchAgentShares, per-agent isolated.

Tests: src/frontend/tests/unit/usageShareCard.spec.js (22, mounted under
jsdom). Mutations each turned it red and were restored from a copy:
breakdown ungated (1 red), at_budget ignored (2), client validation
bypassed (5), Guardrails section ungated (1). Raw-colour ratchet: no
existing file grew; the new card carries 0 raw non-gray.

Refs abilityai/trinity-enterprise#1059

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(execution): every door answers an admission-policy refusal; a refused loop iteration is skipped, not failed (abilityai/trinity-enterprise#1059 fix)

Review C2, H1, the test_3274 sweep red and I5 on the pre-admission policy
seam.

C2: a turn an admission policy stopped inside `execute_task` is a SKIPPED
row `[usage_share] <sentence>`, and `_admission_policy_gate` returned it as
a result rather than raising — so every `dispatch_and_await_terminal` caller
that branched on failed/cancelled only answered success-shaped with an
empty reply. On the paid door that attached the execution to the claim,
logged verify-ok and SETTLED a charge for a turn that never ran.

- `chat_signals.admission_refusal_of(result, agent_name)` is the one rule:
  the in-memory attribute when the gate ran in this process, else a rebuild
  from the row's `skipped` + code shape. `result_from_execution_row`
  attaches it, so a turn refused on another worker (the backlog drain, a
  long-poll reading the row back) carries the same refusal; the separate
  rebuild in `_dispatch_sync_backlog` is that call now.
- One branch per door, before failed/cancelled: paid releases the claim and
  neither attaches nor settles (no charge; `payment.reason` is the
  sentence); MCP inline chat answers 429 with the sentence and
  `X-Trinity-Error-Code`; a channel sends the sentence and returns before
  step 12 so no empty assistant turn is persisted; the public link answers
  429 (sync) or stores the sentence as the reply (async); `portal_chat`
  reads status + code as well as the attribute; a room posts the policy's
  sentence and keeps its resume handle and cursor; A2A maps `skipped` to
  `rejected` with the message on the inline path as `_ROW_STATE` already
  did for the row; a refused validation turn is an ERROR verdict. The
  scheduler (`internal.py`), fan-out and operator-resume doors already
  record the skipped row with its message and need no branch; voice and
  the brain orb call `execute_task` directly and close SKIPPED.

H1: `loop_service._close_run` counted a policy-refused SKIPPED as a failed
run (only a gate-held SKIPPED was exempt), so `failed_runs` rose,
`on_failure` applied, and an at-budget loop kept ticking to `max_runs`. It
now reads the refusal off the row (`_split_error_code` + the predicate),
closes the run `skipped`, counts nothing, and stops the loop with the code
as `stop_reason`.

Sweep: `usage_notice` joins the platform-controlled list in
`test_3274_gate_context` — the line is composed by a policy from platform
numbers and never reads requester text. I5: `fetchAgentShares` runs at most
six reads in flight.

Docs: `requirements/security.md` §20.5d and `architecture/execution.md`
state the result-not-worker rule and each door's branch.

Red before the fix, with the door code reverted and the predicate kept:
all ten door tests in `test_ent1059_refusal_doors.py` (the paid one read
`settled`, the Workspace one DID NOT RAISE, A2A read `failed`) and both
loop variants beside the ent#751 hold test (`('failed', 'error')`);
restored byte-identical.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(completion-report): a refused turn's report shows the policy's sentence, not its [usage_share] code (abilityai/trinity-enterprise#1059 re-review N1)

An admission-policy refusal closes the row SKIPPED with `[usage_share] <sentence>`,
and the completion report (Workspace, Slack, Telegram) posted that text as-is.
The report now strips a known `[code]` prefix from a non-success terminal before
sanitising; an unknown `[...]` and any success text stay as the agent wrote them.
`_split_error_code` moves to the cycle-free `execution_envelope` leaf as
`split_error_code` so the report uses the same parser; the old names stay
importable from `task_execution_service`.

Also adds an executing spec for `fetchAgentShares`' six-lane cap (re-review N3):
a deferred `getUsageShare` over 15 names, high-water mark 6, every name written,
a failed read as `{ error: true }`. Mutation-checked: with the cap at 100 it
fails (expected 15 to be 6).

Red before the fix: test_the_workspace_report_shows_the_sentence_without_the_code,
test_the_channel_report_shows_the_sentence_without_the_code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agents): a dotted tag in github:owner/repo@ref pins the clone

The ref after `@` was checked against [A-Za-z0-9_-/] only, so a release tag
such as v1.2.0 failed the check and was dropped without a word: the agent was
created on main while the caller believed it pinned. The ref is now taken
whole when it is a valid branch or tag name (dots allowed, minus the git
ref-format shapes '..', a leading-dot component, a trailing '.' or '.lock'),
and an unusable ref is a named 400 instead of a silent fall-back to main.
The charset stays a shell-safety barrier for startup.sh's eval-built clone.

Red first: tests/unit/test_4165_github_ref_tag.py — the five dotted refs
returned url_branch=None and the ten unusable refs did not raise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(agents): purge_agent_now removes an agent at once, audit first (abilityai/trinity-enterprise#1055)

Agent delete is a soft delete (#834): rows, volumes and the MCP key stay for
the retention window. Removing an invited member's agent, or rolling back a
half-created one, must leave nothing but the audit trail, so the retention
sweep's hard purge becomes an immediate, edition-agnostic primitive with no
route of its own:

- the agent_lifecycle:purge audit row is written while the agent still
  exists and outlives it; if it cannot be written nothing is destroyed (503)
- a person caller must pass assert_admin (an agent key carrying an admin
  owner's role is refused); actor=None is the platform itself
- container, queued and in-flight work, Redis state, the #816 cascade
  (sharing, permissions both ways, MCP key) and the data volumes under both
  identities of a renamed agent (#1664) go; a base another agent claims
  stays; a Docker fault never stops the row purge
- system agents (403) and ephemeral agents (409) are refused; no row is a no-op

Red first: tests/unit/test_ent1055_purge_agent_now.py (module absent). Each
of five mutations turns it red: admin gate removed (2), fail-closed removed
(1), soft-delete-before-purge removed (7), base-claim guard removed (1),
audit moved after the container removal (2).

Docs: requirements/core-agent.md §1.4.1 and §4.2 ref pinning (trinity#4165);
architecture/agent-lifecycle.md pointer. Registry: both new test files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agents): a tag in github:owner/repo@ref survives the three ref-existence checks (trinity#4165, abilityai/trinity-enterprise#1055 review C1)

The parser accepted a dotted tag and stored it in `source_branch`, but every
check that consumed that value before the clone asked for a BRANCH of that
name: `provisioning.check_remote_branch_exists` ran `ls-remote --heads
refs/heads/<ref>`, `ref_probes._ref_arg` prefixed `refs/heads/`, and the
PAT path asked `GET /repos/{repo}/branches/{ref}`. So a tag passed the
parser and was refused with "Branch 'v1.2.0' not found" on every path; the
public doc claimed it pinned the clone.

Now all three accept a branch or a tag, the ref still a value after the URL
and never an option: the anonymous check asks for `refs/heads/<ref>
refs/tags/<ref>` with no `--heads`; the probes ask for both and take the
branch first (as `git clone -b` does), peeling an annotated tag to its
commit; the REST path answers a 404 on `/branches/{ref}` with
`/git/ref/tags/{ref}` before calling the ref missing. The refusal names
both: "Branch or tag '…' not found".

Red first: `tests/unit/test_4165_ref_existence_checks.py` drives the real
`check_remote_branch_exists`, `probe_anonymous_ref`,
`probe_tokened_repo_access` and `_validate_github_access` on all three
paths against a fake `ls-remote` that filters like git (so a check that
asks for heads only cannot see the tag) — 9 of 15 red before the change,
all green after. Three pins on the old branch-only contract moved with it
(`test_3725_*`: the argv now carries both refs and a same-named tag answers
when no branch does; `test_ent123_tokenless_clone`: the wording).

Docs: `requirements/core-agent.md` §4.2 names the three checks and the
precedence; the two flow rows that quoted `--heads` / the old wording
follow. Registry entry added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(agents): a ref in github:owner/repo@ref may not begin with '-' (trinity#4165, abilityai/trinity-enterprise#1055 review I5)

`_GITHUB_REF_RE` admitted `-foo`. Safe today — every live site passes the
ref as a value (`git clone -b <ref>` takes the next token whatever it
starts with; the probes prefix `refs/…`) — but `startup.sh` also runs
`git checkout "${SOURCE_BRANCH}"`, where a leading `-` IS parsed as an
option, benign only because the clone already checked the ref out. One
shell edit away from not. The regex gains `(?!-)`; the 400 names it.

Red first: `TestRefRefused[-foo]` — DID NOT RAISE. Upgrade-safe: the parser
has one caller (creation); no stored `source_branch` is re-parsed on boot,
pull or reset, so existing agents are untouched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(agents): an annotated tag in @ref resolves to its commit, not the tag object (trinity#4165)

`ref_probes` asked `ls-remote` for `refs/heads/<r>` and `refs/tags/<r>` and
took a peeled `refs/tags/<r>^{}` line when one was listed. git never listed
one: it shows a ref only when a pattern names it, and the peeled line's name
ends in `^{}`. So an annotated tag resolved to the TAG OBJECT, and the raw
template read was pinned to an id that is not the commit the clone checks
out. The probe now also asks for `refs/tags/<r>^{}` by name.

The unit fake listed `^{}` lines for a bare tag pattern, which is why the old
test passed. It now lists a ref only when a pattern names it, and a new file
runs the probes against a real bare repository over file:// (a lightweight
tag, an annotated tag, a branch and an annotated tag sharing a name).

Red first: test_4165_ref_probes_real_git.py — the annotated-tag and tokened
cases returned the tag object id; 4 others passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(agent-server): a tag-pinned agent's pull cycle is a named skip, not a failure every tick (trinity#4165)

`github:owner/repo@<tag>` clones with `git clone -b <tag>` in source mode,
which leaves the agent on a detached HEAD: pinned to that release, by design.
Pull sync is on for every `github:` agent, and `_run_pull_once` recorded
`failed: detached HEAD: nothing to pull onto` on every cycle, a failure
streak for an agent doing what it was asked to.

A detached HEAD now records `skipped` with the reason named. A detached HEAD
left by a rebase stopped part-way (its rebase-merge/rebase-apply directory
exists) stays `failed`, so a stuck tree still shows. The push cycle is
unchanged: it is off by default for a source-mode agent, and an owner who
turns it on for a pinned agent gets an honest failure.

Red first: test_4165_pull_cycle_pinned_tag.py::test_every_cycle_is_a_named_skip_not_a_failure
— 'failed' == 'skipped'. Real repos, the agent cloned -b v1.0.0 (annotated).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>

* fix(credentials): keep the credential read inside the agent home and make the paste guard linear (#4191)

* fix(agent-server): the credential read stays inside the agent home (trinity-enterprise#1066)

CodeQL flagged the `os.lstat` this branch added to `GET /api/credentials/read`
(path depends on a user-provided value). The finding is real at the guard,
not at any current caller:

- the guard (`lstrip("/").lstrip(".")`, a `".." in` test on the stripped
  string, `str(resolved).startswith(str(home))`) let a single leading `../`
  through, and its prefix compare had no separator, so `../home2/.env`
  READ a file in a sibling directory whose name extends the home's;
- the new `lstat` ran before any containment check, so `../<anything>`
  came back in `missing` — an existence probe one level above the home.

Not reachable before this fix through the platform: the route sits behind
the agent's per-agent auth middleware (#1159) and every backend caller sends
fixed relative paths (`.env`, `.mcp.json`, `.credentials.enc`) or the agent's
own `/list` output.

Fixed at the root with one helper, `_contained_read_target`: refuse absolute
paths and any `..` component, then require both the normalised lexical path
and the link-resolved path to sit under the home with a trailing separator.
`lstat` runs on the contained lexical path (the absence proof); the read goes
through the contained resolved path, so a link is followed only to a target
that is itself inside.

Red first: tests/unit/test_ent1066_credential_read_containment.py — 5 of 13
red at the previous guard (sibling read, `../` oracle, absolute path, link to
a sibling file, linked parent directory), all green with the fix; the fix
reverted from a scratch copy turns the same 5 red.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sanitizer): the paste guard's KEY=value walk is linear by construction (trinity-enterprise#1066)

CodeQL flagged the two regex calls in `secret_shape` (py/polynomial-redos,
"may run slow on many repetitions of '!'"). Origin: the patterns pre-exist
on dev — `_KV_LINE_RE` / `_KV_PAIR_RE` are the redaction's #1661/#3311 walk —
but these two alerts are introduced by this branch, which feeds them a
Workspace chat message (user-provided text) through the new guard.

Measured before the change, CPython was already linear on every shape tried
(`!`*n, `=`+`!`*n, `!`*n+`=`, `!=`*n, `k=!`*n, an unclosed quote, sensitive
keys with short values): 1M characters took 0.04-1.1 s, scaling ~10x per
10x. The lookbehind pins each key to the start of its run — the engine
detail CodeQL's model does not see (#1661 says the same). The route caps a
message at 100k characters.

The guard no longer rests on that detail. It finds each `=` with
`str.find`, walks back to the key start (never past the previous `=`, so
no character is visited twice), and checks the value with one fixed-width
match — an optional opening quote and eight non-space, non-quote
characters. No length cap, so nothing at the end of a long message is
dropped. One deliberate widening: the closing quote is no longer required,
because a truncated paste is still the secret. The redaction path is
unchanged.

Red first: tests/unit/test_ent1066_secret_guard_linear.py — red before the
change on the no-unbounded-regex pin and the unclosed-quote case (2 of 43);
the timing bound (1M < 3 s, 10x input < 30x time) and both-way detection
were green before and after. The change reverted from a scratch copy turns
the same 2 red. The 1661/2208/2398/3840 sanitizer suites and the paste-guard
suite stay green (608 passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* chore(enterprise): bump the submodule pointer to main (448cdbc -> f347a02) (#4193)

Picks up abilityai/trinity-enterprise#1072 (member_agents module, ent#1055),
which composes the purge_agent_now primitive from #4183.

Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* revert: an agent's share of a subscription (#4180) (#4199)

* Revert "feat(subscriptions): an agent's share of a subscription, enforced at every door (#4180)"

This reverts commit 9eedbbb6e0be8d5b73ccb5e8f0217a33a987b089.

* chore(enterprise): bump the gitlink to the ent#1070 revert (trinity-enterprise#1076)

Lands with the #4180 revert so dev never carries the usage_share module
without the admission_policy seam it imports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(sub-003): the agent's auth answer outranks a prompt-length mention, and the turn-limit anchor is pinned (#4123) (#4197)

* fix(workspace): keep a room's content inside the Inbox reading pane (#4160) (#4169)

Every agent bubble renders PortalMarkdown's sr-only live region, which is
position:absolute. The reading pane's scroll box was not positioned, so
those regions resolved against the page, escaped the overflow box, and a
long room stretched the document: the wheel scrolled the whole Workspace.
Make the scroll box `relative`, as the list column's already is.

Adds a mount spec pinning the containment structure for a long room, a
room with many messages, and a thread.

Fixes #4160

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(operator-queue): the listing engine moves to listing.py, and the poller core into PollerCoreMixin (#3785, PR 2 of 4) (#4037)

* fix(operator-queue): the #1677 helper delegates to the platform-alert seam

create_bounded_alert(_outcome) keep their signatures and outcome contract
and become a thin delegate of platform_alerts.observe, which already
composes the per-(agent, type) budget inside its one locked create. The
registered type names its kind; the key is read back from the item's id
and context by derive_legacy_subject and must resolve to that same kind,
else ALERT_FAILED_CREATE. The two kinds whose ids carry no subject
(gitignore, problem report) are keyed by the request id minus the kind's
prefix. observe's "updated" and "snoozed" pass through; "failed" maps to
ALERT_FAILED_CREATE; every refused or failed arm logs [#1677 budget].
ALERT_FAILED_COUNT stays importable and is no longer returned.

The budget episode reports through observe as kind alert_budget keyed by
the budgeted type: one alert_budget:<type> row per agent, re-read by a
later refusal outside the cooldown, ended by its 14-day lifetime. The
bucketed id and its own operator_queue_new broadcast are gone; observe
sends the thin operator_queue_sync trigger.

Ratchet: create_bounded_alert_outcome and _maybe_emit_alert_budget_episode
leave EMITTERS_NOT_YET_ON_SEAM; alert_budget gets a NO_CLEAR_SITE reason.
Census: both leave _ALLOWED_CALLERS (no direct create left in either).

#3254 re-pins (asserted outcomes unchanged):
- test_1677_operator_alert_budget: write-observation point. The harness
  stands in for the seam's create with the same budget arithmetic and
  runs what observe spawns. Id shape in
  test_deterministic_bucketed_id_with_reserved_prefix,
  test_cooldown_knob_zero_never_raises (the subject replaces the bucket)
  and test_under_cap_creates_item_and_notification (the seam's id). The
  episode raise now stays in its spawned task, so
  test_episode_helper_raise_swallowed_refusal_stands reads the delegate's
  WARNING marker; test_ws_broadcast_failure_swallowed checks the thin
  operator_queue_sync payload.
- test_3130_flood_guard, test_1632_operator_queue_caps: write-observation
  point. The flood alert still rides the delegate, so its writes, the
  typed budget read and the I1 fault injection move to the seam's create.
- test_3243_atomic_asks::test_a_cap_hold_never_fires_the_flood_alert:
  write-observation point. Watched at observe, since the oqs.db assertion
  alone would now pass whether or not the alert fired.

Known until the problem report moves in its own commit: nine
test_3521_problem_report_comment cases are red here. The delegate files
an event-kind row under the seam's id, which the old _attach_comment
(keyed on the pre-seam request id) cannot find.

New: tests/unit/test_3254_budgeted_alerts.py (registry parity, reach-back
imports, the delegate's outcome table over all five budgeted types, the
episode's seam properties, R1 for alert_budget).

Part of #3254

* fix(operator-queue): the flood alarm reports through the seam and ends with its episode

OperatorQueueSyncService._maybe_emit_flood_alert reports through
platform_alerts.observe as kind queue_flood keyed by the reason: one
pending row per (agent, reason), rewritten in place, budgeted by the
seam. #3130's outcome rule is kept on observe's strings: a failed write
releases the episode and is retried after the cooldown (I1); created,
updated, snoozed and refused consume it.

While an episode lasts it is re-read at most every 6 hours, so the kind's
14-day lifetime ends only a row nobody re-read, never a condition that
still holds. The refresh time per (agent, reason) is a dict the method
creates on the instance for itself; __init__ is unchanged. The flood's
own operator_queue_new broadcast (which carried the title) is gone;
observe sends the thin operator_queue_sync trigger.

The two _sync_agent statements where an episode ends
(_flood_episodes.discard for oversize_file and ingestion_cap) become
calls to the new _end_flood_episode, which ends the episode and, only
when one was running, ends its alert as the platform through
platform_alerts.clear. A cycle with no episode costs no read.

Ratchet: _maybe_emit_flood_alert leaves EMITTERS_NOT_YET_ON_SEAM;
queue_flood's clear site is _end_flood_episode.

No re-pin in this commit: the #3130 and #1632 harnesses were moved to
the seam's create in the previous commit and keep their results.

Tests: the flood through the real _sync_agent poll for 30 simulated days
with the real expiry sweep (one row, re-read every 6 hours, ended as the
platform when nothing is held), no read without an episode, two reasons
two subjects, I1 on the real seam, a person's ending standing through the
re-read and the clear, the thin trigger, R1 for queue_flood.

Part of #3254

* fix(execution): the effect guard and missing-skill alarms report through the seam

_on_unguarded_effect reports a refused effect through
platform_alerts.observe as kind effect_unguarded keyed
"<effect_type>:<reason>": one row per agent, effect and reason,
rewritten by each further refusal, ended by its lifetime (nothing
observes an agent starting to send ids). The send is refused whatever
the alarm's outcome.

_alert_skill_not_found reports through observe as kind skill_not_found
keyed by the truncated command: one row per agent and command, re-read by
each scheduled run. The paired notification is sent only on "created": a
repeat of a pending command is an "updated" reading and already had one;
refused, failed and snoozed wrote no new row. The pre-create dedup read
stays and now matches only a pending pre-#3246 row (no subject), which
keeps standing for its command until the upgrade sweep stamps it; a seam
row is re-read through observe, where a repeat is never refused at the
cap.

task_execution_service.py: only _alert_skill_not_found changes. Its
module-level utc_now_iso import is now unused and is left in place.

Ratchet: _on_unguarded_effect and _alert_skill_not_found leave
EMITTERS_NOT_YET_ON_SEAM; skill_not_found gets a NO_CLEAR_SITE reason
(only the dispatch path could see a command resolve, and there the
detector cannot tell "resolved" from "not a slash command").

#3254 re-pins (asserted outcomes unchanged):
- test_1677_operator_alert_emitters::
  test_skill_not_found_emitter_is_routed_not_allowlisted: the module must
  call platform_alerts.observe naming "skill_not_found" (AST), the seam
  that composes the budget, instead of mentioning create_bounded_alert.
- test_2392_effect_guard_fail_closed: write-observation point and id
  shape. The alarm is recorded at platform_alerts.observe instead of a
  sys.modules stub of operator_queue_service, which lacks the names the
  seam reaches back for. The id prefix is asserted on the kind; the
  at-budget case returns the seam's refused_at_budget.
- test_ent879_aauth_resource_route (the refused-call case): the dead
  create_bounded_alert patch moves to platform_alerts.observe.

Tests: the effect refusal's seam properties and lifetime; the missing
skill's one row per command, no notification on a repeat, a pre-seam row
still standing, no notification at the cap; R1 for both kinds; the other
shape, the clock 30 days ahead: a full skill_not_found budget frees
itself through the real expiry sweep and a new command files.

Part of #3254

* fix(git-sync): the gitignore sweep's alert is one row per change set

_emit_gitignore_untracked_alert reports through platform_alerts.observe
as kind gitignore_untracked, which stops being an event kind
(platform_alerts.py: event=True dropped). It is a must-act kind: no
lifetime, never ended by the platform.

It is keyed by the change itself: a 32-hex digest of the canonical,
direction-tagged set of paths the Push untracked and newly un-ignored
(sorted removed paths, the exact removed count, sorted un-ignored paths).
A repeat of the same set collapses onto one row; a different set, a
different total behind a capped list, or the same path in the other
direction is a different row. Keying per agent would let a later Push
overwrite an earlier Push's path list on a pending must-act alert, which
#2529 calls the surface that outlives the session. The legacy prefix
keeps its _no_subject parser, so pre-existing rows stay pending until a
person acts.

Ratchet: _emit_gitignore_untracked_alert leaves EMITTERS_NOT_YET_ON_SEAM.

#3254 re-pins (asserted outcomes unchanged):
- test_2529_gitignore_precedence: write-observation point and id shape.
  The alert is watched at platform_alerts.observe (the two
  create.await_count == 0 checks would otherwise have gone vacuous); the
  per-agent id prefix is asserted on the kind, with the 32-hex key.
- test_3246_platform_alerts_leaf::test_event_kind_has_no_subject:
  gitignore_untracked is a condition now, so it is asserted keyed and the
  problem report stays the event example.

Tests: a repeated set is one row that never expires; distinct sets and a
capped list with another total stay distinct; the direction tag holds;
a person's ending stands; the 30-day case now also shows the gitignore
row still pending.

Part of #3254

* fix(workspace): the problem report is one seam row per person, target and day

raise_problem_report reports through platform_alerts.observe as kind
workspace_problem_report, which stops being an event kind (event=True
dropped). It is keyed by the 32-hex digest _problem_report_id already
computes: one row per person per target per UTC day, the "never
duplicates" rule its docstring states. A person must act on it, so it
never expires and the platform never ends it. The workspace-problem- id
prefix is kept, so ent#866's owner-only rule and the machine-key "about a
person" exclusion still hold. It returns True when the row was created or
updated, False when snoozed, refused or failed.

#3521's words-only rule moves under the seam's lock. observe gains
keep_text (passed through database.create_platform_operator_queue_item to
create_platform_item and _touch): with keep_text and a pending row, the
reading only counts (last_seen_at, seen_count, expires_at) and the title,
question, priority and context stand. The bare click passes keep_text, a
reading with words does not. The click and the comment are two background
requests that meet on one row inside the per-agent lock, so either order
ends with the words. With no pending row the reading files as usual.

update_pending_problem_report (database.py, db/operator_queue.py) and the
nested _attach_comment are removed: one write path.

Ratchet: raise_problem_report leaves EMITTERS_NOT_YET_ON_SEAM, which
fixes the nine test_3521 cases the delegate commit left red.

#3254 re-pins (asserted outcomes unchanged):
- test_3521_problem_report_comment: the acknowledgement fixture goes
  through ask_service.answer (fixture shape; a raw status UPDATE carries no
  person ending for the snooze to read); the accessor test asserts the
  same type guard at the seam (a foreign row under the report's old id is
  never written); the lost-race test injects the bare click's whole
  reading, in its own thread, before the comment's locked create.
- test_ent499_problem_report: write-observation point. The fake moves from
  create_bounded_alert to platform_alerts.observe; the routing AST test
  asserts the call to observe.
- test_ent715_queue_person_fields: update_pending_problem_report leaves
  _NON_ROW_ACCESSORS (the accessor census forbids a stale entry).
- test_3246_platform_alerts_leaf::test_event_kind_has_no_subject: no
  built-in kind is an event any more, so the property is pinned on a kind
  registered for the test, and both former events are asserted keyed.
test_ent866_problem_report_owner_only is unchanged.

Tests: keep_text at the sink, both interleavings keeping the words, one
must-act row per person, target and day, the owner-only prefix, the
delegate and the emitter landing on one subject, a person's ending not
rewritten or reopened; the 30-day case now also shows the report still
pending; the five-type admission test asserts every kind keyed.

Part of #3254

* fix(operator-queue): decide a platform alert's snooze under the create's lock

observe checks the snooze before the create's lock. Two moments let a
person's ending slip past that check: an acknowledgement after observe
read the pending row but before the locked create (the locked find then
misses), and one between the locked find and _touch's compare-and-set
(the lock covers creates, not respond_to_item, so the CAS loses). Either
way the create fell through to an insert, and the alert a person had just
ended was back at once. Before this batch most of the moved writers had a
deterministic id that could not re-file after an ending, so the moves
would otherwise ship that regression.

create_platform_item gains snooze_since and a snoozed predicate. On the
insert path, after a missed find or a lost CAS and inside the same locked
transaction, it reads the newest person-ended row for the subject through
the transaction's own connection (the public lookup opens another one)
and returns {"outcome": "snoozed"} without inserting when the predicate
says so. observe passes the standard 7-day window, computed on its own
rather than from the pre-lock check's conditionally assigned cutoff, and
lambda ended: _snoozed_by(kind, ended, priority, context). The pre-lock
check stays as the fast path. A caller that passes neither keeps the old
behaviour.

The statement behind the public find_person_ended_by_subject becomes
_find_person_ended_by_subject(conn, ...), shared by both reads.

Tests: a person's acknowledgement through ask_service.answer, landed (a)
between observe's read and the locked create and (b) between the locked
find and the CAS, yields "snoozed" and no new row, for the problem
report, an inbox collision as registered on dev, and the flood alarm's
6-hourly re-read. All six cases were red before this commit (a fresh row
was created) and pass with it. On SQLite, BEGIN IMMEDIATE holds every
other writer, so moment (b) lands the ending first and hands both finds
the row as it stood just before it; two real workers are not exercised.

Review fixes carried here (the earlier commits are left as they are):
- OperatorQueueSyncService._maybe_emit_flood_alert: the cooldown is
  stamped before every reading, the 6-hourly re-read included. A failed
  re-read released the episode with the cooldown stamp still 6 hours
  old, so it was retried on the next 5-second cycle. New test: a failed
  re-read is retried no sooner than the cooldown (red before the fix).
- test_3521_problem_report_comment (the lost-race re-pin): asserts the
  bare click's own request returned True and left a pending, comment-free
  row before the comment's locked create ran, so the test cannot pass
  without the interleaving it claims.
- gitignore_sweep: states that past the probe's 2,000-line cap the key is
  the capped list plus the exact total (a full-set digest needs the
  in-container probe, outside this change).
- test_1677_operator_alert_emitters: the census's guidance for an
  agent-influenceable emitter now points at platform_alerts.observe, not
  the delegate the #3246 ratchet counts as off the seam.
- test_3254_budgeted_alerts: the frozen clock also covers
  db.operator_queue's ent#815 commit-lag check, which logged spurious
  errors against the real clock.

Part of #3254

* fix(operator-queue): a failed flood re-read keeps the episode, so its end still clears the alert

Fresh review of the #3254 budgeted slice (two findings):

- A failed 6-hourly re-read of a persisting flood released the episode.
  If the condition then cleared before the retry, `_end_flood_episode`
  found no episode and the pending alert waited out its 14-day lifetime,
  although the code had seen the condition clear (AC 2). A failed re-read
  now keeps the episode, whose alert an earlier reading filed, and the
  re-read is retried once the cooldown has passed. A failed first reading
  still releases the episode (#3130 I1). New test:
  test_a_failed_reread_keeps_the_episode_so_its_end_still_clears_the_alert
  (red with the old release branch put back).
- AC 8 for two kinds had no "a person's ending is never overwritten" test:
  `skill_not_found` (the next run is snoozed and sends no notification)
  and `alert_budget` (a later refusal re-reads the episode and the
  acknowledgement stands). Both added.

* test(operator-queue): the budgeted-alert suite freezes the clock its running methods read

In the full serial unit tier, test_1595_sync_health_signals evicts
`database` and every `db.*` module from sys.modules and restores only
some of them. Afterwards `database.db` and `ask_service.db` run on an
older `db.operator_queue` module than the one this suite's clock fixture
imports and patches, so the seam's create, the expiry sweep and the
answer's compare-and-set read the real clock: rows filed at the frozen
T0 read as long expired (five cases red, `AskConflict: expired`, a
second flood row). The fixture now also freezes `utc_now_iso` and
`datetime` in the globals of the live operations class (R6: patch what
the running method reads). Red before: test_1595 followed by this file,
7 failed; green after: 66 passed; the file alone: 55 passed.

* refactor(operator-queue): operator_queue_service becomes a package, content unchanged (#3785)

The 2,840-line module moves to services/operator_queue_service/__init__.py
byte for byte (100% similarity), the first step of the Invariant #1 split.
Every `from services.operator_queue_service import X` and
`from services import operator_queue_service` resolves as before.

Six path-keyed guards name the file by its path, so their key moves with it
(the PR #2487 precedent): _NOT_EMITTERS (test_3246), _ALLOWED_CALLERS
(test_1677), _ALLOWED (test_1920), _OQS (test_ent715), FLEET_LEVEL_ALLOWLIST
(test_ent467), and the source read in test_ent499. Only the key changes; the
rule, the reason text and every assertion are untouched.

Part of #3785

* test(operator-queue): pin the package's one-binding rules before the split (#3785)

tests/unit/test_3785_operator_queue_package.py pins what S2–S6 must keep
while they move code out of __init__, each property derived from the tree
so no later slice edits it: modules under 800 lines (__init__ exempt, with
a staleness check); the import surface src/backend and tests/ read still
resolves; no from-import between package modules; one top-level binding per
name; import-time reads defined first and the _MARKER_UNCHANGED default the
owner's object; a patch of a re-exported name lands where its readers read;
one logger identity; owner-exact qualified reads; no submodule named like a
package attribute; one rate_limiter; no method on two classes of the
composed service; external imports before the first submodule import,
and a failed first import, injected at that line, leaves no stale submodule.
The AST scans live in _oqs_package_scan.py (pure stdlib, never imports src).

The other shape, a fresh install: each consumer imported first in its own
interpreter on an empty database raises a bounded alert (created; only main
binds a WebSocket manager, and then exactly one thin operator_queue_sync
trigger goes out). Outcomes equal on the base.

Part of #3785

* refactor(operator-queue): bind the service's collaborators once, in deps.py (#3785)

db, _queue_db, principal_reach, get_breaker_redis, ask_service, AgentClient
and the audit sink _audit_sync move to services/operator_queue_service/deps.py,
bound once and read as deps.X everywhere in the package. They are no longer
attributes of the package, so a stale monkeypatch.setattr(oqs, "db", ...)
raises AttributeError instead of patching a copy nothing reads (Invariant
#1(a), the PR #2487 rule). rate_limiter stays on the package: ask_service
reads oqs.rate_limiter.check.

Tests that patched a collaborator on the package now patch oqs.deps.X; no
assertion, expected value, fixture or control flow changes. The package guard
gains G4 (deps binds exactly the collaborators, no other module imports one
from its source under any alias or holds one by identity, the package has
none) and refuses any reach of a package function's __globals__.

Part of #3785

* refactor(operator-queue): the queue listing engine moves to listing.py (#3785)

QueueListError, narrow_to_agent_key, the cursor and walk-snapshot helpers and
list_for_principal (trinity-enterprise#815) move whole from __init__ to
services/operator_queue_service/listing.py. The two package-owned prefix
tuples are read as _oq.X, collaborators as deps.X. The package re-exports
exactly the six names read from outside (the router's list_for_principal and
QueueListError; narrow_to_agent_key, encode_cursor, decode_cursor and
CURSOR_MAX_BYTES, which tests call or compare).

test_ent715's row-reader census re-keys list_for_principal to listing.py; no
assertion changes.

Part of #3785

* refactor(operator-queue): the poller core moves into PollerCoreMixin (#3785)

The instance state, start/stop, the Redis leader lease, _poll_loop,
_poll_cycle and _broadcast_sync move into PollerCoreMixin in
services/operator_queue_service/poller.py. OperatorQueueSyncService is now
composed in __init__ from the mixin and keeps its singleton there (the
db/schedules shape). Package-owned names (DEFAULT_POLL_INTERVAL, _LEADER_KEY,
_RESERVED_ID_PREFIXES, _websocket_manager) are read as _oq.X; the default
poll_interval still binds 5 at import.

Three path-keyed censuses re-key their poller entries to poller.py
(test_1920's lease, test_ent467's operator_queue_sync trigger, test_ent715's
_poll_cycle); no assertion changes.

Part of #3785

* fix(operator-queue): a new flood, budget or untracking episode files after an acknowledgement (#3254)

A person's ending of a `queue_flood`, `alert_budget` or `gitignore_untracked`
row snoozed every later reading of the subject for 7 days, because none of
the three kinds had a material key, so `_snoozed_by` was vacuously true. A
runaway agent's second flood, a second budget-full episode and a second
untracking Push of the same paths were all silent (review C1; dolho on
operator_queue_service.py:2800 and gitignore_sweep.py:335).

Each reading now carries an episode marker that the kind lists in its
`material_keys`:
- queue_flood: `episode_started_at`, stamped when the in-memory episode
  starts. Re-reads of one episode share it; an episode that starts after the
  condition cleared does not.
- alert_budget: `filled_by`, a digest of the ids of the pending rows filling
  the budget. Re-reads of the same full budget share it; once a slot frees
  and a new row fills it, it differs.
- gitignore_untracked: `push_id`, one per call. The emitter runs once per
  Push, so every untracking Push after an acknowledgement files; repeats
  still collapse onto a pending row.

So the snooze silences re-reads of the acknowledged episode for the snooze
window and a new episode files at once, which makes the
`_maybe_emit_flood_alert` docstring's #3130 edge-trigger claim true again.
The budget episode's read of the filling rows is classified in the ent#780
row-reader census as internal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* fix(operator-queue): a flood re-read no longer stamps the per-agent cooldown; the oversize end is pinned (#3254)

Review follow-ups on the flood alarm:
- dolho on operator_queue_service.py:2778 (webmixgamer agreed): the 6-hourly
  re-read of one reason's episode stamped the per-agent
  `_flood_alert_cooldown`, so the other reason's first alert could wait up to
  one cooldown. The cooldown spaces episodes and a re-read is not one, so it
  is now stamped only before an episode's first reading. A failed re-read's
  retry spacing already comes from its refresh time.
- webmixgamer I3: the 6-hour re-read spacing is one constant,
  `OPERATOR_QUEUE_FLOOD_REREAD_SECONDS`, read by the gate and by the failed
  re-read's retry arithmetic, so the two cannot drift.
- webmixgamer I1: a `_sync_loop` case serves an oversized file and then a
  sane one and asserts the row ends as the platform. It goes red when
  `_sync_agent`'s `_end_flood_episode(agent_name, "oversize_file")` is
  replaced by a bare episode discard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* docs(operator-queue): state the fail-open double-leader bound on the flood episode marker (#3254)

The episode marker is worker-local. With Redis down the leader lease fails
open, so each worker stamps its own episode_started_at and another worker's
re-read can file past a person's ending, at most one extra row per extra
worker per re-read window. Docstring only; no behaviour change (review L1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* lint(operator-queue): __init__ drops its file-level F401 waiver (#3785)

Review I1 (dolho): the file-level `# ruff: noqa: F401` switched off
unused-import detection for all of `__init__`, so a dead import left behind
by a later slice or feature would go unflagged. At this PR's head
`__init__` still reads every name in its import block, so the waiver hid
nothing: `ruff check --select F401` gives 0 findings with it removed. It is
dropped, and the block's comment now says that a name `__init__` stops
reading keeps its line with a per-line waiver naming why (G13, or read as
`oqs.X` from outside). PR2, PR3 and PR4 add those per-line waivers where
their moves leave a name unread.

`deps.py` keeps its file-level waiver: it is a binding module whose
imports are its bindings, so there is no import there F401 could rightly
flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* lint(operator-queue): per-line F401 waivers for what __init__ stops reading (#3785)

Review I1 on #4036: PR1 dropped `__init__`'s file-level F401 waiver. This
slice's moves leave four of its imports unread in `__init__`; each now
carries its own `noqa: F401` with the reason, so F401 keeps checking every
other line:
- `asyncio`, `base64`, `uuid`: kept for G13, because `listing` and `poller`
  import them at module level.
- `from . import listing`: loads the submodule at its G6 point; the names
  callers read come from the re-export block.

`ruff check --select F services/operator_queue_service/` is clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(frontend): useVoiceSession goes through the single API client (#2720) (#4185)

The last bare axios call in the composable, voice stop, built its own auth
header. It now uses the shared client, so it follows the interceptor's
token and 401 handling (Invariant #7). The WebSocket URL still takes the
store token, which is a different path.

Closes #2720

Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* test(memory): stub last_error in the remaining memory_on fixtures (#4187)

The memory_on fixtures in test_ent1022_retrieval_memory and
test_ent1027_model_gateway stubbed is_loaded and availability but not
last_error, so an embedder error left by an earlier test on the same
worker made status() report memory unavailable. The 1028 fixture got
the same stub in #4145.

Fixes #4137

* docs(readme): link the Trinity 1.0 complete course (#4063)

* docs(readme): link the Trinity 1.0 complete course

Add the 39-chapter complete course video as the first entry under
"Watch more" so new visitors find the end-to-end walkthrough first.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(readme): update Complete Course link to new YouTube id and chapter count

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(readme): update Complete Course YouTube link to re-published video

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(metrics): code-health dashboard 2026-11-03 @ 93658be60 (#4198)

Co-authored-by: Trinity Agent (trinity) <trinity-agent@ability.ai>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>

* feat(auth): terms acceptance gate and invite door (trinity-enterprise#1054) (#4195)

OSS half of trinity-enterprise#1054: the terms-gate seam (services/terms_gate.py, consulted in resolve_platform_user_unfloored; @terms_route exemptions), EmailService.send_html on one HTML shell, the /terms SPA view + interceptor, and the entitlement-gated InvitesPanel.

Refs abilityai/trinity-enterprise#1054

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(workspace): a Direct call — every spoken turn goes to the agent and you hear its own reply (trinity-enterprise#1046) (#4194)

* feat(workspace): a Direct call, where every spoken turn goes to the agent and you hear its own reply (trinity-enterprise#1046)

A second call mode beside Live, chosen from the Call control's menu (remembered per
browser; Live stays the default). No model sits in the conversation: the browser
endpoints an utterance, the backend transcribes it, and the browser sends the text
through the same POST .../chat/stream a typed message uses, carrying the call's vd_ id.
The bridge then speaks the agent's reply sentence by sentence.

- Harness-agnostic: every reply is spoken from the persisted row; a runtime whose
  stream carries messages (Claude Code, Codex) only starts sooner, and the unspoken
  tail is reconciled so nothing repeats. Gemini CLI agents work, with a line saying
  replies take about 10 s.
- Agent approvals by voice: an ask the turn raises is read aloud, and a whole-utterance
  yes/no after the prompt has played is posted by the browser on the person's own
  answer route. The socket never answers an ask and never starts a turn.
- Gates: socket owner only (no admin attach); a turn may carry only the caller's own
  live Direct call on this agent and thread (uniform 404); a spoken run must be the
  caller's own execution, including one reached through an approval; one call per
  thread, claimed atomically when the socket opens; a vd_ id never bypasses the Live
  call guard; 30 utterances/min per person.
- Speech providers behind services/speech (Gemini REST STT/TTS, ElevenLabs), chosen in
  Settings (GET/PUT /api/settings/direct-voice, admin, audit-logged).
- The #2694 delta cursor treats a Direct reply as the agent's own session answering.

Measured end to end with real speech: first spoken word 3.4-4.4 s after send on Claude
Code, 10.7-12.0 s on Gemini CLI; STT 1.1-1.9 s.

The speech providers and the bridge were written before their tests. Every gate was
then mutation-checked: 16 backend gates go red when removed, run with bytecode caching
off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(workspace): two call buttons, and the Live orb in the Direct call's strip (trinity-enterprise#1046)

Operator review of the first build:

- The Call control's mode menu is gone. The composer has two buttons, one per
  call: the Live call (waveform) and the Direct call (handset). Each carries its
  own reason when it is off; while one call is on, its button ends it and the
  other says "Another call is on". Nothing is remembered per browser any more
  (`CALL_MODE_KEY`, `loadCallMode`, `saveCallMode` and `CallModeMenu.vue` are
  removed; `callButtons` is the pure rule).
- The Direct strip's flat pulsing disc is replaced by the Live call's orb in a
  48px disc. The overlay's smoke and core move into `chat/voiceOrbField.js`
  (one renderer, an instance per orb, no module state) and `VoiceOverlay.vue`
  draws through it unchanged. `chat/VoiceOrb.vue` draws the same field clipped
  to a circle on the orb's black ground, so it reads in both themes: 80
  particles, a DPR-capped bitmap, the first frame drawn on mount, one still
  frame under reduced motion, and the core tinted with the state — green
  listening, amber working, blue speaking — because at this size the smoke is
  a rim and cannot carry it. `directOrbState` maps the Direct statuses onto the
  orb's vocabulary.
- While the person talks, the orb moves with their voice: the composable feeds
  the mic RMS into `amplitude` whenever nothing is playing (`rmsOf` is exported
  from the endpointer).

PortalConversation's raw_gray count stays at its baseline: the two buttons
share one class recipe (#2662 arms) instead of repeating it.

Tests: `portalDirectCall.spec.js` covers the button rule, the status→orb map and
the mounted orb (draws, animates, stops on unmount, still under reduced motion);
`portalDirectCall.mount.spec.js` drives both buttons in the real conversation.
Verified in the browser on the local stack, light and dark, Live and Direct.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(workspace): the Direct call's strip shows four call bars, not a canvas orb (trinity-enterprise#1046)

The strip's mark is now `portal/CallBars.vue`: four rounded bars in a disc
tinted with the status tokens, sitting on the theme's own surface. Green bars
follow the person's mic while it listens, amber bars run a slow wave while the
turn is worked on, blue bars follow the agent's voice while it speaks, and
muted is four flat gray dots. Four elements and no canvas; under
prefers-reduced-motion it holds one still frame per state.

The canvas orb and the field extracted to share with it are gone, so the Live
call's VoiceOverlay.vue is back to dev's version and this PR no longer touches
it.

Tests mount the bars. Each of three mutations turns a test red: ignoring the
sound, ignoring mute, and starting the loop under reduced motion.
`portalUndefinedCalls` now lists `cancelAnimationFrame` as a browser global,
next to `requestAnimationFrame`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(workspace): a Direct call answers a reply it cannot read aloud, and its strip is one quiet row (trinity-enterprise#1046)

A reply that is only code, a table or links had no speakable sentence, so the
call said nothing and looked dead. test-echo's fenced echo hit this on every
turn. A successful reply with nothing to read aloud now gets "The reply is in
the chat." (LINE_REPLY_IN_CHAT); a reply with any spoken sentence does not.

The strip is now one fixed-height row, so the thread below it no longer moves
when the state changes: 32px bars, one short word (Listening, Got it,
Thinking, Speaking, Yes or no?), one detail line (a notice, what was heard,
the tool at work, or the slow-runtime wait), a mic icon that shows a slash
when muted, and a red hang-up handset. The "Direct call · runtime · speech
by …" line and the first-word timing are gone; Esc moves to the hang-up's
tooltip.

Tests written red first: two backend (the in-chat line, and no line when
something was spoken) and four frontend (the detail order, short words, and
the mounted row with icon buttons and a danger-token hang-up).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(workspace): a Direct call reads a reply that is only a code block, instead of pointing at the chat (trinity-enterprise#1046)

test-echo answers with nothing but a fenced block. The previous fix spoke
"The reply is in the chat." for it, which is no answer. When a reply has no
prose outside its code blocks, the text inside the blocks is the reply and is
now read (fence markers and the language tag dropped). Code beside prose
stays unsaid. The in-chat line remains only for a reply with nothing to read
at all, such as a table alone. The rule lives in spoken_text.speakable, so the
streamed speech and the reconciled tail agree and nothing is said twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Revert "fix(workspace): a Direct call reads a reply that is only a code block, instead of pointing at the chat (trinity-enterprise#1046)"

This reverts commit c214c9e4d. Operator ruling: a reply that is only a code
block is correctly answered with "The reply is in the chat." Code is not read
aloud, whether or not prose sits beside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(voice): a Direct call speaks an execution once (trinity-enterprise#1046)

Each speak frame built a fresh SpokenBudget, and only utterances were
rate-limited, so re-sending speak for the same run bought its synthesis
again, up to the call's 30 minutes and across calls. The bridge now claims
an execution before speaking it: Redis SET NX across calls and workers,
plus a per-socket set that holds when Redis cannot answer.

Also pins the store<->backend contract of a Direct call (mode on start,
voice_call_id on a spoken turn, the roster's direct_voice), each of which
could be deleted with every test green.

merge-train 2026-11-02, mechanical per operator ruling at Gate 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(voice): stub the Live capability in the one-call-per-thread test (trinity-enterprise#1046)

The live case reached realtime_voice_capability before the cross-kind 409
and got a 503 on a host with no realtime provider key (CI). merge-train.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: trinity-ability <309458136+trinity-ability@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* chore(enterprise): bump submodule — invite door and terms acceptance (trinity-enterprise#1054) (#4200)

src/backend/enterprise 47cb75a → 452ea04 (abilityai/trinity-enterprise#1074).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(auth): a grant's use leaves an audit row, and grant changes share one verb (abilityai/trinity-enterprise#871) (#4174)

An agent key a grant admits now writes one `capability_used` audit row: the
agent as actor, its key id, the capability, the target, the method and the
endpoint. It is written inside `enforce_agent_capability`, after the owner
bound, so it means the grant cleared the call, not that the change landed, and
a refused call writes only `capability_refused` (a holder aiming outside its
owner's agents included, code `capability_target_not_owned`, same 404). People,
`user` and `system` keys write none. One row per capability and target per
request; manifest deploys and an honoured skill-set probe record their own use.

`skills.manage` grant changes log `capability_grant` / `capability_revoke`
through every door; earlier rows keep `skill_manager_*`.

Security fixes found by `/cso --diff` and review
(docs/security-reports/cso-diff-2026-11-02-871-capability-used.md):
- `owner_owns_agent` now refuses the system agent. Owned by the admin, it was
  reachable by any holder an admin owns, and what lands there runs under a key
  that bypasses every permission check.
- The file routes apply the owner bound, so an edge to another user's agent no
  longer lets a holder write its instructions or skills (now 404).
- The skill-gate map read uses the same bound.
- The create row names the slug the agent would get, not the raw body.

Also: `request_id` on the agent `delete` row; `test_ent1030_gates.py` no longer
reaches the host's Docker. Out of scope: issue item 3 (outcome rows for schedule
writes and the timeout PUT); `trinity_prompt` via create-mode deploy stays #4025.

Fixes abilityai/trinity-enterprise#871

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(autonomy): declare get_seat_autonomy in the self-gate census; count get_autonomy in the MCP docs (ent#641)

Fallout from merging dev:
- test_ent719_self_gate_identity drives every assert_own_agent route with a
  well-formed request. The new GET /seat-autonomy needs an execution_id query
  parameter, like its seat-decision siblings.
- tool-count-docs (ent#991 T5) reads the registered total from the user docs.
  dev's search_memory plus this PR's get_autonomy make 177 tools (172
  operator), and decisions.ts now has 3 tools.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(gemini): dev's wall-clock and usage-statistics tests run as the owner's turn (ent#926)

test_ent1003_gemini_wall_clock and test_ent986_gemini_usage_statistics came in
with the dev merge and drive the Gemini runtime with an execution id. This
branch's tier check asks the platform whose turn it is, and with no platform
to ask it fails closed (503). These tests are about the CLI, not the turn, so
they take the same owner-turn stub the branch's other Gemini tests use
(turn_scope.fetch_turn).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(skills): find a skill and see what Save would do, on bounded lists (abilityai/trinity-enterprise#660) (#4178)

- Assign skills dialog: text, source and category filters narrow the rows
  and both bulk buttons, never the draft. Each row and a footer count say
  what Save would do: "to add", "to remove", or "kept by set" for a skill an
  assigned set still holds. The list keeps one height while the filter
  narrows, in a panel capped to the window.
- Library and the agent's Skills tab: the lists scroll in a BoundedRegion
  that fills the window, so the page no longer grows with the library. The
  Library gets the same filters and a stated total. On the tab, Own and
  Shared share one box, a total sits in the header, and Shared's heading
  docks to the box from 640 px up.
- BoundedRegion is now `relative`: unpositioned, the cards' sr-only labels
  escaped the box and Chrome counted them in the page height.
- Backend: `category` on SkillInfo, from the skill's frontmatter. No
  migration, no new route, no base-image or MCP change.
- e2e/skills-bounded-lists.spec.js (Chromium, @smoke, hermetic) pins the
  geometry that jsdom and Firefox cannot see.

ent#660 was re-scoped because its text predates ent#754. Edition:
OSS-core, ungated (confirmed on ent#660).

Fixes abilityai/trinity-enterprise#660
Fixes #3448

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(access): declare get_seat_autonomy's tier in the agent route census (#4206)

#2984 added GET /api/agents/{agent_name}/seat-autonomy and #3778 added the
census that requires every agent-naming route to declare a tier. They merged
one after the other without seeing each other, so dev fails
test_ent926_agent_route_census::test_every_agent_route_is_declared.

Declared accessor, with a reason, matching its sibling decision routes'
gates (assert_own_agent, then assert_agent_access).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix(slack): fall back to Public URL for OAuth callback redirect (#4167)

Motivation: with FRONTEND_URL empty (the .env.example default), the Slack
OAuth callback redirect fell straight to http://localhost, so after
Install to Workspace the admin landed on a dead page even though the install
succeeded. The redirect URI for the same flow is already built from the
Public URL setting.

Approach: get_oauth_callback_redirect now uses FRONTEND_URL if set (unchanged
precedence), else the Public URL setting, and only then the localhost
fallback with the existing error log. This covers the platform and per-agent
success and error redirects, since they share the function.

Validation: ran tests/unit/test_slack_*.py plus the new
tests/unit/test_3563_slack_oauth_redirect_base.py: 227 passed. With the fix
reverted, te…
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