Skip to content

feat(canvas): delete, pin, search and a stated bound for the canvas pile (ent#553) - #2619

Merged
vybe merged 15 commits into
devfrom
feature/553-canvas-lifecycle
Sep 14, 2026
Merged

vybe merged 15 commits into
devfrom
feature/553-canvas-lifecycle

Conversation

@dolho

@dolho dolho commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes abilityai/trinity-enterprise#553 — canvases can now be removed, pinned, and are bounded.

An agent that uses its canvas the way ent#438 intends accumulates dozens: one per report, per topic, per run. The Workspace could only ever add to that pile — no delete on the client-portal surface at all, one ordering, and nothing bounding the table.

The two decisions

Both were open questions in the issue, answered by operator ruling and recorded here because each had a plausible alternative.

Deleting is owner-or-admin — the answer ent#548 gives for files. This narrows the platform DELETE route, which previously accepted any user with agent access; safe because no UI called it, so no workflow depended on the wider gate. A canvas is one shared surface with no per-user copy, so a non-owner has no "hide it from my list" middle ground: per AC #2 they see no control at all rather than one that 403s. Agents keep clearing their own (clear_canvas, the #918 self-gate).

The bound is a per-agent cap, not a retention window. ent#438 recorded "no retention window" because the composite key bounds rows per canvas — but canvas_id is agent-chosen, so the count was unbounded. The axis was missed, not decided, and this PR corrects that note. CANVAS_MAX_PER_AGENT (100, env-tunable) is checked inside upsert_canvas's insert branch, in the same transaction as the INSERT, so it is not a check-then-act race.

Two properties make the cap safe to ship:

One ownership predicate, one capability channel

Both surfaces resolve permission through db.can_user_share_agent — the same predicate dependencies.assert_agent_owner uses — rather than a faster per-row comparison that would merely agree today. Agent Detail and the Workspace must never disagree about who owns an agent.

The Workspace learns it from PortalAgentCard.can_manage_canvases, the portal's only capability channel (#2128), since a portal principal cannot read /api/settings/feature-flags. It fails closed, so an external client — and any card predating the field — gets a read-only panel.

Pinning

pinned (dual-track: agent_canvases_pinned + Alembic 0058, NOT NULL DEFAULT 0, no backfill) is written only by the human pin route and is deliberately absent from every agent-facing tool — pinned by a test. audience is the agent's decision about who may read; pinned is the reader's about what they see first, and an agent that could pin itself to the top would defeat the ordering. A pin survives the agent rewriting the canvas.

Living with many

CanvasPanel.vue, shared by Agent Detail and the Workspace rail (one rendering layer, per ent#475): search over title and id once the list passes six, a height-bounded scrolling strip so a long list does not cost the rail its other tabs, and a Manage mode giving each row its age, stale mark, pin toggle and delete, plus a bulk bar with a single count-naming confirmation.

Decidable rules are pure in canvasUtils.js (sortCanvases, filterCanvases, selectionState, bulkDeletePrompt, bulkDeleteOutcome, canvasHeadroom) — vitest runs environment: 'node' with no mount harness, so a rule inside the SFC is one no test can reach.

Bulk delete is a POST rather than a body-carrying DELETE (bodies on DELETE are permitted-but-unreliable and this one is not optional), declared above the parameterized routes on both routers (Invariant #4), and it reports the ids that existed rather than those requested, so "3 of 5 removed" is sayable.

Verification

Verified against a real database, not just unit stubs: the cap refuses the 4th of 3 with a named message, updates still succeed at the cap, a pin outranks recency and survives a rewrite, and bulk delete returns only ids that existed (ghost excluded).

  • 23 new backend tests + ~24 vitest cases
  • Canvas / portal / voice suites: 794 passed
  • Full frontend suite: 2319 passed (103 files)
  • Full backend suite: running; result posted below
  • Design system: raw-color delta on the changed SFC is nongray 0 → 0, hardcoded 0 → 0 (semantic status-* / action-* tokens throughout)

Three pre-existing guards failed and each was right to. empty_canvas was missing the new field — a real bug in this change, fixed; the self-gate guard needed to learn the new gate's name; and the positional-read guard needed its synthetic row extended, which is precisely why that guard exists (_row_to_summary reads by index).

Recorded, not fixed

canvas_service.empty_canvas returns None timestamps while models.Canvas requires strings, so Canvas(**empty_canvas(...)) raises. Latent, not live — its only caller (routers/voice.py::get_voice_panel) declares no response_model, so FastAPI returns the dict unvalidated. Noting it because adding a response_model=Canvas there would turn the voice teardown-window poll into a 500. Left as a comment where the next person to reach for it will meet it, rather than fixed out of scope.

Fixes abilityai/trinity-enterprise#553

🤖 Generated with Claude Code

https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

dolho and others added 2 commits September 8, 2026 15:21
An agent that uses its canvas the way ent#438 intends accumulates dozens: one
per report, per topic, per run. The Workspace could only ever ADD to that pile
— the client-portal surface had no delete at all, the only ordering was "newest
updated", and nothing bounded the table.

Two decisions, both by operator ruling 2026-09-08, recorded because each had a
plausible alternative:

**Deleting is owner-or-admin.** The answer ent#548 gives for files — the owner
deletes the shared artifact. This NARROWS the platform DELETE route, which
accepted any user with agent access; safe because no UI called it, so no
workflow depended on the wider gate. A canvas is one shared surface with no
per-user copy, so a non-owner has no "hide it from my list" middle ground: per
AC #2 they see no control at all rather than one that 403s. Agents keep
clearing their own (`clear_canvas`, the #918 self-gate).

**The bound is a per-agent CAP, not a retention window.** ent#438 recorded "no
retention window" because the composite key bounds rows per canvas — but
`canvas_id` is agent-chosen, so the COUNT was unbounded; the axis was missed,
not decided. `CANVAS_MAX_PER_AGENT` (100, env-tunable) is checked inside
`upsert_canvas`'s insert branch, in the same transaction as the INSERT, so it
is not a check-then-act race. Updating an existing canvas is NEVER refused — a
cap that froze updates would punish exactly the agent that reuses ids — and the
refusal is a named 409 telling the agent to retire one, never an eviction:
deleting a person's surfaces on a timer is the #1638 failure direction.

Both surfaces resolve permission through `db.can_user_share_agent`, the same
predicate `assert_agent_owner` uses, so Agent Detail and the Workspace cannot
disagree about who owns an agent. The Workspace learns it from
`PortalAgentCard.can_manage_canvases` — the portal's only capability channel
(#2128), since a portal principal cannot read `/api/settings/feature-flags` —
and it fails closed.

`pinned` (dual-track: `agent_canvases_pinned` + Alembic 0058, NOT NULL DEFAULT
0, no backfill) is written only by the human pin route and is deliberately
absent from every agent-facing tool: `audience` is the agent's decision about
who may read, `pinned` is the reader's about what they see first, and an agent
that could pin itself to the top would defeat the ordering. A pin survives the
agent rewriting the canvas.

Living with many is `CanvasPanel.vue`, shared by both surfaces (one rendering
layer, per ent#475): search once the list passes six, a height-bounded strip so
a long list does not cost the rail its other tabs, and a Manage mode giving
each row its age, stale mark, pin and delete. Decidable rules are pure in
`canvasUtils.js` — vitest runs `environment: 'node'` with no mount harness, so
a rule inside the SFC is one no test can reach.

Bulk delete is a POST, not a body-carrying DELETE (bodies on DELETE are
permitted-but-unreliable and this one is not optional), declared above the
parameterized routes on both routers (Invariant #4), and it reports the ids
that EXISTED rather than the ids requested so "3 of 5 removed" is sayable.

Three pre-existing guards failed and each was right to: `empty_canvas` was
missing the new field (a real bug in this change, fixed), the self-gate guard
needed to learn the new gate's name, and the positional-read guard needed its
synthetic row extended — that one exists precisely because `_row_to_summary`
reads by index.

Tests: 20 new backend cases (cap refusal + update-at-cap, pin ordering and
survival, bulk scoping, the permission matrix on both surfaces, route ordering,
dual-track migration parity, and that the MCP tools cannot pin) and ~24 vitest
cases for the pure rules. Verified against a real database: the cap refuses the
4th of 3, updates still succeed at the cap, a pin outranks recency and survives
a rewrite, and bulk delete returns only the ids that existed.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ
…ment the lifecycle

Closes the three acceptance criteria the first commit left open:

* AC #1 asked for the deletion to be audited and only the BULK route was —
  the single-canvas route is the one a person actually clicks. Logged only
  when something was removed, since the route is idempotent and a repeat
  click would otherwise fill the trail with events where nothing happened.
* AC #8: deleting the DEFAULT canvas is allowed, comes back empty on the
  next write, and frees a slot against the cap. `main` is the id both the
  MCP tools and the voice panel fall back to, so it is the one most likely
  to be deleted by accident and the one whose deletion must strand nobody.
* AC #9: the user doc gains a "Removing canvases" section stating the
  permission rule, the cap, and that nothing is ever deleted to make room.

Also records a latent pre-existing mismatch found while testing:
`empty_canvas` returns None timestamps while `models.Canvas` requires
strings, so `Canvas(**empty_canvas(...))` raises. Not live — its only
caller declares no `response_model` — but adding one there would turn the
voice teardown poll into a 500. Left as a comment where the next person to
reach for that will meet it, rather than fixed out of scope.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ
…he test imports it

Two ent#553 tests passed in isolation and failed in a full-suite run:
`test_the_cap_refuses_a_new_canvas_by_name` and
`test_deleting_the_default_canvas_frees_a_slot_against_the_cap`.

Order-dependence, not a defect in the feature. They patched
`db.canvas.CANVAS_MAX_PER_AGENT` via a fresh `import db.canvas`. Some earlier
test in the suite evicts that module from `sys.modules`, so the fresh import
hands back a NEW module object while the live `db._canvas_ops` is still an
instance of the OLD class — whose `upsert_canvas` reads the OLD module's
globals. The patch lands somewhere nothing consults, the cap stays at its
default of 100, and the "refuses the 4th of 3" assertions fail.

`_set_cap` patches the bound method's own `__globals__`, which is whichever
module dict the running code actually closes over — correct whether or not an
eviction happened, so it does not depend on knowing which test pollutes.

Same failure and same fix as #2589, where the identical shape bit
`mark_stale_activities_failed`. Worth noting the class: a monkeypatch on a
module attribute is only as good as the assumption that the live object came
from that module object, and in a suite that evicts modules that assumption is
not free.

The feature is unchanged — this touches only the test file.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ
@vybe

vybe commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

merge-train: ejected — two reasons. (1) Real code conflict with #2603 in routers/canvas.py, services/canvas_service.py and models.py; #2603 has to land first (it needs a fix of its own, see its thread), then re-merge dev here. (2) 0058_agent_canvases_pinned shares down_revision = 0057 with #2608's 0058_portal_file_dismissals — the #2068 two-heads fork. #2608 is on this train; re-parent this revision to 0058_portal_file_dismissals after it lands. Also from /validate-pr: CANVAS_MAX_PER_AGENT is advertised as env-tunable but is not wired into either compose file or .env.example (#1056 class). Rides the next train once all three are addressed.

@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown

⚠️ Alembic head fork if this PR is merged into dev.

dev has advanced since this PR's checks last ran. GitHub recomputes the merge ref when the base moves but does not re-trigger workflows, so a green schema-parity here can describe a base that no longer exists (#2533).

scripts/ci/check_alembic_heads.py against dev + this PR, merged in memory
alembic-heads: FAIL — src/backend/migrations/versions resolves to 2 heads across 60 revision(s); exactly 1 is required.
  • 0058_agent_canvases_pinned  (0058_agent_canvases_pinned.py)
  • 0058_portal_file_dismissals  (0058_portal_file_dismissals.py)

They fork at: 0057_portal_messages_voice_source  (0057_portal_messages_voice_source.py)

`alembic upgrade head` is singular and resolves its target BEFORE applying anything,
so this graph applies ZERO revisions — every revision since the fork stops arriving,
not only the one that forked. Fix by chaining the newer revision off the real head,
or — if the forked revision may already be applied somewhere — by adding a merge
revision (`alembic merge -m "…" <head-a> <head-b>`), whose tuple `down_revision`
converges the line from any starting state. See Architectural Invariant #3.
alembic-heads: src/backend/enterprise/backend/migrations/versions — version directory absent (submodule not initialised) — skipped.

Fix: rechain this PR's revision off 0058_portal_file_dismissals (the current dev head), or — if the forked revision may already be applied somewhere — add a merge revision (alembic merge -m "…" 0058_agent_canvases_pinned 0058_portal_file_dismissals), whose tuple down_revision converges the line from any starting state. See Architectural Invariant #3.

Push the fix and schema-parity re-checks it against the merge ref immediately; this comment clears on the next push to dev touching src/backend/migrations/versions/**.

Advisory — this check does not block merge. · head_sha: 5fd114c88030f5e25a084b83c3f53408960bfc0c · run

@vybe

vybe commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-09-09): not on this train, three reasons. (1) Alembic two-heads fork: 0058_agent_canvases_pinned.py has down_revision = "0057_portal_messages_voice_source", and dev already carries 0058_portal_file_dismissals off the same parent (#2608) — check_alembic_heads.py on the merged tree fails with 2 heads, so PostgreSQL would apply zero revisions (#2068 class). Re-parent: rename to 0059_agent_canvases_pinned, down_revision = "0058_portal_file_dismissals", and update the path pinned in tests/unit/test_ent553_canvas_lifecycle.py:387 plus the mention in db/migrations.py. (2) It conflicts in src/ with two siblings on this train: #2603's canvas router/service/models edits and #2615's client_portal/service.py — re-merge off dev once those land. (3) CANVAS_MAX_PER_AGENT (models.py:662) is read via os.getenv but wired into neither compose file nor .env.example. Non-blocking but worth a look: the portal delete routes make no audit call (AC 1), canvasLimit is never populated so the headroom label is dead (AC 6), and requirements/core-agent.md:1195 still claims no bound. Please also change Related to → Fixes abilityai/trinity-enterprise#553. Rides the next train once re-parented.

dolho and others added 2 commits September 9, 2026 11:15
…eachable

Two review items from #2619.

**Alembic head fork (#2068 class).** `0058_agent_canvases_pinned` shared
`down_revision = 0057` with #2608's `0058_portal_file_dismissals`, which has
since landed on `dev` — two heads, and `alembic upgrade head` resolves its
single target before applying anything, so EVERY revision merged since the
fork stops arriving, not just one. Re-parented onto
`0058_portal_file_dismissals` and renumbered to `0059` so the prefix keeps
being a usable ordering cue; the id is not applied anywhere yet, so the
rename costs nothing. `check_alembic_heads.py` reports 1 head.

**`CANVAS_MAX_PER_AGENT` was inert (#1039 class).** The refusal message names
the number, but the variable was read only from `os.getenv` in `models.py` and
appeared in no compose file — so an operator following the refusal's own advice
would raise a lever that never reaches the container. Wired into
`docker-compose.yml`, `.prod.yml` and `.hosted.yml` (the last two launch
standalone, no base merge / no `env_file`) plus `.env.example`.

Related to #2619

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP
@dolho

dolho commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

Both of the branch's own blockers are fixed in 16ca1d53, dev merged.

Alembic head fork. 0058_agent_canvases_pinned is re-parented onto 0058_portal_file_dismissals and renumbered 0059_agent_canvases_pinned (the id is applied nowhere yet, so the rename is free, and it keeps the numeric prefix usable as an ordering cue). The three references — the SQLite mirror's docstring, test_ent553_canvas_lifecycle.py and the flow doc — moved with it. check_alembic_heads.py now reports 1 head; alembic-head-watch was the only failing check on the PR.

CANVAS_MAX_PER_AGENT was inert. Confirmed — read only via os.getenv in models.py, present in no compose file. It is the number the refusal message quotes, so an operator following that message would have raised a lever that never reaches the container. Wired into docker-compose.yml, .prod.yml and .hosted.yml (the last two launch standalone — no base merge, no env_file) plus .env.example. Compose parity guards pass.

The #2603 conflict stands as you called it. That PR's fix was a no-op — it read canvas["execution_id"] where every canvas dict carries updated_by_execution_id — and is now fixed on its branch with tests that go through the shape upsert_agent_canvas returns. Once it lands I will re-merge dev here.

@vybe

vybe commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

merge-train (2026-09-09, second run): not on this train either — the branch's own blockers are indeed fixed in 16ca1d53 (Alembic parent is now 0058_portal_file_dismissals, single head), but dev moved under it after the 08:33 re-merge:

  1. Conflicts with dev in src/backend/client_portal/service.py — ent#403 (feat(workspace): a user-friendly model dropdown in the chat composer (abilityai/trinity-enterprise#403) #2615) rewrote the same _card/roster builder signature (is_platform, runtime, model_context keyword-only) that this PR extends with can_manage_canvases. Four hunks (builder signature, the card field block, the roster read, the builder call).
  2. Conflicts with sibling fix(canvas): set_canvas reports whether the audience reaches the session that asked (#2577) #2603 in src/backend/models.py, src/backend/routers/canvas.py, src/backend/services/canvas_service.py. fix(canvas): set_canvas reports whether the audience reaches the session that asked (#2577) #2603 is the smaller fix and lands first.

Both are src/ conflicts, so they need the author's intent, not a mechanical merge. Rides the next train once dev (with #2603 and ent#403) is merged in.

dolho and others added 2 commits September 9, 2026 14:05
…ecycle

# Conflicts:
#	src/backend/client_portal/service.py
#	src/backend/models.py
#	src/backend/routers/canvas.py
#	src/backend/services/canvas_service.py
…t#553

The raw-colour ratchet became enforceable on dev while this branch was
open (#2605/#2609), and the merge brings it here: this PR's delete/pin/
search chrome takes `components/canvas/CanvasPanel.vue` from 25 to 46
`raw_gray`, so `tests/unit/rawColorRatchet.spec.js` fails the frontend
build.

That growth is the honest kind. The design-system contract SPELLS the
neutral ink ladder as `gray-N` — surfaces gray-50/100/800/900, borders
gray-200/300/700/800, ink gray-300/400/500/600 — and there is no
semantic token for a neutral, which is exactly why the spec's own
comment says gray is ratcheted but never held to zero for new files.
The rule it does hold new code to is `raw_nongray`, and this file stays
at **0**.

Re-frozen in its OWN commit with the increase named in the baseline's
`refrozen` block, which is what the ratchet's error message asks for —
not absorbed silently into the feature diff. The entry is hand-edited
rather than regenerated so #2605's provenance block survives; no other
file's ceiling moves (verified: nothing grew, nothing is stale, no
un-baselined file carries `raw_nongray`).

Related to #553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP
@dolho
dolho requested a review from vybe September 9, 2026 13:22
@vybe

vybe commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-09: not on this train — and this one was close enough that it went to a human call rather than being decided by the train.

Credit where it is due: no criticals, CI clean, scope tight, and all three earlier merge-train blockers are genuinely resolved — I re-verified each independently rather than taking the description's word. The Alembic fork is gone (0059_agent_canvases_pinned off 0058_portal_file_dismissals, check_alembic_heads.py reports one head over 60 revisions), both migration tracks are present, and the schema.py DDL feeds both fresh-build paths. Invariants #4, #8, #13 and #14 all hold.

Three things held it back, all in the same direction — the backend is right and the user-facing half does not arrive:

1. The "stated bound" in the title never reaches the user — src/frontend/src/components/canvas/AgentCanvasTab.vue:46

const canvasLimit = ref(0) is declared, bound to the child at :22, and never assigned. canvasHeadroom(n, 0) returns {label: null}, so the early warning cannot render. count_agent_canvases and count_canvases have zero callers outside their own definitions — I grepped every backend .py at head. The agent still gets a correct 409, so the bound is enforced; it is only unstated. Where the limit reaches the client is a design decision, which is why this is yours and not a train patch.

2. Portal deletes are unaudited — src/backend/client_portal/router.py:758,815,832

The platform twins log at routers/canvas.py:157,318; the portal routes record nothing, though the file already imports platform_audit_service at :45 and has _audit_client_control at :394. The guard test_both_delete_routes_are_audited only inspects routers.canvas, so it passes. docs/user-docs/agents/agent-canvas.md tells users deletion is audited. The handlers are sync def with no Request, and mapping a portal principal to an actor is a decision, not a mechanical edit.

3. canManage is hardcoded — AgentCanvasTab.vue:43, AgentDetail.vue:241

const canManage = ref(true), and Agent Detail passes no ownership prop, while ReportsPanel five lines above passes :can-delete="agent.can_share". A merely-shared user sees Manage → Delete/Pin and gets a 403 — the exact failing-control problem can_manage_canvases was added to prevent on the portal surface. This one is a one-liner and I offered to patch it, but it made little sense to land the PR with (1) and (2) open.

Two smaller ones worth folding in: get_agent_card omits can_manage_canvases so it always reads False while the roster says true for the same owner (latent, fails closed); and docs/user-docs/agents/agent-canvas.md:50 says "the agent cannot pin its own canvas", but _gate_human_removal early-returns on current_user.agent_name with only a self-check, so an agent-scoped key can pin its own canvas (verified: own-agent pin 200, sibling 403). Low impact, false claim.

The +21 raw-gray growth on CanvasPanel.vue is fine — argued in its own commit, and I regenerated the scan against your tree and got a byte-identical result, so the ratchet still bites.

Body says Related to abilityai/trinity-enterprise#553 — cross-tracker never auto-promotes, so that issue will need status-in-dev set by hand whenever this lands.

Rides the next train once (1) and (2) are settled.

… on ownership (ent#553)

Three review findings, all in the same direction — the backend was right and
the user-facing half did not arrive — plus the two smaller ones.

1. **The stated bound now reaches the user.** `canvasLimit` was a `ref(0)`
   nothing ever assigned, so `canvasHeadroom(n, 0)` returned `{label: null}` and
   the early warning could not render at any count. The ceiling rides
   `GET /api/settings/feature-flags` as `canvas_max_per_agent` — the established
   home for a value the browser needs to render a surface, and where
   `platform_default_model` / `install_source` already set the precedent for a
   non-boolean. Not a new route (Invariant #13 would owe three surfaces for one
   integer) and not an envelope around the canvas list (the MCP tool and the
   Workspace both read it as a bare array). It is a CONSTANT, not per-agent
   state, and the client already holds the count. `0` still means "not told" and
   still renders nothing, so an older backend is unchanged.

2. **The Workspace canvas writes are audited.** The three portal routes recorded
   nothing while their operator twins have logged since they shipped, and
   `docs/user-docs/agents/agent-canvas.md` tells users deletion is audited — so
   the claim was false for exactly the client-facing surface. `_audit_canvas_change`
   is the shared helper; the actor is `actor_email` (the documented #848
   inline-auth path) rather than a fabricated `User`, which is honest because
   `_require_canvas_manager` is platform-only and owner-or-admin, so a real
   Trinity user is always behind it. Ids and counts only (G-04). The three
   routes become `async def` to await it, matching their operator twins, which
   already call the same sync db functions from an async handler.

   Pinning is audited too, on BOTH surfaces — the operator route was the one
   recording nothing. A pin decides which canvas an entire roster sees first, so
   it is an administrative act on a shared surface, not a per-viewer preference.

3. **`canManage` comes from the parent.** It was hardcoded `true` on the
   argument that the server decides. It does — but a merely-shared user was then
   shown Manage → Delete / Pin and got a 403, which is the failing-control
   problem `can_manage_canvases` exists to prevent on the Workspace. Agent
   Detail passes `agent.can_share`, the same predicate `ReportsPanel` five lines
   above already reads and the same one `_gate_human_removal` enforces. The prop
   defaults FALSE, so a caller that forgets it hides an affordance rather than
   offering one that refuses.

4. **`get_agent_card` resolves `can_manage_canvases`.** It omitted it, so the
   same owner read `true` in the sidebar and `false` on the agent's own page —
   the disagreement #2160's own docstring says that function exists to prevent.

5. **An agent genuinely cannot pin its own canvas now.** The user doc said so;
   `_gate_human_removal` allowed it (right for delete — an agent tidying up
   after itself — and wrong for pin), and "no MCP tool exposes it" is a property
   of the client, not of the route. `_gate_pin` is humans-only, which makes the
   documented sentence true rather than aspirational.

Tests: the audit guard now walks the portal routes as well as `routers.canvas`
(it only ever inspected the latter, which is why three unaudited routes passed
it), plus pin-audit parity, the humans-only pin gate beside the still-permitted
agent self-delete, the feature-flags constant being the same object the refusal
is raised from, the agent-card/roster agreement, and four frontend wiring cases.

1025 backend / 2538 frontend tests green.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN
@dolho

dolho commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

All five addressed in 0b941935.

1. The bound reaches the user. canvas_max_per_agent rides GET /api/settings/feature-flags. The decision you asked for, stated: it is a constant, not per-agent state, and the client already holds the count — so the ceiling is the only missing half. That surface is where a non-boolean UI value already lives (platform_default_model, install_source), it costs no new route (Invariant #13 would owe three surfaces for one integer), and it avoids turning List[CanvasSummary] into an envelope, which the MCP tool and the Workspace both read as a bare array. 0 still means "not told" and still renders nothing, so an older backend behaves exactly as before. A test pins that the flag reads the same constant object the 409 is raised from.

2. Portal deletes — and pins — are audited. _audit_canvas_change in the portal router; the three routes become async def to await it, matching their operator twins, which already call the same sync db functions from an async handler. On the actor question: _require_canvas_manager is platform-only and owner-or-admin, so a real Trinity user is always behind it, and I used actor_email — the documented path for a principal the resolver cannot derive a User for (#848's precedent) — rather than fabricating one. Ids and counts only, per G-04.

I also audited the operator pin route, which recorded nothing either. A pin decides which canvas a whole roster sees first, so it is an administrative act on a shared surface; auditing one surface and not the other buys nothing.

The guard is extended to walk the portal routes, since inspecting only routers.canvas is exactly why three unaudited routes passed it.

3. canManage. Now agent.can_share from AgentDetail, same as ReportsPanel five lines up, and the prop defaults false so a caller that forgets it hides an affordance rather than offering one that 403s.

4. get_agent_card resolves can_manage_canvases through may_manage_canvases, so the page and the sidebar can no longer disagree for the same viewer.

5. The pin claim. Rather than weaken the doc, I made the sentence true: _gate_pin is humans-only. _gate_human_removal lets an agent-scoped key act on its own canvases, which is right for delete and wrong for pin — and "no MCP tool exposes it" is a property of the client, not of the route. Delete still permits agent self-clear; there is a test asserting both halves.

1025 passed, 2 skipped backend across canvas/portal/settings; 2538 frontend.

The user doc is corrected on all three counts (pin refusal, Workspace auditing, the count being shown before the refusal).

@dolho

dolho commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Re-review after the fixes. Clean from me.

Re-verified rather than assumed:

  • Alembic is right against the CURRENT dev, not just against the base it was cut from: merging origin/dev in resolves to one head (0059_agent_canvases_pinned off 0058_portal_file_dismissals, 60 revisions, check_alembic_heads.py PASS). The renumber that fixed the earlier fork holds.
  • 29 passed on test_ent553_canvas_lifecycle.py after that merge, and the three fixes survive it — _gate_pin is still the pin route's gate, and get_agent_card still resolves can_manage_canvases through may_manage_canvases rather than a second ownership answer.

One thing to flag that is not about this PR's contents. The renumber is correct and it breaks the two PRs stacked above it: #2623 still carries the old 0058_agent_canvases_pinned and chains its share migration off that id, and #2628 chains off #2623. Merging this into either produces two heads and alembic upgrade head then applies zero revisions. Neither of those branches can see it — each tree has one head; only the union has two.

So the merge order matters: this one first, then #2623 and #2628 re-based as a stack, bottom-up, with check_alembic_heads.py run on the merged tree rather than the branch. Details are on #2623.

… (ent#553)

Found re-reviewing my own audit fix. Adding the rows was right; the attribution
was wrong, and a row that lands under the wrong actor is worse than the missing
row it replaced — nothing fails, so the wrong answer is believed.

`_audit_canvas_change` passed `actor_email` only. But
`platform_audit_service._resolve_actor` derives `actor_type` from
`actor_user` / `actor_agent_name` / `mcp_scope` / `mcp_key_id` and never from
the email, so an email-only call falls through to its last branch:

    _resolve_actor(None, None, None, None) -> ("system", "trinity-system", None)

So every Workspace canvas delete and pin was recorded as `actor_type="system"`,
`actor_id="trinity-system"` — a named operator's action attributed to the
platform, invisible to any `actor_type=user` query and to the audit UI's
per-actor filter. Verified against the real resolver, not by reading the call.

The `actor_email`-only path I cited (#848 inline auth) is right where the caller
genuinely has no `users` row. That is not this route: `_require_canvas_manager`
is platform-only and resolves through `db.can_user_share_agent`, so a row exists
by construction. It now resolves that row and passes `actor_user`, producing the
same `("user", <id>, <email>)` shape the operator twin has always written —
which is the point, since auditing the two surfaces differently buys little more
than auditing one of them.

Best-effort by construction: the action has already happened, so a lookup that
raises or misses must not drop the row. It falls back to the email-only call
with a WARNING, since a miss would mean the gate admitted someone the user table
does not know.

Tests: the regression is pinned against the REAL `_resolve_actor` (both the
shape the fix must not return to and the shape it produces now), plus a source
guard that the helper resolves a row, passes `actor_user`, keeps the email as a
fallback and cannot raise. Removing `actor_user=` reds it.

31 passed on the ent#553 file; 953 across canvas / portal / audit.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN
@dolho

dolho commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Deeper self re-review — found a defect in my own audit fix. Fixed in 4be21808.

Adding the Workspace audit rows was right. The attribution was wrong, and this is the worse failure of the two: a row that lands under the wrong actor does not fail, so the wrong answer gets believed. A missing row at least reads as missing.

_audit_canvas_change passed actor_email only. platform_audit_service._resolve_actor derives actor_type from actor_user / actor_agent_name / mcp_scope / mcp_key_id — never from the email — so an email-only call falls through to its last branch. Verified against the real resolver rather than inferred:

_resolve_actor(actor_user=None, actor_agent_name=None, mcp_scope=None, mcp_key_id=None)
  -> ('system', 'trinity-system', None)

So every Workspace canvas delete and pin was being written as actor_type="system", actor_id="trinity-system" — a named operator's action recorded as a platform action, invisible to any actor_type=user query and to the audit UI's per-actor filter. Which is close to the opposite of what the row was added for.

The actor_email-only path I cited (#848 inline auth) is correct where the caller genuinely has no users row. That is not this route: _require_canvas_manager is platform-only and resolves through db.can_user_share_agent, so a row exists by construction. I reached for the precedent without checking that its precondition held here.

It now resolves the row and passes actor_user, producing the same ("user", <id>, <email>) shape the operator twin has always written — which was the whole point, since auditing the two surfaces differently buys little more than auditing one of them. Best-effort by construction: the action has already happened, so a lookup that raises or misses falls back to the email-only call with a WARNING rather than dropping the row — and a miss would mean the gate admitted someone the user table does not know, which is worth a log line of its own.

Test pins it against the real _resolve_actor — both the shape it must not return to and the shape it produces now — since the defect lived entirely in what that function does with the arguments, and a source-scan of the call site would have passed either way. Removing actor_user= reds it.

31 passed on the ent#553 file, 953 passed, 3 skipped across canvas / portal / audit.

Everything else from the earlier pass re-read clean: _gate_pin still humans-only with delete still permitting agent self-clear, canvas_max_per_agent still reading the same constant the 409 is raised from, get_agent_card still resolving through may_manage_canvases, and Alembic still one head against current dev.

@vybe

vybe commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-10: not on this train. Fourth time, and I want to be straight about it: all four of the previously-cited blockers are genuinely fixed, and I verified each one independently rather than on your word. What holds it is a new defect introduced by this round's own headline feature — and it is the same class as the one that ejected it before, which is the part worth pausing on.

The four historical blockers — re-verified, all genuinely fixed

# Defect Evidence I produced
1 Alembic head fork check_alembic_heads.py on the PR tree: 60 revisions, 1 head (0059_agent_canvases_pinned off 0058_portal_file_dismissals). Re-ran on the merged dev+PR tree — same PASS.
2 client_portal/ conflicts with dev git merge-tree against live dev tip 5a0cb0078: 0 conflicts. Real merge committed clean.
3 Inert client half (canvasLimit) Traced to a rendered element, every hop live: models.py:662 → routers/settings.py:274 → stores/sessions.js:144 → AgentCanvasTab.vue:112 onMounted → :64 computed → :22 bound → CanvasPanel.vue:247 prop → :266 headroom → :33-34 rendered. All six new canvasUtils exports have live consumers.
4 Audit-row attribution (4be21808) The test executes the real PlatformAuditService._resolve_actor, pinning both the bad shape ("system","trinity-system",None) and the good ("user","7","[email protected]").

Schema is clean too — both tracks, check_alembic_parity.py PASS, DDL in schema.py:531 and tables.py. I ran your suites: 31 passed (ent553), 76 (ent438+ent537), 953 backend canvas/portal/audit on the head and 954 on the merged tree, 2611 frontend, 74 architecture guards, 191 schema/alembic. 29 CI checks green.

❌ The blocker: search narrowing to exactly one match makes that match unreachable

CanvasPanel.vue:46, with :132 and :374-383.

v-if="visible.length > 1 || manage" gates the chip strip on the filtered list. At exactly one match: the strip is hidden; the no-match line at :132 needs !visible.length so it doesn't render either; and the auto-select watcher at :374 keys off props.canvases — unfiltered — so it never selects the match. The user searches, hits one result, and the chips vanish with the previously selected canvas still in the detail pane and no message explaining anything.

Proven by execution, not by reading: 7 canvases, query "Topic 3" → visible.length === 1, strip v-if → false, message v-if → false.

Pre-PR the gate was canvases.length > 1 — unfiltered — so this is newly introduced, and it lands squarely on AC 4, the feature this round exists to add. The correct gate expression is your call, which is why I didn't patch it.

The pattern worth naming

Ejections 1-3 and this one are the same shape: the backend half is correct and the client half doesn't work. canvasLimit declared-and-never-assigned, then this. That is not four unrelated bugs, it is one testing habit — and the evidence is in your own suite. The frontend wiring cases (ent#553 — AgentCanvasTab wiring) are readFileSync + regex over SFC source; vitest runs environment: 'node' with no mount harness, so nothing executes the wiring. Only one of the four executes anything at all (canvasHeadroom(99, 0)). Deleting the line does red the test, so it is a real guard — but it is strictly weaker than execution, and it cannot catch a gate expression that is syntactically present and semantically wrong. That is exactly what happened here.

You already have the technique: your own #2647 slices a real function body out of a .vue and runs it through new Function. Applied to CanvasPanel's two gate expressions, this defect fails in CI instead of in review.

Other findings — none blocking on their own

  • _gate_pin is a denylist over a free-text scope column (routers/canvas.py:105, also :84). if current_user.agent_name: catches only scope == "agent", so a system-scoped key falls through to assert_agent_owner → admin → True for every agent. No new privilege (trinity-system is admin-equivalent by design), but it makes docs/user-docs/agents/agent-canvas.md:51 ("refuses an agent's own key outright") false, and it is precisely the feat: machine identities for admin/ops APIs — service credentials that survive enforced 2FA #2323 denylist class Invariant security: implement safe tar extraction with symlink/hardlink validation #8 records. An allowlist reads the same and fails closed.
  • Cap atomicity is overclaimed — db/canvas.py:238-241 says "not a check-then-act race". Under PostgreSQL READ COMMITTED a COUNT(*) takes no phantom lock, so two concurrent creates can both read limit-1 and both insert. Bounded one-time overshoot; it's the claim that needs correcting (it repeats in the flow doc and PR body).
  • CANVAS_MAX_PER_AGENT=0 bricks canvas creation silently — models.py:662, unvalidated int(os.getenv(...)). 0 >= 0 → every INSERT 409s forever, while the frontend reads the same 0 as "not told" and says nothing. Non-numeric raises at import → boot failure.
  • The 409 has no test — canvas_service.py:307-313 → routers/canvas.py:50. 409 appears nowhere in test_ent553_canvas_lifecycle.py; only the raw db exception is covered. That named message is the entire agent-facing contract of the cap.
  • requirements/core-agent.md:1194-1198 still asserts the error this PR corrects — "Deliberately no retention window: a canvas is bounded by construction". Fixed in feature-flows/ but left standing in the requirements file, which is the stated source of truth (RoE Fix: Add missing Docker labels to system agent container #1/fix: add missing logging_config.py to backend Dockerfile #4), with no FR entries for delete/pin/cap/search.
  • Dead code with a false docstring — db/canvas.py:295 count_canvases / database.py:2218 count_agent_canvases: zero production callers, docstring claims it's "used to SHOW headroom"; headroom is computed in the browser.
  • Select-all can exceed the bulk cap — CanvasPanel.vue:280 toggleAll is unbounded vs models.py:847 max_length=100, and run() at :291 renders e.response.data.detail, which for a 422 is a list of objects. Only reachable if CANVAS_MAX_PER_AGENT > 100.
  • Portal routes skip the canvas_id validation their operator twins apply (client_portal/router.py:773, 904, 928). No SQLi — fully parameterized — but unvalidated ids land in the audit details JSON, and none of the three new destructive routes is rate-limited though the neighbouring read is.
  • N+1 on every roster load — client_portal/service.py:907 calls may_manage_canvases per row (get_user_by_email + can_user_share_agent each). 40 agents → 80 extra queries on the Workspace front door. Your comment acknowledges it.
  • Portal actor lookup is case-sensitive against a non-UNIQUE users.email (service.py:1555) vs the roster's func.lower(...). Fails closed; not reachable on shipped installs.
  • canvasUtils.spec.js is git-binary (literal NUL+BEL from a deliberate safeLabel control-char test — pre-existing on dev). Consequence: its 23 new cases are invisible in the PR diff, and a coverage grep silently false-negatives on it without grep -a. Worth a .gitattributes entry.

Design system and ratchet: compliant. Semantic tokens throughout, every gray has a dark: pair, no dark:text-gray-500, zero hex, bounded viewport for the unbounded list. The raw_gray growth on CanvasPanel.vue (25 → 46) is in its own dedicated commit with the growth named in the baseline JSON, raw_nongray stays 0, and I re-ran the scanner: live count is exactly 46, so the entry isn't above reality and the ratchet still bites. Not counted against you. .env.example/compose add only CANVAS_MAX_PER_AGENT consistently across all three files, so the lever isn't inert (#1039). Secrets sweep across all 32 files: zero hits.

Schema ordering

Independent of the above: #2532 is 0059_execution_fan_out_task_id off the same 0058_portal_file_dismissals, so only one of you can ride. #2532 also ejected this round, so nothing is racing you for the slot — but whichever lands second re-parents. Yours is applied nowhere, so it's a one-line down_revision change either way.

The gate fix and the 409 test are small and contained. This is one more round, not a rewrite.

@github-actions

Copy link
Copy Markdown

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

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

Resolve src/frontend/raw-color-baseline.json: keep dev's #2662 notes, totals
patched to the merged tree's real values (per-file entries unchanged on both
sides; scanner + ratchet test verified).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht
@dolho

dolho commented Sep 11, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the 2026-09-10 ejection in 08719bf1b (propagated into #2623 and #2628, both merge clean; branch merges clean against current dev, and 0059_agent_canvases_pinned still has the slot — #2532 is open, so no re-parent needed yet).

The blocker — search narrowing to one match (CanvasPanel.vue:46)

  • canvasSelectorVisible({visible, manage, query}) in canvasUtils.js: with a query, any hit shows the strip; with none, one canvas is no choice (unchanged from before the PR).
  • canvasAutoSelect(visible, selectedId, query): while a query is active the selection follows the matches — no-op without a query or when the current selection is already a hit. Wired as a watcher on [visible, query], so the unfiltered-props.canvases watcher no longer decides alone.
  • Template reads v-if="selectorVisible".

Took the testing point as stated rather than as advice: canvasPanelSelectorGate.spec.js slices the selectorVisible computed out of the SFC and runs it (the #2647 new Function technique) against the ejection's own numbers — 1 match + query "Topic 3" → true, 1 canvas + no query → false — and pins that the template reads the computed rather than a re-derived length test, and that the watcher calls canvasAutoSelect. The two pure rules have their own cases in canvasUtils.spec.js (9 new).

The 409 has a test now — test_the_cap_reaches_the_wire_as_a_409: the real routers/canvas.write_canvas → canvas_service → db chain with only the Redis rate limiter stubbed; asserts 409 (not 413/500), that the detail names the remedy, and that the same PUT against an existing id at the cap is still an update.

Verified: test_ent553_canvas_lifecycle.py 32 passed (was 31); full vitest 2688 passed on this branch, 2715 on #2623/#2628 after the merge; raw-color ratchet unchanged.

Not touched this round (your "none blocking on their own" list) — _gate_pin allowlist, cap-atomicity wording, CANVAS_MAX_PER_AGENT=0, count_canvases dead code, portal canvas_id validation, the roster N+1. Happy to fold the first three in here if you'd rather not carry them as follow-ups.

🤖 Generated with Claude Code

https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

@vybe

vybe commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-11: not on this train. The 2026-09-10 blocker is genuinely fixed and I verified it by mutation, not by reading: reverting canvasSelectorVisible to the old visible > 1 rule reds "the ejection repro" case in canvasPanelSelectorGate.spec.js, and reverting the template v-if reds "gates the strip on the computed". Schema is clean on both tracks — one head (0059_agent_canvases_pinned ← 0058_portal_file_dismissals) on the branch and again after a git merge origin/dev; check_alembic_parity.py passes both ways. /cso --diff has nothing at the gate.

What holds it is the next defect of the same class, proven by execution rather than inferred:

query is never cleared, so crossing the 7→6 threshold wedges the panel — src/frontend/src/components/canvas/CanvasPanel.vue:26 (<input v-if="showSearch"), :258 (const query = ref('') — its only writer is that input's v-model), :270 (showSearch = ordered.length > SEARCH_THRESHOLD), :135 (the no-match line). Seven canvases, type "Topic 3", delete the one match → six canvases: showSearch flips false, the input unmounts, visible still filters on the stale query, selectorVisible is false, and the panel says No canvas matches "Topic 3" with no control left to clear it. Every remaining canvas is unreachable via chips until navigation. It also happens with no operator action: the agent's own clear_canvas plus a rail refresh while a query is typed. The new gate spec cannot see it because it drives visible/query in isolation from showSearch.

The fix is one gate expression plus one spec case, but which expression is yours to pick — keep the box while a query is active (showSearch = ordered.length > T || !!query.trim()), or reset query when showSearch flips false. Same standard the train applied on 09-10.

Four mechanical items can ride the same push:

  • docs/memory/requirements/core-agent.md:1194-1198 still asserts "deliberately no retention window: a canvas is bounded by construction" — the claim this PR corrects; and no requirements entries exist for delete/pin/cap/search.
  • src/frontend/raw-color-baseline.json: the _ent553_note that 2794388b added was dropped by the dev merge aa248f77; CanvasPanel.vue raw_gray is 25 → 46 and the growth is no longer named in the file.
  • Body: Implements / Related to abilityai/trinity-enterprise#553 — neither is a closing keyword. Fixes abilityai/trinity-enterprise#553.
  • routers/canvas.py:1 # mcp: header lists the five covered tools but doesn't say pin/bulk-delete are unexposed on purpose — Invariant feat: SMARTS trading pipeline with Telegram notifications and Miro visualization #13's "deliberate vs forgotten" signal.

Rides the next train once fixed.

dolho and others added 2 commits September 13, 2026 08:01
…t#553 review)

`query` has exactly one writer — the search input's `v-model` — and that
input was `v-if="showSearch"` with `showSearch = ordered.length > 6`.
Seven canvases, type "Topic 3", delete the one match: six canvases, the
box unmounts, `visible` still filters on the stale query, the strip
collapses, and the panel says *No canvas matches "Topic 3"* with no
control left to clear it. Every remaining canvas is unreachable via the
chips until navigation. Also reachable with no operator action: the
agent's own `clear_canvas` plus a rail refresh while a query is typed.

The rule is pure — `canvasSearchVisible(count, threshold, query)` — and
keeps the box while a query is active regardless of the count: the typed
intent survives the shrink, and the no-match line keeps the one control
that clears it. Resetting `query` when the box would flip off was the
other option and was rejected: it erases a search the user was mid-way
through because a sibling canvas went away.

The gate spec that pinned the previous ejection drove `visible`/`query`
in isolation from `showSearch`, which is why it could not see this one.
It now slices the real `showSearch` computed out of the SFC and RUNS it
against the ejection's own numbers (7 → 6 with "Topic 3" typed → box
stays; 6 with no query → box gone), and pins that the input is gated on
that computed and is the sole writer of `query`. Mutation-checked:
reverting the gate to the old length test reds three cases.

Four mechanical items from the same review ride along:

- requirements/core-agent.md: the ent#438 "deliberately no retention
  window: bounded by construction" line now says why that reasoning was
  wrong (rows are bounded per canvas, the count was not) and what bounds
  it instead; FR-18..FR-22 record delete / bulk / cap / pin / search,
  which had no requirements entries at all.
- raw-color-baseline.json: the `_ent553_note` naming CanvasPanel.vue's
  25 → 46 raw_gray was added in 2794388 and dropped by the dev merge
  aa248f7; re-added so the growth is named in the file.
- routers/canvas.py `# mcp:` header now says pin and bulk-delete are
  unexposed on purpose, and why — Invariant #13's deliberate-vs-forgotten
  signal.
- feature-flows/agent-canvas.md: the two search-state rules and the
  defect class they close.

Verified: vitest 2696 passed (121 files); canvas backend suites 101
passed; raw-colour ratchet and loading-gate ratchet unchanged.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RS8FBA7oEtAAv6GamZKong
@dolho

dolho commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the 2026-09-11 ejection in f2adcfa4d, dev merged in (a0f31a59e), and propagated bottom-up into #2623 and #2628 — each merged tree resolves to one Alembic head (0059_agent_canvases_pinned → 0060_agent_canvas_shares → 0061_execution_open_canvas).

The blocker — query never cleared across the 7→6 threshold (CanvasPanel.vue)

Took the first of your two options: the box stays while a query is active. canvasSearchVisible(count, threshold, query) in canvasUtils.js — with a query typed it returns true at any count, so the typed intent survives the shrink and the no-match line keeps the one control that clears it; with none it is the old count > threshold. Resetting query on the flip was rejected: it erases a search the user was mid-way through because a sibling canvas went away (and, on the clear_canvas + rail-refresh path, with no operator action at all).

You named why the previous gate spec could not see this — it drove visible/query in isolation from showSearch — so canvasPanelSelectorGate.spec.js now slices the real showSearch computed out of the SFC and runs it against the ejection's numbers (7 → 6 with "Topic 3" typed → box stays; 6 with no query → box gone; 3 with "zzz" → box up while the strip is down), and pins that the input is gated on that computed and is the sole v-model="query" writer. Mutation-checked: reverting the gate to ordered.length > SEARCH_THRESHOLD reds three cases. Four pure cases in canvasUtils.spec.js.

The four mechanical items

  • requirements/core-agent.md: the ent#438 "deliberately no retention window: bounded by construction" line now says why that reasoning was wrong (rows were bounded per canvas, the count was not) and what bounds it instead; FR-18..FR-22 record delete / bulk / cap / pin / search, which had no entries.
  • raw-color-baseline.json: _ent553_note re-added (25 → 46 raw_gray on CanvasPanel.vue, named), with the dropped-by-merge provenance in the note.
  • Body: Fixes abilityai/trinity-enterprise#553.
  • routers/canvas.py:1: the # mcp: header names pin and bulk-delete as deliberately unexposed and why (one line — the convention is a first-line header).

feature-flows/agent-canvas.md also records the two search-state rules as one defect class.

Verified on this branch after the dev merge: vitest 2776 passed (126 files); canvas backend suites 155 passed; raw-colour + loading-gate ratchets unchanged; check_alembic_heads.py 1 head.

🤖 Generated with Claude Code

https://claude.ai/code/session_01RS8FBA7oEtAAv6GamZKong

@vybe

vybe commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

merge-train 2026-09-12: not on this train. No commits since the 2026-09-11 ejection (08719bf1 is still the head), so the query-never-cleared wedge at CanvasPanel.vue:26/:258/:270/:135 and the four mechanical items in that comment stand as written. Also note 0059_agent_canvases_pinned still shares its parent with #2728 and #2532 — none of the three landed today, so the slot remains open. Rides the next train once fixed.

@github-actions

Copy link
Copy Markdown

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

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

…ecycle

Conflict: src/frontend/raw-color-baseline.json (the `totals` block only).

The two sides moved different counters for unrelated reasons, so the
resolution takes both rather than choosing a side:

- dev (#2718) fixed a scanner false positive — a `#` followed by hex
  digits in rendered copy (issue references like `(#526)`) was read as a
  colour — dropping hardcoded_colors 456 -> 447 across 8 files. Nothing
  on this branch touches those files.
- this branch adds the canvas delete/pin/search chrome, which raises
  semantic_tokens 4020 -> 4030.

Merged totals are therefore hardcoded_colors 447 (dev's) and
semantic_tokens 4030 (this branch's); raw_nongray, raw_gray and
files_with_violations were identical on both sides and merged cleanly.

`totals` is informational — the ratchet compares PER-FILE counts — but it
is kept honest anyway. Verified with the gate itself:
`npx vitest run tests/unit/rawColorRatchet.spec.js` → 14 passed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ
@dolho

dolho commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Review: /review + /validate-pr

Reviewed against the merge-base with dev (2c5cfe0e3) after the conflict resolution. Recommendation: APPROVE — no critical findings; five informational, none blocking.

/validate-pr — Lane C+schema

Lane C is triggered by the three docker-compose*.yml files (the new env var), not by an auth/credential path. +schema by db/{schema,migrations,tables}.py + the new Alembic revision.

Category Status Notes
Base branch ✅ dev
Closing keyword ✅ Fixes abilityai/trinity-enterprise#553 — cross-tracker, so set status-in-dev on ent#553 by hand after merge (the automation is same-repo only)
PR size ✅ 35 files, +2220/−59
Dual-track migration (Invariant #9) ✅ SQLite agent_canvases_pinned and Alembic 0059_agent_canvases_pinned; NOT NULL DEFAULT 0 on both, so pre-#553 rows read unpinned with no backfill
Alembic single head ✅ check_alembic_heads.py → 62 revisions, 1 head. 0059 chains off 0058_portal_file_dismissals — no fork (#2068)
Config packaging (§4.9) ✅ CANVAS_MAX_PER_AGENT wired into all three composes + .env.example. This is the #1039/#1707 class handled properly — prod and hosted launch standalone, and both were covered
Build packaging (§4.8) ✅ no new top-level src/backend/ package
Security greps (§4.1–4.3, 4.5, 4.10) ✅ clean; no symlink/mode flip, no host paths
Docs ✅ feature-flows/agent-canvas.md (+92), requirements/core-agent.md (+84), user-docs/agents/agent-canvas.md
Merge gate (Step 6.5) ✅ 28/28 green — pytest ×6 seeds, prod-image-smoke, pg-migrations, schema-parity, gitleaks, verify-non-root
Test adequacy ✅ 33 tests in test_ent553_canvas_lifecycle.py covering both gates, audit attribution, cap semantics, route ordering and the migration tracks

⚠️ One warning — no ui label. The diff changes 266 lines of CanvasPanel.vue plus AgentCanvasTab.vue and PortalRailCanvas.vue, but the PR carries no labels, so frontend-e2e never exercised the new UI in a browser. Unit coverage is real (canvasPanelSelectorGate.spec.js, and canvasUtils.spec.js roughly doubled), so this is a gap in browser-level coverage, not in coverage generally. Add ui if you want the e2e run before merge.

/review — structural

Critical: none.

Checked and clean, with the line that proves it:

  • SQL safety — every new statement is SQLAlchemy Core with bound params; delete_canvases puts agent_name in the WHERE alongside canvas_id.in_(...), so an authorized-for-one-agent caller cannot reach another's rows (pinned by test_bulk_delete_cannot_reach_another_agents_canvases).
  • Auth boundaries — two gates, both correct and both tested. _gate_pin is deliberately not _gate_human_removal: an agent key may delete its own canvas but may not pin one, which is what makes the user-doc sentence "the agent cannot pin its own canvas" true rather than aspirational. The portal's may_manage_canvases reuses db.can_user_share_agent — the same predicate assert_agent_owner reaches — rather than a second implementation.
  • Route ordering (Invariant fix: add missing logging_config.py to backend Dockerfile #4) — bulk-delete declared above the parameterized routes on both routers.
  • Enumeration safety (Invariant security: implement safe tar extraction with symlink/hardlink validation #8) — _require_canvas_manager raises a uniform 404, matching the prefix's contract.
  • Value completeness (4.12) — pinned reaches all three canvas-dict constructors (_row_to_summary, the upsert return, and empty_canvas); the last is the easy one to miss and it is covered.
  • Frontend — no v-html introduced; the destructive actions confirm once via bulkDeletePrompt, and failures surface through actionError.

Informational

[I1] The portal bulk-delete does not validate canvas ids; its operator twin does. (Confidence: 8/10)
src/backend/client_portal/router.py:794 — deleted = db.delete_agent_canvases(agent_name, body.canvas_ids), with no validate_canvas_id loop, where routers/canvas.py:171 runs one. CanvasBulkDelete caps the list at 100 but puts no bound on each item, and CANVAS_ID_RE ({1,64}) is what supplies that bound on the operator path. Not a SQL-injection risk (parameterized) and not an audit-log injection risk (only ids that matched are logged), but it means the external-facing route accepts a 100 × 1 MB body that the operator route would reject with a named 400. Adding the same loop makes the two surfaces agree.

[I2] count_canvases has no production caller. (Confidence: 9/10)
db/canvas.py + the count_agent_canvases facade in database.py:2222 are reached only from test_ent553_canvas_lifecycle.py:205,222. Its docstring says it is "used to SHOW headroom", but the UI derives headroom from the list length it already holds plus canvas_max_per_agent from the feature-flags surface. Either wire it or drop it — a helper whose stated purpose nothing fulfils is the thing a later reader trusts.

[I3] The portal routes declare no response_model; the operator twins do. (Confidence: 7/10)
client_portal/router.py:780, 908, 934 return bare dicts, while routers/canvas.py uses CanvasBulkDeleteResult and CanvasSummary. CanvasBulkDeleteResult is already defined and already used by the operator route, so the portal could adopt it as-is. Worth more here than on the operator side: a declared response model is what stops a later field from leaking to an external client by accident.

[I4] The cap's "not a check-then-act race" claim is stronger than the engine guarantees. (Confidence: 7/10)
db/canvas.py — the comment on the count says "the count and the insert share one transaction, so this is not a check-then-act race". db/engine.py sets no isolation_level, so on PostgreSQL that is READ COMMITTED (two concurrent creators can both read count = 99 and both insert), and on SQLite pysqlite defers BEGIN until the first DML, which puts the SELECT outside the transaction it is claimed to share. The overshoot is bounded by concurrency and the cap is deliberately generous, so the behaviour is fine — but the comment will be believed by the next person, and it should say the cap is approximate under concurrency rather than exact.

[I5] actionError can render a Pydantic 422 body as [object Object]. (Confidence: 5/10 — low-confidence appendix)
CanvasPanel.vue — e?.response?.data?.detail is a list of error dicts for a 422, not a string. Reachable only via a malformed request the UI does not currently make, which is why this is an appendix item rather than a finding.

Note on the tooling, not the PR

/validate-pr §4.9 greps the checked-out compose files rather than the PR's version of them, so run from any tree that is not on the PR branch it reports a false ❌ "read in code but missing from docker-compose.yml" for a var the PR does in fact wire up. It did exactly that here on the first pass. Worth fixing in the skill.

🤖 Generated with Claude Code · https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

@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: batch validated on train/20260914-0901 (train PR #2765, full suite green). All fourteen previously cited blockers verified fixed on head 46f4928 by code and execution; single Alembic head on the merged tree.

@vybe
vybe merged commit 00d8790 into dev Sep 14, 2026
31 checks passed
vybe added a commit that referenced this pull request Sep 14, 2026
#2619 (ent#553) squash-landed on dev, so the stacked base is gone. Conflicts
were the parent-squash echo in nine canvas files (branch already carried
#2619's final tree, 46f4928) plus two docs files dev had moved on:
learnings.md keeps both the 2026-09-13 and the ent#554 entries;
user-docs/agent-canvas.md takes the #2746 sync and re-adds the share/PDF
section and the share bullets. Tree vs dev is exactly the ent#554 delta
(27 files, +2178/-20).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LAFj2RWjsQWPgnq1vNT9Xm
vybe added a commit that referenced this pull request Sep 14, 2026
…#554) (#2623)

* feat(canvas): delete, pin, search and a stated bound for the canvas pile

An agent that uses its canvas the way ent#438 intends accumulates dozens: one
per report, per topic, per run. The Workspace could only ever ADD to that pile
— the client-portal surface had no delete at all, the only ordering was "newest
updated", and nothing bounded the table.

Two decisions, both by operator ruling 2026-09-08, recorded because each had a
plausible alternative:

**Deleting is owner-or-admin.** The answer ent#548 gives for files — the owner
deletes the shared artifact. This NARROWS the platform DELETE route, which
accepted any user with agent access; safe because no UI called it, so no
workflow depended on the wider gate. A canvas is one shared surface with no
per-user copy, so a non-owner has no "hide it from my list" middle ground: per
AC #2 they see no control at all rather than one that 403s. Agents keep
clearing their own (`clear_canvas`, the #918 self-gate).

**The bound is a per-agent CAP, not a retention window.** ent#438 recorded "no
retention window" because the composite key bounds rows per canvas — but
`canvas_id` is agent-chosen, so the COUNT was unbounded; the axis was missed,
not decided. `CANVAS_MAX_PER_AGENT` (100, env-tunable) is checked inside
`upsert_canvas`'s insert branch, in the same transaction as the INSERT, so it
is not a check-then-act race. Updating an existing canvas is NEVER refused — a
cap that froze updates would punish exactly the agent that reuses ids — and the
refusal is a named 409 telling the agent to retire one, never an eviction:
deleting a person's surfaces on a timer is the #1638 failure direction.

Both surfaces resolve permission through `db.can_user_share_agent`, the same
predicate `assert_agent_owner` uses, so Agent Detail and the Workspace cannot
disagree about who owns an agent. The Workspace learns it from
`PortalAgentCard.can_manage_canvases` — the portal's only capability channel
(#2128), since a portal principal cannot read `/api/settings/feature-flags` —
and it fails closed.

`pinned` (dual-track: `agent_canvases_pinned` + Alembic 0058, NOT NULL DEFAULT
0, no backfill) is written only by the human pin route and is deliberately
absent from every agent-facing tool: `audience` is the agent's decision about
who may read, `pinned` is the reader's about what they see first, and an agent
that could pin itself to the top would defeat the ordering. A pin survives the
agent rewriting the canvas.

Living with many is `CanvasPanel.vue`, shared by both surfaces (one rendering
layer, per ent#475): search once the list passes six, a height-bounded strip so
a long list does not cost the rail its other tabs, and a Manage mode giving
each row its age, stale mark, pin and delete. Decidable rules are pure in
`canvasUtils.js` — vitest runs `environment: 'node'` with no mount harness, so
a rule inside the SFC is one no test can reach.

Bulk delete is a POST, not a body-carrying DELETE (bodies on DELETE are
permitted-but-unreliable and this one is not optional), declared above the
parameterized routes on both routers (Invariant #4), and it reports the ids
that EXISTED rather than the ids requested so "3 of 5 removed" is sayable.

Three pre-existing guards failed and each was right to: `empty_canvas` was
missing the new field (a real bug in this change, fixed), the self-gate guard
needed to learn the new gate's name, and the positional-read guard needed its
synthetic row extended — that one exists precisely because `_row_to_summary`
reads by index.

Tests: 20 new backend cases (cap refusal + update-at-cap, pin ordering and
survival, bulk scoping, the permission matrix on both surfaces, route ordering,
dual-track migration parity, and that the MCP tools cannot pin) and ~24 vitest
cases for the pure rules. Verified against a real database: the cap refuses the
4th of 3, updates still succeed at the cap, a pin outranks recency and survives
a rewrite, and bulk delete returns only the ids that existed.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* feat(canvas): audit the single delete, cover the default canvas, document the lifecycle

Closes the three acceptance criteria the first commit left open:

* AC #1 asked for the deletion to be audited and only the BULK route was —
  the single-canvas route is the one a person actually clicks. Logged only
  when something was removed, since the route is idempotent and a repeat
  click would otherwise fill the trail with events where nothing happened.
* AC #8: deleting the DEFAULT canvas is allowed, comes back empty on the
  next write, and frees a slot against the cap. `main` is the id both the
  MCP tools and the voice panel fall back to, so it is the one most likely
  to be deleted by accident and the one whose deletion must strand nobody.
* AC #9: the user doc gains a "Removing canvases" section stating the
  permission rule, the cap, and that nothing is ever deleted to make room.

Also records a latent pre-existing mismatch found while testing:
`empty_canvas` returns None timestamps while `models.Canvas` requires
strings, so `Canvas(**empty_canvas(...))` raises. Not live — its only
caller declares no `response_model` — but adding one there would turn the
voice teardown poll into a 500. Left as a comment where the next person to
reach for that will meet it, rather than fixed out of scope.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* feat(canvas): share a canvas at a link, and download it as a PDF

A canvas is where an agent's real output lives, and until now it could not
leave the Workspace: no share link, no export, nothing in the tree that renders
a PDF.

**Sharing never widens the audience by accident.** Two scopes, and the default
is the narrow one: `authorized` makes the link a DEEP link — opening it
requires signing in and the server re-checks `can_user_access_agent`, so it
reaches "the people who could already see it" and nobody else. `public` is an
explicit, separate, audited choice. Failing narrow is enforced in five
independent places (column default, Pydantic default, `normalize_scope`'s
fallback, the order of `SHARE_SCOPES`, the radio the dialog preselects),
because a link that reaches further than the sharer understood is the one
failure this feature must not have.

**`agent_canvas_shares` is deliberately its own table.** `agent_public_links`
has a `type` column that looks purpose-built for this, and reusing it would
have been a real vulnerability: nothing in that table's read path filters on
type — `get_public_link_by_token`, `is_link_valid` and
`routers/public.py::_validate_public_link` all resolve a token whatever it is —
so a canvas row there would ALSO be a working public-CHAT token, and anyone
sent a canvas could talk to the agent. (`type='site'` is the same trap already
laid; it is unexploited only because nothing creates those rows today.) A
separate table makes the isolation structural instead of dependent on every
consumer remembering to check.

**Live, and it says so** (AC #3, operator ruling): the link renders the canvas
as it is now, carrying its `updated_at` and stale mark, and the page states it
is not a copy taken at share time. That follows ent#438's model — a canvas is a
surface an agent keeps current — and means a share stores nothing. The cost is
drift after sharing; the mitigation is revocation, not freezing.

**Revocation keeps the row.** `revoked_at` is stamped, never deleted, because a
revoked link has to be able to SAY it was revoked (AC #2), which it cannot do
once the row is gone. The status vocabulary splits along disclosure: `revoked`
and `expired` are returned only for a token that MATCHED a row — whoever holds
such a link was already told the canvas exists — while an unknown token and a
canvas deleted out from under a link both collapse into one `not_found`, so a
stranger guessing tokens learns nothing from the difference. An unparseable
`expires_at` reads as expired: a lifetime we cannot read is one we cannot
promise is live.

**PDF is print-first**, the path the issue recommended: a print stylesheet plus
the browser's own PDF. No headless service to run, and — the deciding reason —
no second renderer to keep in step with `CanvasBlock`. A server-side renderer
was the stated fallback and was not needed: pagination (`break-inside: avoid`
per block) and fidelity both fall out of the same markup the screen uses.
`CanvasDocument.vue` is the one printable form, rendered by both the shared
page and every authenticated surface, so AC #7's "identical from every canvas
surface" is true by construction rather than by three surfaces agreeing. It
carries title, agent and generation date, forces the light rendering under
`@media print`, and when `window.print` is unavailable the control says so and
the share link still works.

`ent#425` (hosted deliverable pages) is still open, so per this issue's own
boundary rule this ships the narrower share link and #425 adopts it later.

Verified against a real database, not stubs: the full resolution matrix
(public/anonymous → ok, authorized/anonymous → sign-in, authorized/owner → ok,
authorized/stranger → refused, unknown → not-found, revoked, expired,
unparseable expiry → expired, canvas deleted → not-found), views counted only
on a successful render, cross-agent revoke refused, and a second revoke keeping
the first revocation time.

23 backend tests, 20 vitest cases for the pure rules.

Related to Abilityai/trinity-enterprise#554

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* test(canvas): patch the cap where the live code reads it, not where the test imports it

Two ent#553 tests passed in isolation and failed in a full-suite run:
`test_the_cap_refuses_a_new_canvas_by_name` and
`test_deleting_the_default_canvas_frees_a_slot_against_the_cap`.

Order-dependence, not a defect in the feature. They patched
`db.canvas.CANVAS_MAX_PER_AGENT` via a fresh `import db.canvas`. Some earlier
test in the suite evicts that module from `sys.modules`, so the fresh import
hands back a NEW module object while the live `db._canvas_ops` is still an
instance of the OLD class — whose `upsert_canvas` reads the OLD module's
globals. The patch lands somewhere nothing consults, the cap stays at its
default of 100, and the "refuses the 4th of 3" assertions fail.

`_set_cap` patches the bound method's own `__globals__`, which is whichever
module dict the running code actually closes over — correct whether or not an
eviction happened, so it does not depend on knowing which test pollutes.

Same failure and same fix as #2589, where the identical shape bit
`mark_stale_activities_failed`. Worth noting the class: a monkeypatch on a
module attribute is only as good as the assumption that the live object came
from that module object, and in a suite that evicts modules that assumption is
not free.

The feature is unchanged — this touches only the test file.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* fix(canvas): print the canvas, not the whole page

Reported from hands-on testing: pressing PDF offered to export the entire page.
Correct report — the print stylesheet only STYLED the document and never hid
anything else, so `window.print()` printed the nav bar, the tabs, the
on-screen panel AND the print copy. That is not "one clean column" by any
reading (AC #4), and it is the first thing anyone pressing the button hits.

Two halves, both required:

* a print rule that hides every `body` child except `.canvas-print-root`;
* the print copy TELEPORTED to <body>, so it is a body child and the rule can
  spare it. Nested inside the app the rule would hide its ancestor and print
  nothing at all — worse than the bug.

`body > *` rather than a class on the app root: it needs no knowledge of how
the app is mounted and works identically on the standalone shared page, which
keeps AC #7's "identical from every surface" true rather than approximately
true. The copy is rendered only while printing (`v-if="printing"` + a
`nextTick` flush before `print()`, since printing a not-yet-rendered teleport
yields a blank sheet), so the DOM carries no permanent hidden duplicate.

`canvasPrintIsolation.spec.js` pins all three structural facts. Nothing
automated can inspect a print preview, which is exactly why the bug shipped —
so the guard asserts the mechanism instead: the hiding rule exists, the root is
teleported to body, and the document mounts before print() is called.
Mutation-tested: removing the hiding rule fails it.

Also fixes a design-system violation the ratchet caught in the same file:
`SharedCanvas` gated its skeleton on a bare `v-if="loading"`. Now
`viewState()` — loading means "no data yet", never "a fetch is in flight"
(#1927, design-system p13-p15). The page fetches once today, so this is the
rule holding rather than a bug fixed; it stays correct if a refresh is added.
Baselining my own new violation was the alternative and would have been the
wrong one.

Related to Abilityai/trinity-enterprise#554

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* fix(canvas): re-parent the pinned revision, and make the canvas cap reachable

Two review items from #2619.

**Alembic head fork (#2068 class).** `0058_agent_canvases_pinned` shared
`down_revision = 0057` with #2608's `0058_portal_file_dismissals`, which has
since landed on `dev` — two heads, and `alembic upgrade head` resolves its
single target before applying anything, so EVERY revision merged since the
fork stops arriving, not just one. Re-parented onto
`0058_portal_file_dismissals` and renumbered to `0059` so the prefix keeps
being a usable ordering cue; the id is not applied anywhere yet, so the
rename costs nothing. `check_alembic_heads.py` reports 1 head.

**`CANVAS_MAX_PER_AGENT` was inert (#1039 class).** The refusal message names
the number, but the variable was read only from `os.getenv` in `models.py` and
appeared in no compose file — so an operator following the refusal's own advice
would raise a lever that never reaches the container. Wired into
`docker-compose.yml`, `.prod.yml` and `.hosted.yml` (the last two launch
standalone, no base merge / no `env_file`) plus `.env.example`.

Related to #2619

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP

* chore(design-system): re-freeze CanvasPanel's raw-gray ceiling for ent#553

The raw-colour ratchet became enforceable on dev while this branch was
open (#2605/#2609), and the merge brings it here: this PR's delete/pin/
search chrome takes `components/canvas/CanvasPanel.vue` from 25 to 46
`raw_gray`, so `tests/unit/rawColorRatchet.spec.js` fails the frontend
build.

That growth is the honest kind. The design-system contract SPELLS the
neutral ink ladder as `gray-N` — surfaces gray-50/100/800/900, borders
gray-200/300/700/800, ink gray-300/400/500/600 — and there is no
semantic token for a neutral, which is exactly why the spec's own
comment says gray is ratcheted but never held to zero for new files.
The rule it does hold new code to is `raw_nongray`, and this file stays
at **0**.

Re-frozen in its OWN commit with the increase named in the baseline's
`refrozen` block, which is what the ratchet's error message asks for —
not absorbed silently into the feature diff. The entry is hand-edited
rather than regenerated so #2605's provenance block survives; no other
file's ceiling moves (verified: nothing grew, nothing is stale, no
un-baselined file carries `raw_nongray`).

Related to #553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP

* fix(canvas): state the bound, audit the Workspace writes, gate Manage on ownership (ent#553)

Three review findings, all in the same direction — the backend was right and
the user-facing half did not arrive — plus the two smaller ones.

1. **The stated bound now reaches the user.** `canvasLimit` was a `ref(0)`
   nothing ever assigned, so `canvasHeadroom(n, 0)` returned `{label: null}` and
   the early warning could not render at any count. The ceiling rides
   `GET /api/settings/feature-flags` as `canvas_max_per_agent` — the established
   home for a value the browser needs to render a surface, and where
   `platform_default_model` / `install_source` already set the precedent for a
   non-boolean. Not a new route (Invariant #13 would owe three surfaces for one
   integer) and not an envelope around the canvas list (the MCP tool and the
   Workspace both read it as a bare array). It is a CONSTANT, not per-agent
   state, and the client already holds the count. `0` still means "not told" and
   still renders nothing, so an older backend is unchanged.

2. **The Workspace canvas writes are audited.** The three portal routes recorded
   nothing while their operator twins have logged since they shipped, and
   `docs/user-docs/agents/agent-canvas.md` tells users deletion is audited — so
   the claim was false for exactly the client-facing surface. `_audit_canvas_change`
   is the shared helper; the actor is `actor_email` (the documented #848
   inline-auth path) rather than a fabricated `User`, which is honest because
   `_require_canvas_manager` is platform-only and owner-or-admin, so a real
   Trinity user is always behind it. Ids and counts only (G-04). The three
   routes become `async def` to await it, matching their operator twins, which
   already call the same sync db functions from an async handler.

   Pinning is audited too, on BOTH surfaces — the operator route was the one
   recording nothing. A pin decides which canvas an entire roster sees first, so
   it is an administrative act on a shared surface, not a per-viewer preference.

3. **`canManage` comes from the parent.** It was hardcoded `true` on the
   argument that the server decides. It does — but a merely-shared user was then
   shown Manage → Delete / Pin and got a 403, which is the failing-control
   problem `can_manage_canvases` exists to prevent on the Workspace. Agent
   Detail passes `agent.can_share`, the same predicate `ReportsPanel` five lines
   above already reads and the same one `_gate_human_removal` enforces. The prop
   defaults FALSE, so a caller that forgets it hides an affordance rather than
   offering one that refuses.

4. **`get_agent_card` resolves `can_manage_canvases`.** It omitted it, so the
   same owner read `true` in the sidebar and `false` on the agent's own page —
   the disagreement #2160's own docstring says that function exists to prevent.

5. **An agent genuinely cannot pin its own canvas now.** The user doc said so;
   `_gate_human_removal` allowed it (right for delete — an agent tidying up
   after itself — and wrong for pin), and "no MCP tool exposes it" is a property
   of the client, not of the route. `_gate_pin` is humans-only, which makes the
   documented sentence true rather than aspirational.

Tests: the audit guard now walks the portal routes as well as `routers.canvas`
(it only ever inspected the latter, which is why three unaudited routes passed
it), plus pin-audit parity, the humans-only pin gate beside the still-permitted
agent self-delete, the feature-flags constant being the same object the refusal
is raised from, the agent-card/roster agreement, and four frontend wiring cases.

1025 backend / 2538 frontend tests green.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN

* fix(canvas): the Workspace audit names the operator, not the platform (ent#553)

Found re-reviewing my own audit fix. Adding the rows was right; the attribution
was wrong, and a row that lands under the wrong actor is worse than the missing
row it replaced — nothing fails, so the wrong answer is believed.

`_audit_canvas_change` passed `actor_email` only. But
`platform_audit_service._resolve_actor` derives `actor_type` from
`actor_user` / `actor_agent_name` / `mcp_scope` / `mcp_key_id` and never from
the email, so an email-only call falls through to its last branch:

    _resolve_actor(None, None, None, None) -> ("system", "trinity-system", None)

So every Workspace canvas delete and pin was recorded as `actor_type="system"`,
`actor_id="trinity-system"` — a named operator's action attributed to the
platform, invisible to any `actor_type=user` query and to the audit UI's
per-actor filter. Verified against the real resolver, not by reading the call.

The `actor_email`-only path I cited (#848 inline auth) is right where the caller
genuinely has no `users` row. That is not this route: `_require_canvas_manager`
is platform-only and resolves through `db.can_user_share_agent`, so a row exists
by construction. It now resolves that row and passes `actor_user`, producing the
same `("user", <id>, <email>)` shape the operator twin has always written —
which is the point, since auditing the two surfaces differently buys little more
than auditing one of them.

Best-effort by construction: the action has already happened, so a lookup that
raises or misses must not drop the row. It falls back to the email-only call
with a WARNING, since a miss would mean the gate admitted someone the user table
does not know.

Tests: the regression is pinned against the REAL `_resolve_actor` (both the
shape the fix must not return to and the shape it produces now), plus a source
guard that the helper resolves a row, passes `actor_user`, keeps the email as a
fallback and cannot raise. Removing `actor_user=` reds it.

31 passed on the ent#553 file; 953 across canvas / portal / audit.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN

* fix(migrations): chain 0060_agent_canvas_shares off the renamed pinned revision

ent#553 renamed its revision 0058_agent_canvases_pinned -> 0059 when it
absorbed dev's 0058_portal_file_dismissals; this revision still pointed at
the old id, so after the merge the directory resolved to two heads and
`alembic upgrade head` would have applied nothing. Renumbered to 0060 as
well so the numeric prefix stays a unique ordering cue.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* chore(frontend): re-freeze CanvasPanel.vue raw_gray 46 -> 62 for ent#554

The share/PDF controls add gray chrome copied from the panel's existing
header; the branch predates the #2605 ratchet, so the guard first bit when
dev was merged in. Scoped to this one entry, in its own commit, as the
guard's own message prescribes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* test(canvas): resolve CanvasLimitExceeded from the live method's globals

The two cap tests imported the class from `db.canvas` while `_set_cap` already
patches the cap through `upsert_canvas.__globals__` — because an earlier test
can evict and re-import the module. The same eviction gives the test a
different class object than the one the live code raises, and `pytest.raises`
then reports the correct refusal as an unexpected exception. Seen once in a
full local run after the dev merge (both tests pass in isolation and under
CI's three seeds); resolve the class from the same globals the cap comes from.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* fix(canvas): keep the selector visible when a search narrows to one match (ent#553 review)

`CanvasPanel.vue` gated the chip strip on `visible.length > 1 || manage`,
where `visible` is the FILTERED list. Searching down to exactly one canvas
hid the strip while the previously selected canvas stayed on screen, and the
auto-select watcher — keyed off the unfiltered `props.canvases` — never
selected the match. Proven by execution: 7 canvases, query "Topic 3" → strip
false, no-match message false. The one canvas the user just searched for was
unreachable.

Fix:
- `canvasSelectorVisible({visible, manage, query})` — with a query, any hit
  shows the strip; without one, a single canvas is no choice (unchanged).
- `canvasAutoSelect(visible, selectedId, query)` — while a query is active
  the selection follows the matches; no-op with no query or when the current
  selection already matches.
- `CanvasPanel.vue` consumes both: `v-if="selectorVisible"` and a watcher on
  `[visible, query]`.

Tests:
- `canvasUtils.spec.js`: the two pure rules.
- `canvasPanelSelectorGate.spec.js`: slices the `selectorVisible` computed out
  of the SFC and RUNS it against the ejection's numbers; pins that the
  template reads the computed, not a re-derived length test, and that the
  watcher calls `canvasAutoSelect`.
- `test_ent553_canvas_lifecycle.py`: the second review ask — the per-agent
  cap reaches the wire as a 409 through the real router → service → db
  chain (only the Redis rate limiter stubbed), names the remedy, and the same
  PUT against an existing id stays an update.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* fix(canvas): the search box outlives a shrink below the threshold (ent#553 review)

`query` has exactly one writer — the search input's `v-model` — and that
input was `v-if="showSearch"` with `showSearch = ordered.length > 6`.
Seven canvases, type "Topic 3", delete the one match: six canvases, the
box unmounts, `visible` still filters on the stale query, the strip
collapses, and the panel says *No canvas matches "Topic 3"* with no
control left to clear it. Every remaining canvas is unreachable via the
chips until navigation. Also reachable with no operator action: the
agent's own `clear_canvas` plus a rail refresh while a query is typed.

The rule is pure — `canvasSearchVisible(count, threshold, query)` — and
keeps the box while a query is active regardless of the count: the typed
intent survives the shrink, and the no-match line keeps the one control
that clears it. Resetting `query` when the box would flip off was the
other option and was rejected: it erases a search the user was mid-way
through because a sibling canvas went away.

The gate spec that pinned the previous ejection drove `visible`/`query`
in isolation from `showSearch`, which is why it could not see this one.
It now slices the real `showSearch` computed out of the SFC and RUNS it
against the ejection's own numbers (7 → 6 with "Topic 3" typed → box
stays; 6 with no query → box gone), and pins that the input is gated on
that computed and is the sole writer of `query`. Mutation-checked:
reverting the gate to the old length test reds three cases.

Four mechanical items from the same review ride along:

- requirements/core-agent.md: the ent#438 "deliberately no retention
  window: bounded by construction" line now says why that reasoning was
  wrong (rows are bounded per canvas, the count was not) and what bounds
  it instead; FR-18..FR-22 record delete / bulk / cap / pin / search,
  which had no requirements entries at all.
- raw-color-baseline.json: the `_ent553_note` naming CanvasPanel.vue's
  25 → 46 raw_gray was added in 2794388 and dropped by the dev merge
  aa248f7; re-added so the growth is named in the file.
- routers/canvas.py `# mcp:` header now says pin and bulk-delete are
  unexposed on purpose, and why — Invariant #13's deliberate-vs-forgotten
  signal.
- feature-flows/agent-canvas.md: the two search-state rules and the
  defect class they close.

Verified: vitest 2696 passed (121 files); canvas backend suites 101
passed; raw-colour ratchet and loading-gate ratchet unchanged.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RS8FBA7oEtAAv6GamZKong

* fix(canvas): a share link is a grant, so only a human may mint one (ent#554 review)

`create_canvas_share`'s docstring said "Owner-or-admin and human-only via
`_gate_human_removal`". That gate is not human-only — its own docstring, one
screen above, says an agent-scoped key may act on its own agent, which is
correct for `clear_canvas` ("an agent tidying up after itself") and wrong for
every verb that decides what someone OTHER than the agent may see.

So a prompt-injected agent could POST /api/agents/<self>/canvas/<id>/share
{"scope": "public"} with the TRINITY_MCP_API_KEY already in its container and
publish its own canvas at an unauthenticated URL. Three things make that worse
than it first reads:

* the share is LIVE, not a snapshot, so one link is a self-updating channel
  rather than a one-time disclosure;
* the agent is the only writer of canvas blocks, so anything it can read it
  can copy into a canvas and publish;
* `audience` is not consulted on the share path, so ent#438's fail-closed "a
  canvas reaches a client only because the agent said so" would not have
  applied — the agent would have been choosing for itself.

`list_canvas_shares` had the same gate and returns the TOKEN, which is the
capability itself; `revoke_canvas_share` too, so an agent could also turn off
a person's link.

The fix is the grant-vs-use line (Invariant #8): the endpoint that USES a
capability may be agent-callable, the one that GRANTS one is human-only.

* `_gate_human_only(current_user, name, *, agent_detail)` is factored out of
  `_gate_pin` — the predicate was always right, only its NAME described one
  caller. A gate named for a verb ("removal") is one a fourth caller reaches
  past by accident; a gate named for its rule is not. `_gate_pin` and the new
  `_gate_share` both delegate to it, with per-caller refusal text because an
  agent reads that message to decide what to do next.
* The three share routes now call `_gate_share`.
* The delete routes deliberately KEEP `_gate_human_removal`, and a test guards
  that boundary in the other direction — the first attempt at this fix swept
  `clear_canvas` into the human-only gate, because one `str.replace` matched
  both bodies. That would have broken a real MCP tool for every agent: a
  security fix breeding the next bug, the /review §4.14 class.

Six regression tests; four of them fail against the previous commit (the other
two are the over-correction guards, which must pass both ways by design). The
23 tests already here covered scope defaults, expiry, revocation and
enumeration, but none used an agent principal on any share route — which is how
this shipped.

Docs: the user doc now states that sharing is the owner's alone and that the
routes refuse an agent's own key, beside the same sentence for pin; the flow
doc records the decision, the blast radius, and why the delete routes stay
permissive.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

* docs(canvas): record the share routes in the file's own mcp: convention (ent#554 review)

The header comment lists which canvas routes are deliberately NOT exposed as
MCP tools and why. ent#554 added three that qualify — minting, listing and
revoking a share link — and the list did not grow with them.

Worth more than a comment here: the ent#553 entry states the rule the share
routes then failed to follow ("no tool exposes it" is a property of the
client), so a reader consulting this header to decide a fourth route's gate
would have found the reasoning but not the precedent.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

* docs(learnings): a gate named after a verb gets reached for by the wrong route (ent#554 review)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Eugene Vyborov <[email protected]>
vybe added a commit that referenced this pull request Sep 14, 2026
#2619 (ent#553) and #2623 (ent#554) both squash-landed on dev, so the stacked
base is gone. Conflicts were the parent-squash echo in the seven files this
branch touches on top of them (branch already carried both parents' final
trees) plus two docs files this branch never edits, taken from dev. The
enterprise submodule pointer is repinned to dev's commit — the branch carried
an older one from before the ent#190 bump. Tree vs dev is exactly the ent#555
delta (22 files, +685/-25).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LAFj2RWjsQWPgnq1vNT9Xm
vybe added a commit that referenced this pull request Sep 14, 2026
#2628)

* feat(canvas): delete, pin, search and a stated bound for the canvas pile

An agent that uses its canvas the way ent#438 intends accumulates dozens: one
per report, per topic, per run. The Workspace could only ever ADD to that pile
— the client-portal surface had no delete at all, the only ordering was "newest
updated", and nothing bounded the table.

Two decisions, both by operator ruling 2026-09-08, recorded because each had a
plausible alternative:

**Deleting is owner-or-admin.** The answer ent#548 gives for files — the owner
deletes the shared artifact. This NARROWS the platform DELETE route, which
accepted any user with agent access; safe because no UI called it, so no
workflow depended on the wider gate. A canvas is one shared surface with no
per-user copy, so a non-owner has no "hide it from my list" middle ground: per
AC #2 they see no control at all rather than one that 403s. Agents keep
clearing their own (`clear_canvas`, the #918 self-gate).

**The bound is a per-agent CAP, not a retention window.** ent#438 recorded "no
retention window" because the composite key bounds rows per canvas — but
`canvas_id` is agent-chosen, so the COUNT was unbounded; the axis was missed,
not decided. `CANVAS_MAX_PER_AGENT` (100, env-tunable) is checked inside
`upsert_canvas`'s insert branch, in the same transaction as the INSERT, so it
is not a check-then-act race. Updating an existing canvas is NEVER refused — a
cap that froze updates would punish exactly the agent that reuses ids — and the
refusal is a named 409 telling the agent to retire one, never an eviction:
deleting a person's surfaces on a timer is the #1638 failure direction.

Both surfaces resolve permission through `db.can_user_share_agent`, the same
predicate `assert_agent_owner` uses, so Agent Detail and the Workspace cannot
disagree about who owns an agent. The Workspace learns it from
`PortalAgentCard.can_manage_canvases` — the portal's only capability channel
(#2128), since a portal principal cannot read `/api/settings/feature-flags` —
and it fails closed.

`pinned` (dual-track: `agent_canvases_pinned` + Alembic 0058, NOT NULL DEFAULT
0, no backfill) is written only by the human pin route and is deliberately
absent from every agent-facing tool: `audience` is the agent's decision about
who may read, `pinned` is the reader's about what they see first, and an agent
that could pin itself to the top would defeat the ordering. A pin survives the
agent rewriting the canvas.

Living with many is `CanvasPanel.vue`, shared by both surfaces (one rendering
layer, per ent#475): search once the list passes six, a height-bounded strip so
a long list does not cost the rail its other tabs, and a Manage mode giving
each row its age, stale mark, pin and delete. Decidable rules are pure in
`canvasUtils.js` — vitest runs `environment: 'node'` with no mount harness, so
a rule inside the SFC is one no test can reach.

Bulk delete is a POST, not a body-carrying DELETE (bodies on DELETE are
permitted-but-unreliable and this one is not optional), declared above the
parameterized routes on both routers (Invariant #4), and it reports the ids
that EXISTED rather than the ids requested so "3 of 5 removed" is sayable.

Three pre-existing guards failed and each was right to: `empty_canvas` was
missing the new field (a real bug in this change, fixed), the self-gate guard
needed to learn the new gate's name, and the positional-read guard needed its
synthetic row extended — that one exists precisely because `_row_to_summary`
reads by index.

Tests: 20 new backend cases (cap refusal + update-at-cap, pin ordering and
survival, bulk scoping, the permission matrix on both surfaces, route ordering,
dual-track migration parity, and that the MCP tools cannot pin) and ~24 vitest
cases for the pure rules. Verified against a real database: the cap refuses the
4th of 3, updates still succeed at the cap, a pin outranks recency and survives
a rewrite, and bulk delete returns only the ids that existed.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* feat(canvas): audit the single delete, cover the default canvas, document the lifecycle

Closes the three acceptance criteria the first commit left open:

* AC #1 asked for the deletion to be audited and only the BULK route was —
  the single-canvas route is the one a person actually clicks. Logged only
  when something was removed, since the route is idempotent and a repeat
  click would otherwise fill the trail with events where nothing happened.
* AC #8: deleting the DEFAULT canvas is allowed, comes back empty on the
  next write, and frees a slot against the cap. `main` is the id both the
  MCP tools and the voice panel fall back to, so it is the one most likely
  to be deleted by accident and the one whose deletion must strand nobody.
* AC #9: the user doc gains a "Removing canvases" section stating the
  permission rule, the cap, and that nothing is ever deleted to make room.

Also records a latent pre-existing mismatch found while testing:
`empty_canvas` returns None timestamps while `models.Canvas` requires
strings, so `Canvas(**empty_canvas(...))` raises. Not live — its only
caller declares no `response_model` — but adding one there would turn the
voice teardown poll into a 500. Left as a comment where the next person to
reach for that will meet it, rather than fixed out of scope.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* feat(canvas): share a canvas at a link, and download it as a PDF

A canvas is where an agent's real output lives, and until now it could not
leave the Workspace: no share link, no export, nothing in the tree that renders
a PDF.

**Sharing never widens the audience by accident.** Two scopes, and the default
is the narrow one: `authorized` makes the link a DEEP link — opening it
requires signing in and the server re-checks `can_user_access_agent`, so it
reaches "the people who could already see it" and nobody else. `public` is an
explicit, separate, audited choice. Failing narrow is enforced in five
independent places (column default, Pydantic default, `normalize_scope`'s
fallback, the order of `SHARE_SCOPES`, the radio the dialog preselects),
because a link that reaches further than the sharer understood is the one
failure this feature must not have.

**`agent_canvas_shares` is deliberately its own table.** `agent_public_links`
has a `type` column that looks purpose-built for this, and reusing it would
have been a real vulnerability: nothing in that table's read path filters on
type — `get_public_link_by_token`, `is_link_valid` and
`routers/public.py::_validate_public_link` all resolve a token whatever it is —
so a canvas row there would ALSO be a working public-CHAT token, and anyone
sent a canvas could talk to the agent. (`type='site'` is the same trap already
laid; it is unexploited only because nothing creates those rows today.) A
separate table makes the isolation structural instead of dependent on every
consumer remembering to check.

**Live, and it says so** (AC #3, operator ruling): the link renders the canvas
as it is now, carrying its `updated_at` and stale mark, and the page states it
is not a copy taken at share time. That follows ent#438's model — a canvas is a
surface an agent keeps current — and means a share stores nothing. The cost is
drift after sharing; the mitigation is revocation, not freezing.

**Revocation keeps the row.** `revoked_at` is stamped, never deleted, because a
revoked link has to be able to SAY it was revoked (AC #2), which it cannot do
once the row is gone. The status vocabulary splits along disclosure: `revoked`
and `expired` are returned only for a token that MATCHED a row — whoever holds
such a link was already told the canvas exists — while an unknown token and a
canvas deleted out from under a link both collapse into one `not_found`, so a
stranger guessing tokens learns nothing from the difference. An unparseable
`expires_at` reads as expired: a lifetime we cannot read is one we cannot
promise is live.

**PDF is print-first**, the path the issue recommended: a print stylesheet plus
the browser's own PDF. No headless service to run, and — the deciding reason —
no second renderer to keep in step with `CanvasBlock`. A server-side renderer
was the stated fallback and was not needed: pagination (`break-inside: avoid`
per block) and fidelity both fall out of the same markup the screen uses.
`CanvasDocument.vue` is the one printable form, rendered by both the shared
page and every authenticated surface, so AC #7's "identical from every canvas
surface" is true by construction rather than by three surfaces agreeing. It
carries title, agent and generation date, forces the light rendering under
`@media print`, and when `window.print` is unavailable the control says so and
the share link still works.

`ent#425` (hosted deliverable pages) is still open, so per this issue's own
boundary rule this ships the narrower share link and #425 adopts it later.

Verified against a real database, not stubs: the full resolution matrix
(public/anonymous → ok, authorized/anonymous → sign-in, authorized/owner → ok,
authorized/stranger → refused, unknown → not-found, revoked, expired,
unparseable expiry → expired, canvas deleted → not-found), views counted only
on a successful render, cross-agent revoke refused, and a second revoke keeping
the first revocation time.

23 backend tests, 20 vitest cases for the pure rules.

Related to Abilityai/trinity-enterprise#554

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* test(canvas): patch the cap where the live code reads it, not where the test imports it

Two ent#553 tests passed in isolation and failed in a full-suite run:
`test_the_cap_refuses_a_new_canvas_by_name` and
`test_deleting_the_default_canvas_frees_a_slot_against_the_cap`.

Order-dependence, not a defect in the feature. They patched
`db.canvas.CANVAS_MAX_PER_AGENT` via a fresh `import db.canvas`. Some earlier
test in the suite evicts that module from `sys.modules`, so the fresh import
hands back a NEW module object while the live `db._canvas_ops` is still an
instance of the OLD class — whose `upsert_canvas` reads the OLD module's
globals. The patch lands somewhere nothing consults, the cap stays at its
default of 100, and the "refuses the 4th of 3" assertions fail.

`_set_cap` patches the bound method's own `__globals__`, which is whichever
module dict the running code actually closes over — correct whether or not an
eviction happened, so it does not depend on knowing which test pollutes.

Same failure and same fix as #2589, where the identical shape bit
`mark_stale_activities_failed`. Worth noting the class: a monkeypatch on a
module attribute is only as good as the assumption that the live object came
from that module object, and in a suite that evicts modules that assumption is
not free.

The feature is unchanged — this touches only the test file.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* fix(canvas): print the canvas, not the whole page

Reported from hands-on testing: pressing PDF offered to export the entire page.
Correct report — the print stylesheet only STYLED the document and never hid
anything else, so `window.print()` printed the nav bar, the tabs, the
on-screen panel AND the print copy. That is not "one clean column" by any
reading (AC #4), and it is the first thing anyone pressing the button hits.

Two halves, both required:

* a print rule that hides every `body` child except `.canvas-print-root`;
* the print copy TELEPORTED to <body>, so it is a body child and the rule can
  spare it. Nested inside the app the rule would hide its ancestor and print
  nothing at all — worse than the bug.

`body > *` rather than a class on the app root: it needs no knowledge of how
the app is mounted and works identically on the standalone shared page, which
keeps AC #7's "identical from every surface" true rather than approximately
true. The copy is rendered only while printing (`v-if="printing"` + a
`nextTick` flush before `print()`, since printing a not-yet-rendered teleport
yields a blank sheet), so the DOM carries no permanent hidden duplicate.

`canvasPrintIsolation.spec.js` pins all three structural facts. Nothing
automated can inspect a print preview, which is exactly why the bug shipped —
so the guard asserts the mechanism instead: the hiding rule exists, the root is
teleported to body, and the document mounts before print() is called.
Mutation-tested: removing the hiding rule fails it.

Also fixes a design-system violation the ratchet caught in the same file:
`SharedCanvas` gated its skeleton on a bare `v-if="loading"`. Now
`viewState()` — loading means "no data yet", never "a fetch is in flight"
(#1927, design-system p13-p15). The page fetches once today, so this is the
rule holding rather than a bug fixed; it stays correct if a refresh is added.
Baselining my own new violation was the alternative and would have been the
wrong one.

Related to Abilityai/trinity-enterprise#554

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* feat(canvas): the open canvas is shared context for the turn

When a user with a canvas on screen says "add a column to this", the agent now
knows which canvas they mean. Before this the turn carried the message and
nothing about the surface around it, so the agent asked, guessed, or minted a
new canvas beside the one being looked at.

The mechanism is a per-turn context field — `schedule_executions.open_canvas_id`,
the same shape as the `source_channel*` columns beside it — stamped at dispatch
and read back by the tools and the prompt.

It is CONTEXT, never AUTHORITY, and two independent halves keep it there:

  - `validated_open_canvas` decides what may be STAMPED. The id is
    client-supplied, so it is checked against the agent's own canvases and
    against what that caller can see: an operator-only canvas is invisible to an
    external client (otherwise the field is an existence oracle for canvases the
    agent keeps privately), and another agent's canvas is refused outright.
    Every failure degrades to "nothing open" — never an error, never a wider
    reach.
  - `effective_canvas_id` decides what a tool ACTS on, and cannot widen
    anything: every read and write still passes the existing ownership and
    audience gates.

Precedence is stated once so all three tools agree:
`explicit canvas_id > the canvas the user has open > the default canvas`. It
returns WHY as well as WHICH, because with nothing named the agent has to be
able to say which canvas it wrote to — "I updated the canvas" is not good enough
when there are eight and the user is looking at one.

Both delivery paths are needed, not one. The MCP tools resolve a missing
`canvas_id` through `GET /api/agents/{name}/canvas/context` (declared above
`/{canvas_id}` — Invariant #4, since "context" is a valid id shape), AND the
turn prompt names the open canvas: a tool default handles a call that omits an
id, but an agent must READ a canvas before editing it and cannot read what it
cannot name. The prompt line rides the same prefix as the file manifest, so it
is present on a resumed turn too — the open canvas changes between turns while
the session's memory of it does not.

A canvas deleted mid-conversation resolves to nothing, re-checked at read time
rather than trusted from the stamp: ent#553 made deleting one click, and a
surviving id would have the agent's next write CREATE a canvas under it,
silently resurrecting something a person deleted.

Voice inherits this by construction — ent#440 submits a spoken utterance through
the same `deliver()` a typed one takes. The `canvas` tools in `gemini_voice.py`
are deliberately untouched: that is VOICE-001's ephemeral display panel, a
different surface with no persisted id.

Dual-track migration (`execution_open_canvas` + Alembic `0060`); the column is
nullable, so every existing row and every un-updated caller reads as "nothing
open".

Related to Abilityai/trinity-enterprise#555

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01CdxGmvuKuqaWJZ6pKUgaUJ

* fix(canvas): re-parent the pinned revision, and make the canvas cap reachable

Two review items from #2619.

**Alembic head fork (#2068 class).** `0058_agent_canvases_pinned` shared
`down_revision = 0057` with #2608's `0058_portal_file_dismissals`, which has
since landed on `dev` — two heads, and `alembic upgrade head` resolves its
single target before applying anything, so EVERY revision merged since the
fork stops arriving, not just one. Re-parented onto
`0058_portal_file_dismissals` and renumbered to `0059` so the prefix keeps
being a usable ordering cue; the id is not applied anywhere yet, so the
rename costs nothing. `check_alembic_heads.py` reports 1 head.

**`CANVAS_MAX_PER_AGENT` was inert (#1039 class).** The refusal message names
the number, but the variable was read only from `os.getenv` in `models.py` and
appeared in no compose file — so an operator following the refusal's own advice
would raise a lever that never reaches the container. Wired into
`docker-compose.yml`, `.prod.yml` and `.hosted.yml` (the last two launch
standalone, no base merge / no `env_file`) plus `.env.example`.

Related to #2619

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP

* chore(design-system): re-freeze CanvasPanel's raw-gray ceiling for ent#553

The raw-colour ratchet became enforceable on dev while this branch was
open (#2605/#2609), and the merge brings it here: this PR's delete/pin/
search chrome takes `components/canvas/CanvasPanel.vue` from 25 to 46
`raw_gray`, so `tests/unit/rawColorRatchet.spec.js` fails the frontend
build.

That growth is the honest kind. The design-system contract SPELLS the
neutral ink ladder as `gray-N` — surfaces gray-50/100/800/900, borders
gray-200/300/700/800, ink gray-300/400/500/600 — and there is no
semantic token for a neutral, which is exactly why the spec's own
comment says gray is ratcheted but never held to zero for new files.
The rule it does hold new code to is `raw_nongray`, and this file stays
at **0**.

Re-frozen in its OWN commit with the increase named in the baseline's
`refrozen` block, which is what the ratchet's error message asks for —
not absorbed silently into the feature diff. The entry is hand-edited
rather than regenerated so #2605's provenance block survives; no other
file's ceiling moves (verified: nothing grew, nothing is stale, no
un-baselined file carries `raw_nongray`).

Related to #553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Bd71qsYbFodvofba8P69eP

* fix(canvas): state the bound, audit the Workspace writes, gate Manage on ownership (ent#553)

Three review findings, all in the same direction — the backend was right and
the user-facing half did not arrive — plus the two smaller ones.

1. **The stated bound now reaches the user.** `canvasLimit` was a `ref(0)`
   nothing ever assigned, so `canvasHeadroom(n, 0)` returned `{label: null}` and
   the early warning could not render at any count. The ceiling rides
   `GET /api/settings/feature-flags` as `canvas_max_per_agent` — the established
   home for a value the browser needs to render a surface, and where
   `platform_default_model` / `install_source` already set the precedent for a
   non-boolean. Not a new route (Invariant #13 would owe three surfaces for one
   integer) and not an envelope around the canvas list (the MCP tool and the
   Workspace both read it as a bare array). It is a CONSTANT, not per-agent
   state, and the client already holds the count. `0` still means "not told" and
   still renders nothing, so an older backend is unchanged.

2. **The Workspace canvas writes are audited.** The three portal routes recorded
   nothing while their operator twins have logged since they shipped, and
   `docs/user-docs/agents/agent-canvas.md` tells users deletion is audited — so
   the claim was false for exactly the client-facing surface. `_audit_canvas_change`
   is the shared helper; the actor is `actor_email` (the documented #848
   inline-auth path) rather than a fabricated `User`, which is honest because
   `_require_canvas_manager` is platform-only and owner-or-admin, so a real
   Trinity user is always behind it. Ids and counts only (G-04). The three
   routes become `async def` to await it, matching their operator twins, which
   already call the same sync db functions from an async handler.

   Pinning is audited too, on BOTH surfaces — the operator route was the one
   recording nothing. A pin decides which canvas an entire roster sees first, so
   it is an administrative act on a shared surface, not a per-viewer preference.

3. **`canManage` comes from the parent.** It was hardcoded `true` on the
   argument that the server decides. It does — but a merely-shared user was then
   shown Manage → Delete / Pin and got a 403, which is the failing-control
   problem `can_manage_canvases` exists to prevent on the Workspace. Agent
   Detail passes `agent.can_share`, the same predicate `ReportsPanel` five lines
   above already reads and the same one `_gate_human_removal` enforces. The prop
   defaults FALSE, so a caller that forgets it hides an affordance rather than
   offering one that refuses.

4. **`get_agent_card` resolves `can_manage_canvases`.** It omitted it, so the
   same owner read `true` in the sidebar and `false` on the agent's own page —
   the disagreement #2160's own docstring says that function exists to prevent.

5. **An agent genuinely cannot pin its own canvas now.** The user doc said so;
   `_gate_human_removal` allowed it (right for delete — an agent tidying up
   after itself — and wrong for pin), and "no MCP tool exposes it" is a property
   of the client, not of the route. `_gate_pin` is humans-only, which makes the
   documented sentence true rather than aspirational.

Tests: the audit guard now walks the portal routes as well as `routers.canvas`
(it only ever inspected the latter, which is why three unaudited routes passed
it), plus pin-audit parity, the humans-only pin gate beside the still-permitted
agent self-delete, the feature-flags constant being the same object the refusal
is raised from, the agent-card/roster agreement, and four frontend wiring cases.

1025 backend / 2538 frontend tests green.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN

* fix(canvas): the Workspace audit names the operator, not the platform (ent#553)

Found re-reviewing my own audit fix. Adding the rows was right; the attribution
was wrong, and a row that lands under the wrong actor is worse than the missing
row it replaced — nothing fails, so the wrong answer is believed.

`_audit_canvas_change` passed `actor_email` only. But
`platform_audit_service._resolve_actor` derives `actor_type` from
`actor_user` / `actor_agent_name` / `mcp_scope` / `mcp_key_id` and never from
the email, so an email-only call falls through to its last branch:

    _resolve_actor(None, None, None, None) -> ("system", "trinity-system", None)

So every Workspace canvas delete and pin was recorded as `actor_type="system"`,
`actor_id="trinity-system"` — a named operator's action attributed to the
platform, invisible to any `actor_type=user` query and to the audit UI's
per-actor filter. Verified against the real resolver, not by reading the call.

The `actor_email`-only path I cited (#848 inline auth) is right where the caller
genuinely has no `users` row. That is not this route: `_require_canvas_manager`
is platform-only and resolves through `db.can_user_share_agent`, so a row exists
by construction. It now resolves that row and passes `actor_user`, producing the
same `("user", <id>, <email>)` shape the operator twin has always written —
which is the point, since auditing the two surfaces differently buys little more
than auditing one of them.

Best-effort by construction: the action has already happened, so a lookup that
raises or misses must not drop the row. It falls back to the email-only call
with a WARNING, since a miss would mean the gate admitted someone the user table
does not know.

Tests: the regression is pinned against the REAL `_resolve_actor` (both the
shape the fix must not return to and the shape it produces now), plus a source
guard that the helper resolves a row, passes `actor_user`, keeps the email as a
fallback and cannot raise. Removing `actor_user=` reds it.

31 passed on the ent#553 file; 953 across canvas / portal / audit.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RSjVEjay9ztC1oDXXkh9uN

* fix(migrations): chain 0060_agent_canvas_shares off the renamed pinned revision

ent#553 renamed its revision 0058_agent_canvases_pinned -> 0059 when it
absorbed dev's 0058_portal_file_dismissals; this revision still pointed at
the old id, so after the merge the directory resolved to two heads and
`alembic upgrade head` would have applied nothing. Renumbered to 0060 as
well so the numeric prefix stays a unique ordering cue.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* chore(frontend): re-freeze CanvasPanel.vue raw_gray 46 -> 62 for ent#554

The share/PDF controls add gray chrome copied from the panel's existing
header; the branch predates the #2605 ratchet, so the guard first bit when
dev was merged in. Scoped to this one entry, in its own commit, as the
guard's own message prescribes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* fix(migrations): renumber execution_open_canvas to 0061 behind 0060_agent_canvas_shares

Follows the ent#554 renumber so the chain reads 0059 pinned -> 0060 shares
-> 0061 open-canvas with unique prefixes and a single head.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* test(canvas): resolve CanvasLimitExceeded from the live method's globals

The two cap tests imported the class from `db.canvas` while `_set_cap` already
patches the cap through `upsert_canvas.__globals__` — because an earlier test
can evict and re-import the module. The same eviction gives the test a
different class object than the one the live code raises, and `pytest.raises`
then reports the correct refusal as an unexpected exception. Seen once in a
full local run after the dev merge (both tests pass in isolation and under
CI's three seeds); resolve the class from the same globals the cap comes from.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* fix(canvas): keep the selector visible when a search narrows to one match (ent#553 review)

`CanvasPanel.vue` gated the chip strip on `visible.length > 1 || manage`,
where `visible` is the FILTERED list. Searching down to exactly one canvas
hid the strip while the previously selected canvas stayed on screen, and the
auto-select watcher — keyed off the unfiltered `props.canvases` — never
selected the match. Proven by execution: 7 canvases, query "Topic 3" → strip
false, no-match message false. The one canvas the user just searched for was
unreachable.

Fix:
- `canvasSelectorVisible({visible, manage, query})` — with a query, any hit
  shows the strip; without one, a single canvas is no choice (unchanged).
- `canvasAutoSelect(visible, selectedId, query)` — while a query is active
  the selection follows the matches; no-op with no query or when the current
  selection already matches.
- `CanvasPanel.vue` consumes both: `v-if="selectorVisible"` and a watcher on
  `[visible, query]`.

Tests:
- `canvasUtils.spec.js`: the two pure rules.
- `canvasPanelSelectorGate.spec.js`: slices the `selectorVisible` computed out
  of the SFC and RUNS it against the ejection's numbers; pins that the
  template reads the computed, not a re-derived length test, and that the
  watcher calls `canvasAutoSelect`.
- `test_ent553_canvas_lifecycle.py`: the second review ask — the per-agent
  cap reaches the wire as a 409 through the real router → service → db
  chain (only the Redis rate limiter stubbed), names the remedy, and the same
  PUT against an existing id stays an update.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015owqMKD5QDjzZrUTF2Joht

* fix(canvas): the search box outlives a shrink below the threshold (ent#553 review)

`query` has exactly one writer — the search input's `v-model` — and that
input was `v-if="showSearch"` with `showSearch = ordered.length > 6`.
Seven canvases, type "Topic 3", delete the one match: six canvases, the
box unmounts, `visible` still filters on the stale query, the strip
collapses, and the panel says *No canvas matches "Topic 3"* with no
control left to clear it. Every remaining canvas is unreachable via the
chips until navigation. Also reachable with no operator action: the
agent's own `clear_canvas` plus a rail refresh while a query is typed.

The rule is pure — `canvasSearchVisible(count, threshold, query)` — and
keeps the box while a query is active regardless of the count: the typed
intent survives the shrink, and the no-match line keeps the one control
that clears it. Resetting `query` when the box would flip off was the
other option and was rejected: it erases a search the user was mid-way
through because a sibling canvas went away.

The gate spec that pinned the previous ejection drove `visible`/`query`
in isolation from `showSearch`, which is why it could not see this one.
It now slices the real `showSearch` computed out of the SFC and RUNS it
against the ejection's own numbers (7 → 6 with "Topic 3" typed → box
stays; 6 with no query → box gone), and pins that the input is gated on
that computed and is the sole writer of `query`. Mutation-checked:
reverting the gate to the old length test reds three cases.

Four mechanical items from the same review ride along:

- requirements/core-agent.md: the ent#438 "deliberately no retention
  window: bounded by construction" line now says why that reasoning was
  wrong (rows are bounded per canvas, the count was not) and what bounds
  it instead; FR-18..FR-22 record delete / bulk / cap / pin / search,
  which had no requirements entries at all.
- raw-color-baseline.json: the `_ent553_note` naming CanvasPanel.vue's
  25 → 46 raw_gray was added in 2794388 and dropped by the dev merge
  aa248f7; re-added so the growth is named in the file.
- routers/canvas.py `# mcp:` header now says pin and bulk-delete are
  unexposed on purpose, and why — Invariant #13's deliberate-vs-forgotten
  signal.
- feature-flows/agent-canvas.md: the two search-state rules and the
  defect class they close.

Verified: vitest 2696 passed (121 files); canvas backend suites 101
passed; raw-colour ratchet and loading-gate ratchet unchanged.

Related to Abilityai/trinity-enterprise#553

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RS8FBA7oEtAAv6GamZKong

* fix(canvas): a share link is a grant, so only a human may mint one (ent#554 review)

`create_canvas_share`'s docstring said "Owner-or-admin and human-only via
`_gate_human_removal`". That gate is not human-only — its own docstring, one
screen above, says an agent-scoped key may act on its own agent, which is
correct for `clear_canvas` ("an agent tidying up after itself") and wrong for
every verb that decides what someone OTHER than the agent may see.

So a prompt-injected agent could POST /api/agents/<self>/canvas/<id>/share
{"scope": "public"} with the TRINITY_MCP_API_KEY already in its container and
publish its own canvas at an unauthenticated URL. Three things make that worse
than it first reads:

* the share is LIVE, not a snapshot, so one link is a self-updating channel
  rather than a one-time disclosure;
* the agent is the only writer of canvas blocks, so anything it can read it
  can copy into a canvas and publish;
* `audience` is not consulted on the share path, so ent#438's fail-closed "a
  canvas reaches a client only because the agent said so" would not have
  applied — the agent would have been choosing for itself.

`list_canvas_shares` had the same gate and returns the TOKEN, which is the
capability itself; `revoke_canvas_share` too, so an agent could also turn off
a person's link.

The fix is the grant-vs-use line (Invariant #8): the endpoint that USES a
capability may be agent-callable, the one that GRANTS one is human-only.

* `_gate_human_only(current_user, name, *, agent_detail)` is factored out of
  `_gate_pin` — the predicate was always right, only its NAME described one
  caller. A gate named for a verb ("removal") is one a fourth caller reaches
  past by accident; a gate named for its rule is not. `_gate_pin` and the new
  `_gate_share` both delegate to it, with per-caller refusal text because an
  agent reads that message to decide what to do next.
* The three share routes now call `_gate_share`.
* The delete routes deliberately KEEP `_gate_human_removal`, and a test guards
  that boundary in the other direction — the first attempt at this fix swept
  `clear_canvas` into the human-only gate, because one `str.replace` matched
  both bodies. That would have broken a real MCP tool for every agent: a
  security fix breeding the next bug, the /review §4.14 class.

Six regression tests; four of them fail against the previous commit (the other
two are the over-correction guards, which must pass both ways by design). The
23 tests already here covered scope defaults, expiry, revocation and
enumeration, but none used an agent principal on any share route — which is how
this shipped.

Docs: the user doc now states that sharing is the owner's alone and that the
routes refuse an agent's own key, beside the same sentence for pin; the flow
doc records the decision, the blast radius, and why the delete routes stay
permissive.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

* docs(canvas): record the share routes in the file's own mcp: convention (ent#554 review)

The header comment lists which canvas routes are deliberately NOT exposed as
MCP tools and why. ent#554 added three that qualify — minting, listing and
revoking a share link — and the list did not grow with them.

Worth more than a comment here: the ent#553 entry states the rule the share
routes then failed to follow ("no tool exposes it" is a property of the
client), so a reader consulting this header to decide a fourth route's gate
would have found the reasoning but not the precedent.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

* docs(learnings): a gate named after a verb gets reached for by the wrong route (ent#554 review)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01Q19uRCksdn4DiRAJ55rfpZ

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Eugene Vyborov <[email protected]>
dolho added a commit that referenced this pull request Sep 15, 2026
… 903 dev lines into the split packages

The modify/delete conflicts on `routers/settings.py` and
`services/git_service.py` are resolved by DELETING dev's monolith copies and
re-porting every hunk dev added to them since the fork into the file that
now owns it, symbol by symbol, with each function's body checked equal to
dev's modulo package qualification:

git_service (one dev commit, ent#615 / #2757 — the fleet-PAT fix):
  - `_AUTH_PATTERNS` marker            -> conflicts.py
  - `_git_remote_url` removed, `_remote_seturl_subcommand` docstring,
    `_credentialless_remote_url`, `rebind_origin_and_push` (root push +
    credential in the exec env), `update_remote_pat` (env write, not URL)
                                        -> remotes.py
  - the credential-helper install + embedded-token sweep block
    (`write_container_github_pat`, both alarms, `scrub_git_remote_tokens`,
    the fleet sweep, `spawn_git_remote_token_scrub`, all `_SCRUB_*`)
                                        -> NEW token_scrub.py (remotes.py
    would otherwise sit at 821 lines, over the threshold the split exists for)
  - `_agent_can_push`, `_agent_has_write_credentials` docstring,
    `sync_to_github`, `reset_to_main_preserve_state`   -> sync.py
  - `initialize_git_in_container` (seeds before writing a remote)
                                        -> provisioning.py
  Package `__init__` re-exports every new name; the duplicate
  `REBIND_PUSH_TIMEOUT_S` the hunk would have introduced is dropped.

settings (five dev commits — #2715, #2619, #2707, #2741, #2739):
  - 11 changed routes replaced in place across flags/credentials/
    integrations/generic
  - 11 new symbols placed beside their dev-order predecessors; the #2715
    Resend/Gemini routes + their two helpers go to NEW provider_keys.py
    (credentials.py would otherwise reach 1,045 lines), included on the
    package router right after `credentials` and before `generic`
  - `_ANTHROPIC_KEY_ALIASES` / `_adopt_after_instance_key_removed` reached
    from generic.py through the sibling module object, per the package rule

ops: `_format_model_name`'s #2739 `claude-fable-5-1` entry lands in
`ops_costs_service.py`, where the split moved the function; the #2726
test imports from there.

Dev's tests that patch monolith attributes are re-pointed the way the
split re-pointed every earlier one: the ent#615 exec recorder is installed
on each execing sibling and `_detect_git_dir` on `gitignore`; #2572's `db`
fake on `credentials` and `generic`; ent#553's source read on `flags`;
#1677's emitter allowlist and the ent#615 source reads on `token_scrub`.
`_PRE_SPLIT_ROUTES`' post-split allowlist records the six #2715 routes; the
git_service import-surface pin drops `_git_remote_url` (gone by design) for
its ent#615 replacements.

Content conflicts: `backend.md` (dev's facts under the package names),
`test_ent123_tokenless_clone.py` (dev's helper patch, on `gs.sync`).

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants