Repository navigation
[pull] main from Abilityai:main - #25
Merged
Merged
Conversation
* test(e2e): List-mode spec + five specs adjusted for the retired Agents page (ent#260) NEW dashboard-list-view.spec.js: system-row render (data-agent hooks, SYSTEM badge, detail link; deliberately no toggle-visibility assertions — CI's only agent is the guarded system agent), AC-4 mode persistence, AC-2 redirect (param stripped, saved mode NOT rewritten), ?onboarding=1 survives the redirect + opens the wizard, name-filter narrowing + filtered-empty Clear-all recovery, three-mode round-trip. smoke.spec.js: Agents nav-link assertion dropped (nav list comment updated); 'agents page loads' becomes the redirect assertion. browser-tab-titles: the Agents hop removed from the SPA chain (Dashboard → Templates still proves the client-side repaint); /agents → 'Trinity — Dashboard' joins the redirect-title test. dashboard-grid-view: header comment (three modes; exact-name toggle selectors unaffected). dashboard-stats-overflow: 'list' added to MODES — the third toggle + chassis Create button widen the controls cluster in every mode. navbar-overflow test 3: the 640px squeeze branch is now conditional on the MEASURED overflow (4-link OSS bar may fit where 5 links overflowed; an entitled build still exercises the scroll-recovery branch) — sm=640 is the floor, below it the link row hides, so narrowing further was not an option. Full e2e run defers to CI (frontend-e2e on the ui label) — the live local stack is not exercised from this worktree. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: Dashboard List view — architecture block, new feature flow, index + superseded banner (ent#260) architecture.md: Grid-view paragraph reworded to three modes; new Dashboard List view block (AgentListPanel extraction, visibleAgents seam ownership, N+1 deletion, redirect + NavBar consolidation, zero backend change). NEW feature-flows/dashboard-list-view.md (overview, data-flow diagram, decisions D1/D2/D7/D8/D11 + the two flagged plumbing calls, teardown state-loss note, testing). dashboard-grid-view.md mode-count wording. agents-page-ui-improvements.md superseded banner (kept as history). feature-flows.md: List-view index row, Agents-page row → superseded pointer, changelog entry. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): repoint cross-cutting flow docs off the retired Agents page (ent#260) /sync-feature-flows coverage pass over the full branch diff: eleven flow docs carried live current-state claims about views/Agents.vue (avatar/toggle/meter usage tables, sync-health dot renderer, system-agent display, tag bulk-ops entry points, skills-on-start entry, dark-mode coverage row, timeline-view mode-toggle description). Live references now point at components/AgentListPanel.vue / the Dashboard chassis; dated changelog entries and explicitly-labelled historical sections are left as history. Also fixes dashboard-timeline-view.md's pre-existing stale '[Graph] [Timeline]' toggle claim to the current three-mode set. Touched: agent-avatars, agent-lifecycle, agent-tags, autonomy-mode, autonomy-toggle-component, dark-mode-theme, dashboard-timeline-view, git-sync-health, internal-system-agent, parallel-capacity, read-only-mode, skills-on-agent-start. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(dashboard): review fixes — Create-button icon-only degrade + gated fetch write-through (ent#260) Two review-stage fixes on the ent#260 branch: 1. Create Agent label degrades to icon-only below `md` (title + aria-label kept). The controls cluster is flex-shrink-0; measured against the #1830 stats-ladder constants (agents-only floor 71px), the full label at 640px in grid mode (+ the third mode button) leaves ~47px — the stats-overflow spec's clip assertion would fire. This is the plan's pre-decided degrade, applied ahead of CI. 2. The fetchAgents → agentsStore.agents write-through is now gated on no active quick-tag filter (params.tags narrows the response server-side; a filtered subset must not clobber the full-fleet list agentsStore consumers read — the Executions dropdown's cold-start self-heal is length===0-gated and never recovers from a non-empty wrong value) and writes a shallow copy (array identity per store, shared row objects so in-place status/label patches still propagate). Docs synced (architecture block, flow doc, agents.js contract comment) + a learnings.md entry for the write-through class. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): §9.9 seam wording matches the implemented deviation (ent#260) The plan's D8 wired both convertAgentsToNodes call sites through the visibleAgents computed; the implementation deliberately deferred the timeline wiring to ent#261 (ReplayTimeline :agents prop switch — rewiring the node paths was rejected as timeline-mutation risk) and the code comment + flow doc + architecture all record that. §9.9 still claimed the node-rebuild call sites consume the seam — align it. Co-Authored-By: Claude Fable 5 <[email protected]> * refactor(frontend): rename Templates.vue to Library.vue (pure move) (ent#263) Byte-pure git mv with zero content edits so git rename detection holds and a parallel edit to Templates.vue (ent#260) resolves as a content merge inside Library.vue rather than a modify/delete conflict. All content changes land in follow-up commits. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(frontend): Library page + route/nav rename with /templates redirect (ent#263) - Library.vue: h1 'Library', new subtitle, templates content wrapped in an 'Agent Templates' section (own loading/error/empty states; inner headings demoted h2->h3); fetch migrated to the shared api client (Invariant #7) - router: /library route (meta.title Library) + /templates function-form redirect carrying query AND hash; route name Templates->Library (no named pushes exist) - NavBar: label Library, to=/library, active via startsWith('/library') - CreateAgentModal: its single raw-axios /api/templates call migrated to the shared api client so no half-migrated consumer of the endpoint remains Page-identity naming only (AC#4 reading): the asset-kind noun 'template' survives inside the Library (Starter/GitHub Templates sections, Use Template). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(frontend): Library skills section — fleet browse over the skills library (ent#263) - stores/skillsLibrary.js (new): fleet-scoped store, deliberately separate from stores/skills.js (KeepAlive-cached AgentDetail means SkillsPanel's clear() never fires on nav-away — shared refs would poison the cached tab); imports nothing from stores/skills.js. 4-state emptyReason discriminator (unconfigured/not_cloned/empty + error carried separately); sync() with a 180s timeout and ECONNABORTED -> status-refetch (a first clone can outlive the 30s api.js default; client timeout != server failure) - components/LibrarySkillsSection.vue (new): sync-state header leads with commit_sha + skill_count (disk-derived; last_sync is per-worker in-memory and renders only when truthy); repo URL admin-only, userinfo-stripped, labeled 'Primary source', hidden when status.sources reports >1 (#1901 forward-compat); admin Sync now; per-kind empty states teaching the next action; dormant source_name/shadowed_by slots; interpolation only - components/skills/{SkillContractChips.vue,contract.js} (new): the #183 contract-chips seam extracted from SkillsPanel so both the per-agent tab and the Library browse render package facts from one seam - SkillsPanel.vue: consumes the shared seam (local SkillMeta/formatBytes/deps removed); stores/skills.js untouched - Library.vue: skills section wired in + header jump anchors (no ?kind=) Co-Authored-By: Claude Fable 5 <[email protected]> * test: Library e2e anchors + remove dead template-endpoint tests (ent#263) - smoke.spec.js: '@smoke library page loads' asserts chrome-only getByRole headings (h1 Library + both section headings — the old getByText(/template/i) passed on the un-renamed page and proved nothing); new '@smoke templates path redirects to library'; stale nav comment fixed (Health/Ops merged in #1109) - browser-tab-titles.spec.js: nav click asserts 'Trinity — Library'; redirect test also covers /templates -> /library title resolution - tests/test_templates.py: remove TestEnvTemplate + TestTemplateRefresh — GET /api/templates/env-template and POST /api/templates/refresh no longer exist (router has exactly 2 GET routes; live-stack probe returns 404); test_get_template_by_id now exercises the REAL detail endpoint instead of the dead env-template detour that always skipped. 5 remaining tests pass against the live stack. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: Library page — requirements, architecture, feature flow, stale-endpoint rot sweep (ent#263) - requirements/core-agent.md: new §4.5 Library Page — unified /library surface (agent templates + fleet skills browse), query+hash-preserving /templates redirect, stacked sections, per-kind empty states, the AC#4 page-identity naming rule; fleet assignment visibility named as Not Built - requirements/skills.md (surgical — §21.3/§22.2/new §22.3 only, avoiding PR #1901's §21.1/§21.5 hunks): §21.3 stale 'Skills tab is hidden' note corrected (visible since ent#235/PR #1877); §22.2 rewritten as visible/rebuilt; new §22.3 Library Page fleet skills browse — browse-only over the existing /api/skills/library reads, own skillsLibrary store + the KeepAlive rationale, admin-only URL/Sync, #1901 forward-compat, assignment read = Not Built - architecture.md: 'Top-nav IA — Library (ent#263)' paragraph beside the #1109 Operations one; stale 'Templates (4 endpoints)' table corrected to the 2 real routes (POST /refresh AND GET /env-template both verified absent) - feature-flows: templates-page.md git-mv'd to library-page.md + full rewrite (the old file was deeply stale — AgentSubNav, dead endpoints); index row + platform-settings.md Related-Flows link repointed - template-processing.md + CREDENTIAL_MANAGEMENT.md: dead env-template endpoint references removed/replaced (same rot class as the architecture table); Templates.vue references repointed at Library.vue - user docs (creating-agents.md, faq/agents.md): Templates page → Library (+ redirect note) Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): TGRAM-PROGRESS — Telegram in-progress status indicator (ent#264) New §15.1h: reaction ack + elapsed-time placeholder + channel-agnostic start/progress/resolve seam, group gating (mention/reply OR all-mode; observe stays silent), degradation ladder, default-ON per-binding toggle, GET /telegram access hardening. §15.1c/§15.1e touch-ups. Requirements-first per Rules of Engagement #1. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(channels): in-flight progress indicator seam + Telegram reaction ack and elapsed-time placeholder (ent#264) Channel-agnostic start/progress/resolve seam (Invariant #9): - base.py: default-no-op indicate_progress hook + progress_threshold_seconds/ progress_interval_seconds capability attrs (None => the router never arms a driver, so Slack/WhatsApp/VoIP behave byte-identically). - message_router.py: router-owned per-turn driver — _arm_progress_driver after step 8 (call + arm wrapped so a raising hook can never abort the turn), _progress_loop (elapsed origin captured BEFORE the threshold sleep; per-tick try/except), _resolve_indicator at all three terminals (cancels AND awaits the driver dead, settles the shielded in-flight placeholder send, THEN indicate_done — closes the tick-after-resolve and resolve-vs-first-send races by construction; carries success for the adapter's neutral fallback line), and an idempotent try/finally _cancel_progress_driver backstop. - telegram_adapter.py: indicate_processing upgraded (single binding read, per-turn cfg stash, typing preserved verbatim, 👀 reaction ack — gated on the default-ON per-binding toggle and ack-eligibility; whole body never raises); NEW indicate_progress (placeholder send-then-edit, message_id recorded INSIDE the shielded helper, disable_notification, explicit HTML, 2-consecutive-failure degraded flag over sends/edits/timeouts alike) and indicate_done (clear reaction at every terminal — no success-👍 swap; delete placeholder, neutral edit-to-done fallback); fail-soft primitives _set_message_reaction/_edit_message_text/_delete_message/ _send_placeholder_message mirroring _send_message's shape (429 retry_after capped 30s; never log the token-bearing URL). - parse_message stashes progress_ack_eligible: DMs, @mention/reply group turns, and `all`-trigger-mode groups; observe mode stays typing-only. - All per-turn state on NormalizedMessage.metadata (the adapter is a shared singleton); decrypt_telegram_bot_token facade passthrough so the hook decrypts from the row already in hand. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(telegram): per-binding progress-indicator toggle — dual-track migration, API, UI (ent#264) Default-ON toggle for the in-progress indicator, per-agent == per-binding: - Dual-track migration (Invariant #3 / Rule #9), all six touch points: SQLite `telegram_progress_indicator` in db/migrations.py + Alembic 0031_telegram_progress_indicator (down_revision 0030; renumber-at-rebase rule vs ent#265 applies to whichever PR merges second) + schema.py + tables.py DDL + _BINDING_COLUMNS + _row_to_binding. No backfill UPDATE: ADD COLUMN ... DEFAULT 1 populates existing rows (default ON is the AC). - Read predicate evaluated in Python, never SQL (`NULL != 0` is NULL): enabled ⇔ `v is None or v != 0` — only an explicit 0 disables. - db: set_progress_indicator_enabled + set_telegram_progress_indicator facade. - API: GET /api/agents/{name}/telegram surfaces progress_indicator_enabled (pinned in the hand-built response, #1809 lesson — configure PUT too) and is access-hardened get_current_user → AuthorizedAgentByName (the response carries webhook_url, which embeds the webhook secret — previously readable by ANY authenticated user; uniform-404 accessor, Invariant #8). New PUT /api/agents/{name}/telegram/progress-indicator — OwnedAgentByName + reject_agent_principal (behavior toggles are human-only, ent#223 lesson), 404 when no binding; dedicated route so toggling never re-sends the token. - models.py: TelegramProgressIndicatorRequest + response field (Invariant #14). - UI: TelegramChannelPanel.vue switch (SlackChannelPanel allow_proactive precedent), optimistic flip with revert-on-error, dark-mode aware. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(architecture): channel-adapter progress-indicator seam deltas (ent#264) base.py indicate_progress hook + capability attrs; message_router.py per-turn driver (arm/tick/resolve + backstop, inline-sync coupling named for #1081 pickers); telegram_adapter.py reaction ack + elapsed placeholder + default-ON per-binding toggle. Co-Authored-By: Claude Fable 5 <[email protected]> * test(telegram): progress-indicator unit suite — adapter, router driver, toggle (ent#264) 61 tests, no backend required. Highlights per the plan's scrutiny list: resolve-vs-first-send race (shielded id recording → delete finds it), cancel-and-await ordering at both terminal flavors, 429-backoff cancel promptness, [NO_REPLY]-still-resolves, step-8 wrap regression guard, singleton metadata isolation, degraded-quiesce after 2 consecutive failures, static-template-only egress pin (ent#224 class), live-select column test (4-file schema rule), real-DB facade round-trip (#1533 no-MagicMock), legacy-table SQLite migration + renumber-safe Alembic-twin existence, GET JSON field pinning (#1809) + AuthorizedAgentByName hardening pin, PUT reject_agent_principal 403. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(feature-flows): telegram in-progress status indicator section (ent#264) New section in telegram-integration.md: three fail-soft layers, the channel-agnostic start/progress/resolve seam, race closures (tick-after- resolve, resolve-vs-first-send, singleton concurrency), gating matrix (incl. `all`-mode groups; observe stays typing-only), toggle surface, degradation ladder / Bot API constraints, restart residual + the inline-sync coupling named for #1081/#1083 pickers, test inventory. Index unchanged (existing flow). Revision-history row added. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(telegram): access-harden the groups GET; document the bounded settle residual (ent#264) Review-stage fixes: - GET /api/agents/{name}/telegram/groups moves from bare get_current_user to the uniform-404 AuthorizedAgentByName accessor — the sibling read of the panel flow this PR already hardened. Group chat ids/titles/welcome text are tenant data; the only follow-up action (the group-message POST) was already OwnedAgentByName, so the read tier is strictly broader than every usable consumer and no flow narrows (incl. the MCP list_channel_groups path, whose paired send is owner-gated). - Route-dependency test pinning the groups-GET accessor (mirrors the binding-GET hardening pin). - Docs honesty: the resolve-path in-flight settle is bounded at 10s — a first placeholder send slower than that (429 retry_after >= 10s) is abandoned and can strand a self-dating placeholder. Named in the feature flow Residuals + requirements Known residuals instead of implying the race is closed unconditionally. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(db): source_channel_agent + telegram allow_proactive columns (ent#265) Dual-track migration (Invariant #3 / #1183): SQLite entry channel_report_back_columns + Alembic 0031_channel_report_back (single linear head off 0030), plus db/schema.py + db/tables.py so fresh builds stay correct. - schedule_executions.source_channel_agent (nullable TEXT): the agent whose channel binding owns the execution's INHERITED context (D1 Option A). Written only at the /task row-creation point; NULL for direct rows (reporter falls back to the executing agent). - telegram_group_configs.allow_proactive INTEGER DEFAULT 1: per-group completion-report consent, default ALLOW for existing AND new groups (opt-out mute; no backfill UPDATE needed). - create_task_execution accepts + inserts source_channel_agent; row mapper + ScheduleExecution model surface it. - AgentRef(schedule_executions.source_channel_agent, KEEP) so cascade_rename re-keys the binding agent (D1a); parity-test locks consciously updated (_AGENT_ID_COLUMNS + KEEP set). - Telegram group-config ops carry the flag (columns tuple, row mapper default-allow on NULL, update_group_config arm, explicit insert); database.py facade adds get_telegram_chat_link and converts the group-config passthrough to keyword args (eng M3). - TelegramGroupConfigResponse/UpdateRequest carry allow_proactive (Invariant #14; the response model IS the GET field allowlist). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(chat): persist inherited channel context at /task row creation (ent#265 D0) The ent#224 inheritance wire was severed: run_async_task threaded _inherited_channel_context's values into execute_task(source_channel=...), but execute_task writes channel columns ONLY in its no-execution_id creation branch — and the /task path always pre-creates the row in create_task_execution_and_activities. Every delegated row carried NULL channel context at terminal time, so the shipped Slack delegated report-back was latent dead code on its flagship path. - Resolve inheritance at the single row-creation point both the async and sync /task branches route through (the fork to _dispatch_async/_dispatch_sync happens AFTER creation), and persist all four fields on the row itself via db.create_task_execution. - _inherited_channel_context returns a 4-tuple: + source_channel_agent (D1 Option A — parent's own binding agent, else the parent's agent name; transitive across A→B→C; all-None when the parent lacks source_channel, so a channel-less child never carries a dangling agent pointer). - Provenance guard (security): db.get_execution(parent_id) is a global lookup; the inherited identity now also resolves a bot token. Agent caller (x_source_agent, already past the SELF-EXEC-001 spoof guard in derive_source_and_trigger) must BE the parent's executing agent; human caller must have access to the parent's agent. Failure → no inheritance, info log — fail-open to no-context, never to someone else's chat. - Remove the dead source_channel* threading from run_async_task (execute_task keeps its channel params — message_router uses them for direct turns). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(channels): Telegram completion report-back + failure-applier hook (ent#265) Telegram edition of the ent#224 Slack report-back: a Telegram-triggered long/delegated task posts its terminal back to the originating chat, threaded to the triggering message. channel_completion_report.py rework: - D10 resolver dispatch map (_CHANNEL_RESOLVERS: slack + telegram); SUPPORTED_CHANNELS derives from the map keys, so WhatsApp is additive. - D1 binding-agent resolution for BOTH channels: consent + bot token evaluate against binding_agent = row.source_channel_agent or row.agent_name — the bot the user actually addressed delivers (on Telegram no other bot even CAN deliver the DM). NULL column = legacy fallback, byte-identical pre-#265 behavior. Also fixes Slack's delegated case (previously suppressed whenever worker B wasn't bound to the originating channel); narrowing direction (channel consented to B but not to originating A → now suppressed) is intentional. - D2 Telegram consent: known group → is_active AND allow_proactive (default allow, opt-out mute); known DM chat link → consent-by-construction (the user cold-started the bot; a block is a 403 the send handles gracefully); unknown destination → suppress+log. - D5 rendering: pre-escape &/</> before _markdown_to_html (unescaped `<class 'ValueError'>` trips "can't parse entities" and the strip-HTML fallback deletes the substring), then post-conversion re-cap to 4096 ("message too long" is a 400 the parse-fallback does not catch). - D6 threading: reply_to_message_id when thread is numeric, DMs too; allow_sending_without_reply makes a deleted original safe. - D1c attribution: Telegram has no per-message sender name — when binding_agent != executing agent the head line names the worker. Slack keeps username=executing agent (unchanged). - D9 pin: effect_guard keeps agent_name = the EXECUTING agent (row.agent_name), never binding_agent — resolve_and_validate_execution fail-opens on mismatch, silently disarming dedup for exactly the delegated rows this feature exists for. - D4: failed send returns False INSIDE the guard (claim completes) — at-most-once bias, never blind-retry an ambiguous send. task_execution_service.py (D3, channel-agnostic — fixes Slack AC#2 too): the failure applier's CAS-won block emitted the #1578 event but never the channel report — the path agent-reported failure envelopes take. Sibling spawn added; CANCELLED envelopes report too (uniform with _write_terminal_and_gate). routers/telegram.py: PUT group-config passes allow_proactive through; the allow_proactive arm ONLY is human-only (reject_agent_principal — an agent-scoped key resolves to the owner and could self-grant consent, ent#223's own post-ship pitfall). TelegramChannelPanel.vue: per-group "Completion reports" opt-out checkbox in the panel's house idiom (updateGroup passthrough). Co-Authored-By: Claude Fable 5 <[email protected]> * test(channels): ent#265 suite + facade passthrough fix caught by it New tests/unit/test_265_telegram_completion_report.py (41 tests): - Wired-mock layer: Telegram delivery/consent/rendering decisions — delegated group report + threading, DM consent-by-construction, muted/inactive/unknown-destination suppression, graceful bot-cannot-post, inline-trigger no-double-post, D5 escape+cap, D1c attribution, D1 binding-agent resolution (telegram + slack) incl. the intentional Slack consent-narrowing pin (D1b). - Chokepoint layer: apply_result failure branch spawns the report on CAS-win only (D3), success-branch pin, CANCELLED-envelope report. - Real-DB layer (db_harness): D0 row READ-BACK inheritance tests (a SimpleNamespace mock row cannot see a severed write path — the exact reason ent#224 shipped broken), both provenance-guard arms, channel-less parent all-NULL, two-hop transitive root binding agent; REAL effect_guard replay with source_channel_agent != agent_name (D9/M1 — a binding_agent passthrough fail-opens resolution and posts twice → red); fan-out one-report-per-child (G3); live column SELECTs through db/tables.py metadata; group-config default-allow + kwargs round-trip (eng M3); router PUT round-trip incl. agent-principal 403 and the surgical-gate proof that trigger_mode stays agent-callable. Conscious test_224 edits: non-slack scope test → whatsapp-only (telegram grew a leg); consent fixture keyed on the binding agent. The read-back tests immediately caught a REAL gap: database.py's create_task_execution facade passthrough was missing source_channel_agent (the ops layer had it) — every /task dispatch would have raised TypeError. Fixed here; the exact severed-wire class D0 exists to kill. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(requirements): Dashboard type-to-filter — new §9.10, §9.9 seam note updated (ent#261) Trinity Rule #1: requirements before implementation. §9.10 specifies the / hotkey filter across Timeline/Grid/List — store-seam predicate, pre-query node invariant, pill honesty, Esc layering, chassis query-empty overlay, kbd hint, list-mode composition, and the deliberate timeline owner-filter behavior change. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(dashboard): / type-to-filter across timeline, grid, and list (ent#261) Store seam (network.js): non-persisted filterQuery + setFilterQuery; the visibleAgents seam splits into ownerFilteredAgents (tag ∘ owner, pre-query) and the query-aware visibleAgents (slug + display label via agentDisplayName, #1642). ALL THREE convertAgentsToNodes call sites now read the pre-query ownerFilteredAgents — incl. the 30s poll that previously rebuilt from the RAW list (nodes must never be query-filtered: timeline row enrichment would degrade after Esc). Dashboard chassis: document / keydown with guards (defaultPrevented/repeat, chords, IME, editable targets, open modals) + Firefox quick-find preventDefault; floating filter pill (open OR active — an applied-but-hidden filter is the dishonest state) with live 'X of Y match', Esc hint, x button; input-scoped Esc + gated document Esc backstop (tag-dropdown layered dismissal, native select skip); Enter blurs and keeps the filter; header kbd / toggle button (mouse/touch parity); ONE chassis query-empty overlay with panes MOUNTED underneath; true-empty onboarding CTA branches guarded && !filterActive; timeline :agents switched to the visibleAgents seam (owner filter now applies to timeline rows too — deliberate, release-noted); query cleared on unmount. AgentListPanel: N/M badge suppressed while the chassis query is active (two disagreeing denominators never render simultaneously). ReplayTimeline: data-agent test hook on row labels (no logic change). Co-Authored-By: Claude Fable 5 <[email protected]> * test(e2e): dashboard type-to-filter spec — 8 tests across all three modes (ent#261) Covers: grid live-filter + query-empty with the pane MOUNTED + Esc restore (@smoke); timeline row hiding via the :agents seam; list query-empty preceding the onboarding CTA + pill-x clear; editable-target guard + literal '/' inside the pill; kbd-hint toggle; non-persistence across reload; cross-mode filter survival + the document-Esc backstop after focus wanders; Enter blur-and-keep. Spec rules per plan: focus-wait before keyboard.type (nextTick focus race); regex count assertions (/^1 of \d+ match$/ — X is the claim, Y is environment). Full run defers to CI via the ui label. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): type-to-filter folded into the three dashboard flows + architecture note (ent#261) architecture.md: Grid-view block gains the type-to-filter seam sentence; the List-view block's seam description now covers all three panes. Flow deltas: grid — filter rides the absence-as-filtering layout path (pane stays mounted under the query-empty overlay); timeline — FILTER-001 gains a deliberately NOT-persisted row + a new ':agents = visibleAgents seam' section naming the owner-filter behavior change and the pre-query node invariant; list — D8 seam updated to landed state + the chassis-query ∘ panel-filter composition rules (badge suppression, overlay precedence). feature-flows.md changelog entry (no standalone flow doc, per plan D11). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(dashboard): review fixes — modal z-order, dual empty-state CTA, Esc scope, structural e2e backstop (ent#261) Four review findings on the type-to-filter, fixed in place: - CreateAgentModal was fixed z-10 — UNDER the new z-30 filter pill and z-20 query-empty overlay, so chassis chrome floated above the open modal. Raised to z-50, the house modal tier (SystemViewEditor / OnboardingWizard). Safe in all three mounts (wizard renders it v-if-exclusive with its own z-50 chrome). - AgentListPanel's filtered-empty card assumed the panel never mounts with a zero-agent prop — no longer true under a chassis query zero-match, so it rendered a second contradicting CTA under the query-empty overlay. Gated on a non-empty prop; the chassis overlay owns query-zero messaging (the behavior the list-view flow doc already described). e2e test 3 now pins it. - Document-Esc backstop generalized from the select-only guard to all editable targets: Esc inside the list panel's search box (or any other input/textarea/contenteditable) belongs to that control — it must not clear the chassis filter. Pill input unaffected (own handler stops). §9.10 wording updated to match. - e2e test 7's coordinate click (400,250) on the timeline pane could land on an agent row/toggle on seeded fleets — replaced with a structural pillInput.blur(). npm run build green; spec collects 8 tests. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): overlay-chrome z-order re-pricing + mount-invariant comments (ent#261 review) Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): sibling-route access-hardening class from the ent#264 review Co-Authored-By: Claude Fable 5 <[email protected]> * docs(flows): sync pass — seam note in skill-assignment, Recent Updates row, dead skills-management link purge (ent#263) /sync-feature-flows verification pass over the branch diff: - skill-assignment.md: note that SkillsPanel's package-fact chips now render via the shared components/skills/ contract seam (extracted in ent#263) - feature-flows.md: Recent Updates row for ent#263; removed the stale 'Skills Management UI' index row — skills-management.md was split/archived long ago (the archive table records it) and the live row pointed at a missing file - library-page.md: repointed its two skills-management.md links (propagated from the stale index row) at skill-assignment.md Co-Authored-By: Claude Fable 5 <[email protected]> * fix(library): harden stripUserinfo against silent-no-op and non-parseable URL shapes; share it with SkillsPanel (ent#263 review) Adversarial testing of the display-layer credential scrubber proved five leak shapes. Two families: the regex fallback under-matched what new URL() rejects (git+ssh:// schemes, protocol-relative //user:token@host, leading whitespace), and — worse — schemeless/scp user:token@host shapes PARSE as a WHATWG URL with an opaque hostless path where .username/.password assignment is a silent no-op, so the credential sailed through the success lane untouched. - move stripUserinfo to the shared components/skills/contract.js seam - trust the parsed lane only when host is present AND the strip verifiably took (post-assignment username/password empty); otherwise fall through to a widened textual scrub (scheme charset [A-Za-z][\w+.-]*, protocol- relative, schemeless colon-user, trim) - variant analysis: SkillsPanel's library_empty state rendered the RAW stored URL to any agent accessor — now scrubbed through the same helper - verified by an executed 26-case suite (23 adversarial leak shapes ALL PASS + 3 must-survive-unmangled regressions: plain https, scp git@host:path, path-@ preserved) - durable class captured in docs/memory/learnings.md Co-Authored-By: Claude Fable 5 <[email protected]> * docs: purge the second dead skills-management link; cso --diff report (ent#263 review) - feature-flows.md Archived Flows table pointed at archive/skills-management.md, which does not exist (the archive/ dir never received it) — same dead-link class d23005af purged from the skills index; row now says 'document not preserved' and names the dedicated flows it split into - add the /cso --diff report for the ent#263 review: zero backend surface delta; one MEDIUM display-layer scrubber finding (proven, remediated in 820895bf with variant coverage); secrets/enterprise- disclosure/XSS/supply-chain/CI categories clean Co-Authored-By: Claude Fable 5 <[email protected]> * docs(channels): channel report-back flow + requirements — pays the ent#224 debt (ent#265) - requirements/public-access.md: NEW §15.1h "Channel Completion Report-Back (CHANNEL-REPORT — ent#224 Slack, ent#265 Telegram)" — generic mechanism (inherited-context-only, D0 row-creation persistence + provenance guard, binding-agent resolution, chokepoints incl. D3, effect-guard at-most-once, sanitize-before-truncate), per-channel consent units, the two-DM-consent- regimes rationale (F6), known v1 limits, the deliberate ungated proactive-send scope cut. (§15.1f was already taken by WHATSAPP-001 — plan's placement kept, id shifted to h.) - feature-flows/channel-completion-report.md: NEW flow doc — entry points, D0/D3 fixes, chokepoint coverage table with the v1 boundaries (lease-reaper, bulk sweeps, pull sink, operator-terminate, restart mid-inline-turn, FAILED→SUCCESS resurrection, fan-out per-child, pre-migration NULL rows), destination/consent resolution per channel, D1 identity design with every rejected alternative, failure modes, Testing. Pays the #1763 flow-doc debt (ent#224 shipped undocumented). - feature-flows.md: Recent Updates row + Collaboration-table entry. - telegram-integration.md: ent#265 section (column + toggle + pointer) + revision row. - task-completion-events.md: sibling-spawn paragraph (report rides beside the #1578 emit at the same CAS-won chokepoints incl. the failure applier). - architecture.md: services-catalog entry for channel_completion_report.py, schedule_executions DDL line for source_channel_agent, telegram DB-module line mentions allow_proactive. - learnings.md: the D0 class — a threaded parameter only one callee branch consumes is a severed wire; mock-row suites are blind to it AND to its facade-passthrough sibling (caught pre-merge by the row-read-back tests). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(channels): key the inheritance provenance guard on the principal, not the header (ent#265) The D0 provenance guard selected its arm from the raw `X-Source-Agent` header. The SELF-EXEC-001 spoof guard in `derive_source_and_trigger` only fires when `current_user.agent_name` is set, so for a human caller that header is unvalidated client input (routers/chat.py documents the identical trap for the resume-session IDOR). Setting it to the parent execution's own agent name — a value the row itself discloses — satisfied the agent arm trivially and skipped the human arm entirely: any user with access to ANY agent could POST /task with someone else's `parent_execution_id` and have that task's terminal reported into the parent agent's Telegram DM or Slack thread, delivered by a bot binding they do not own. Second, narrower issue in the same guard: the human arm used `can_user_access_agent`, which admits share recipients. Posting into a channel chat is a proactive-send capability and every other proactive surface is owner-gated (`OwnedAgentByName` for group sends) or per-recipient-consented (#321); a share recipient can already read the owner's execution ids (`GET /api/executions` is accessor-scoped), so an accessor arm let them push a report into the owner's chat. Fix: arms are selected by the authenticated principal — - agent-scoped key must BE the parent's executing agent, - human must OWN the parent agent (`can_user_share_agent`) or be admin, - connector key (consumption-only, ent#46) never inherits, - no principal at all refuses. `x_source_agent` is still passed, now for logging only. Three regression tests, each verified red against the pre-fix guard. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(learnings): header-selected auth-guard arms collapse to the weakest arm (ent#265) Second instance of a class the codebase already warned about: routers/chat.py documents the same X-Source-Agent trap for the resume-session IDOR, and the ent#265 provenance guard reproduced it a few hundred lines away. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design-system): system of record, builder contract, reference page + raw-color scanner & ratchet baseline Stands up the frontend design system's written layer per #1430: - docs/memory/design-system.md — system of record: token taxonomy, both-theme rules incl. the dark ink ladder, type/spacing/radius scales, 10-primitive catalog with exact token recipes, the data-loading motion standard (scanline beam + wipe reveal; first load animates, background refresh is invisible), and 28 UI Construction Principles - docs/memory/design-system-contract.md — condensed binding contract to load before any src/frontend change - docs/memory/design-system-reference.html — approved visual spec (self- contained; both themes; live motion demo) - src/frontend/scripts/scan-raw-colors.mjs — raw-color scanner aligned with check-design-tokens.mjs token families - src/frontend/raw-color-baseline.json — ratchet seed at dev@5b28999: 753 raw non-gray / 383 hardcoded colors; counts may only shrink - CLAUDE.md — Rule of Engagement #10 + Memory Files row making the design system the mandatory reference for frontend work Refs #1430 Co-Authored-By: Claude Fable 5 <[email protected]> * fix: fleet restart adopts rebuilt base images through the canonical lifecycle path (#1860) (#1912) * fix: route fleet restart through the canonical lifecycle path so agents adopt rebuilt base images (#1860) POST /api/ops/fleet/restart stopped/started agents with raw Docker calls, bypassing start_agent_internal — no config-drift predicate ran and a rebuilt trinity-agent-base was never adopted on "Restart All" (#1809's cold-start gate never fired). - lifecycle.restart_agent_internal(): the canonical stop→cold-start helper (explicit stop is load-bearing for the #1809 image predicate; future home of #1817's per-agent start lock) - restart_fleet routes through it; per-agent recreated/recreate_reason surfaced via explicit allowlist copy, summary.recreated count - skips ephemeral ghosts (config predicates aren't ephemeral-gated — a recreate would destroy a volume-less ghost workspace, ent#69) - reject_agent_principal beside assert_admin (the endpoint now replaces containers — Invariant #8 escalation rule, #1816 precedent) - single-flight Redis SETNX lock ops:fleet_restart (409 on contention, own-lease refresh, compare-and-delete release, fail-open) — guards the client-timeout→retry overlap (#799/#1817 wedge class) - partial-safe fleet_restart audit entry with a per-agent recreate map (restores the entry dropped in 0ec3a7fc); sync cleanup ordered before the awaited audit so a shutdown CancelledError can't leave the lock held - actionable containerless-recovery errors (#1559), context-stats cache invalidation, 16 mocked unit tests, flow/architecture docs, learnings, CSO diff report (PASS) Fixes #1860 Co-Authored-By: Claude Fable 5 <[email protected]> * fix: never flow a raw exception message into fleet-restart results (CodeQL py/stack-trace-exposure) Per-agent failure rows now carry HTTPException .detail (platform-authored) or the exception class name only; the full message + traceback go to the backend log (exc_info). The #1559 containerless recovery hint is preserved. Tests strengthened into leak regression guards (raw message asserted absent); flow-doc line refs re-verified. Refs #1860 Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]> * feat(auth): bulk portal-session revocation primitive + operator client panel (#1902) * feat(auth): bulk portal-session revocation primitive + operator client panel The OSS half of an operator kill switch for signed-in portal clients. A client who signs in through sharing holds a 12-hour portal session with no way to end it short of a backend restart, which logs out everyone. `revoke_portal_sessions_for_email(email)` is the edition-agnostic primitive: OSS owns the mint, the decode and this bulk revoke; the entitled module that mints portal sessions decides WHEN to call it (the same split as the delegated mint). Mechanism is a per-email CUTOFF, not a jti list. `jti` is random per token and nothing indexes email -> issued jtis, so answering "which tokens does this address hold?" would need a write-side index maintained at every mint. One timestamp per email is O(1) to write and read, self-expiring at the max session lifetime (same bounded-growth property as the #187 blacklist, no sweep), and — the property that matters — covers every mint path by construction, since they all go through `create_portal_session_token`. That is the failure mode a hand-maintained index has and this does not. `create_portal_session_token` now stamps an explicit `iat` so tokens can be dated against the cutoff; set there rather than in `create_access_token` so no other token type's claim set changes. `decode_portal_session` rejects `iat <= cutoff`. Rounding toward revoking is deliberate: for a kill switch, a token minted in the same second as the revoke must die. A token with NO `iat` is treated as revoked — fail closed. Only sessions minted before this shipped lack one (all expired within PORTAL_SESSION_EXPIRE_HOURS of the upgrade), and only for an email an operator actively revoked; letting an undatable token survive an explicit kill switch is the worse failure. The Redis read stays fail-OPEN, matching #187 and the platform posture. That is why revocation is not the whole feature: the durable half lives in the entitled module and keeps working with Redis down. `revoke_...` returns a bool so a caller can report honestly instead of claiming a success the operator would act on. Frontend: `PortalClientsPanel.vue` on the Sharing tab — per-client log out / block / unblock with current state. Entitlement-gated (`client_portal`), so an OSS build renders nothing. Block is hidden for non-admins rather than offered and 403'd, and the panel reports a failed revoke as a failure rather than "signed out". It deliberately shows no live-session count: portal sessions are stateless JWTs with no server-side store, so any number would be a guess. Related to trinity-enterprise#281 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(ui): use the real status-danger design token in the portal clients panel `status-error-*` does not exist — the token family is success/warning/danger/info/urgent (tailwind.config.js), and `npm run check:tokens` caught every reference. No visual change intended: danger is the red alias the invented name was reaching for. Related to trinity-enterprise#281 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> * feat(skills): library lifecycle automation — auto-sync, fleet re-inject, removal-on-unassign (abilityai/trinity-enterprise#236) (#1883) * feat(skills): library lifecycle automation — auto-sync, fleet re-inject, removal-on-unassign Closes the three "Not Built" gaps in the skills lifecycle (requirements §21.1/§21.4). All three default OFF/no-op, so a zero-config install is unchanged. Removal-on-unassign - `compute_removal` is `compute_prune` against an empty new manifest, so path confinement, `..` rejection, and the cap live in one place and cannot drift. - `remove_skills` takes the SAME per-agent lock as injection (both mutate ~/.claude/skills and read-modify-write CLAUDE.md). Only manifest paths are deleted, so agent-authored files and runtime artifacts survive; a directory the removal empties is reaped via os.rmdir, which refuses a non-empty dir. - Wired into BOTH the single DELETE and the bulk PUT — the bulk PUT is the primary UI/MCP path and drops skills far more often. - The DB unassign is authoritative and always succeeds; a stopped agent, busy lock, or dead transport degrades to a named `removal_deferred:*`. - A partially-failed removal keeps the meta AND the .gitignore line: dropping the meta strands survivors as unmanaged orphans, and dropping the ignore line lets the 15-min auto-sync commit leftover injected files (#1595/#1596 class). Start-path reconciliation - The assignment row is gone by the time a stopped agent starts, so removal is reconciled, not replayed: the agent's platform-managed skill dirs are diffed against the assignment set. No tombstone table, no migration, and every removal route converges. Runs after injection and also at zero assigned skills — that is exactly the "unassigned the last skill" case. - Blast-radius guard: >10 removals for one agent refuses wholesale and alarms. A wiped agent_skills table is indistinguishable from a mass-unassign, and keeping files is the recoverable direction (#1638/#1644). Scheduled auto-sync + fleet re-inject - New leader-locked backend service (skills:sync:leader). Backend-hosted because the sweep must reach agent containers and the scheduler is platform-network-only. - Sweeps only when the library commit actually changed; running non-ghost agents; force=False so the ent#183 tree-SHA skip makes unchanged skills free; bounded concurrency; inject-lock contention is skip-and-report. - Honest aggregate report in Settings + operator alarm only when an agent failed. - Config re-read each cycle, so an interval change needs no restart. Durable sync status - `_last_sync`/`_last_commit_sha` were per-process; under `--workers 2` the worker answering /status was usually not the one that synced, so the panel showed a stale timestamp and could never show an error at all. Now mirrored to system_settings on both the success and failure branches, and the commit-changed comparison reads the durable row (the in-memory field would make every restart look like a change). Hardening found by /review and /cso on this branch - The persisted sync error is PAT-scrubbed: sync_library's outer handler passed a raw str(e), and the authenticated remote URL is an argument in the subprocess command list, so an OSError could carry a token into system_settings and the admin panel. - Cross-worker lock around the shared clone: scheduled + manual sync both run `git fetch` + `git reset --hard` on /data/skills-library. Contention returns 409 and writes no status row, so a contended click cannot paint "Last sync failed". - remove_skills re-reads assignments inside the lock and refuses a still-assigned skill, closing the bulk-PUT check-then-act race (#1445 pattern). - PUT /api/settings/skills-library is human-only (reject_agent_principal): it is the on-switch for an unattended fleet-wide write of SKILL.md files, which Claude executes as instructions. assert_admin answers "what role", never "is this a human" — third occurrence of the trinity-ops-agent#232 class. The remaining half of that chain (skills_library_url writable by an agent key via the generic settings PUT) is pre-existing and filed as abilityai/trinity-enterprise#293. Dedicated range-validated GET/PUT /api/settings/skills-library; the three keys are blocked on the unvalidated generic PUT. 58 new tests. Fixes abilityai/trinity-enterprise#236 * fix(skills): wire ent#236 tuning vars into both compose files + .env.example `SKILLS_RECONCILE_MAX_REMOVALS` and `SKILLS_FLEET_INJECT_CONCURRENCY` were read via os.getenv() but never reached the container — the #1056 / trinity-enterprise#31 packaging class. The reconcile-refusal alarm names the first var in its own remediation text ("raise SKILLS_RECONCILE_MAX_REMOVALS"), so on a deployed stack the operator was told to turn a lever that does not exist, leaving a legitimate mass-unassign permanently blocked at the default cap of 10. Found by /validate-pr on PR #1883. * fix(ui): agent tab panel polish — card borders, section spacing, and an honest Sync-now affordance Three cosmetic fixes plus one UX gap on the agent detail tabs. - SkillsPanel had no card wrapper, so its content sat flush against the tab bar unlike every sibling tab. Wrapped in the same card the other panels use. - FoldersPanel and InfoPanel each had a `v-else` content wrapper with no spacing class, so the root `space-y-6` never reached the cards inside and they rendered touching. Same bug in both files. - SkillsPanel: saving assignments writes the DB rows, but the files only reach the container on a sync or the next agent start. That was stated in muted text above the button, which is easy to miss — an operator can save, message the agent, and be told the skill doesn't exist, because it isn't there yet. "Sync now" now goes prominent while that gap is open, and only while the agent is running (shouting at a disabled control helps nobody). A failed or 409-busy sync keeps it lit, since the gap is still open. * fix(ui): inset the Settings and Skills tab content like every other tab 8 of the agent-detail tab wrappers use p-6 (overview, info, brain, dashboard, schedules, playbooks, git, folders). Settings and Skills had none, so their cards ran flush into the enclosing panel's left and right edges instead of sitting inset like the rest. * fix(skills): re-clone a library path that is not a repository, and make the panel's failures actionable Three fixes found while testing this PR on a live instance. All pre-existing on dev, but each is sharpened by putting sync on an unattended timer. 1. sync_library() chose pull-vs-clone on `library_path.exists()` — directory existence, not repo-ness. A path holding no `.git` (clone interrupted by a full disk, a stray mkdir, a restored backup) failed `git pull` with "not a git repository" on every attempt, with nothing able to re-clone: permanent, and recoverable only by shell access. Now tests for `.git` and re-clones. Detecting it is only half a fix, since `git clone` refuses a non-empty destination — so a non-repo directory is moved aside first. Renamed, never deleted: the platform owns the path exclusively so removal would probably be safe, but "probably safe" is not the standard for an unattended timer deleting a directory derived from an operator-supplied setting (#1638/#1644). One quarantine is kept, so a recurring fault cannot grow without bound. 2. syncSkillsLibrary() saves settings first (setting showSuccess), then syncs; the catch set `error` without clearing it, so a failed sync showed "Settings saved successfully!" and "Clone failed" together. Both true, which is precisely what makes the pair untrustworthy. 3. The panel never said a private library needs a GitHub PAT — it is in two internal docs only, and what an operator hits is raw git ("could not read Username"), which names no remedy and does not hint that the PAT field is one section above. Added that line. The error-string mapping is deliberately NOT done: matching git stderr is brittle across versions and locales, and the raw error is at least surfaced rather than swallowed. Tests: 5 new (4 fail without the fix). Also fixes 7 existing tests that created the library path without `.git` — under the corrected predicate they took the clone path and reached for the network; the suite drops 5.01s -> 0.62s. * fix: ownership-checked fleet-restart lease with loss detection + acquire inside try/finally (#1919) (#1928) The per-iteration refresh was a bare EXPIRE gated on a local flag — after a TTL lapse it extended a concurrent caller's lease while both loops ran. The refresh is now a pre-action ownership gate (GET-compare via the shared redis_breaker_util.lock_token_matches): a foreign token stops the run with honest partial accounting (summary/audit gain processed + stopped_early), an absent token is re-acquired via SETNX so an unraced run completes instead of aborting, EXPIRE→0 routes to the absent path, and refresh Redis errors stay fail-open with one throttled warning per run. list_all_agents_fast() moved inside the try/finally so nothing can ever leak the lock between acquire and release; an abnormal exit audits as stopped_early="error" + exception class name only. TTL 900→2100, sized above the slowest single agent (skill injection alone is bounded at 1800s) so a mid-agent lapse is no longer arithmetically guaranteed. Release stays compare-and-delete, attempted even after detected loss (foreign-safe by construction). +11 unit tests (27 total in the file); live-validated on the local stack (foreign takeover mid-run, absent re-acquire to completion, 409 concurrency, TTL 2098 observed, release verified). Sibling hand-rolled lock sites and the system_seed_service unconditional release → #1920. Fixes #1919 Co-authored-by: Claude Fable 5 <[email protected]> * fix(templates): contain local: template ids and stop deriving credential paths from name: (#1900) (#1935) * fix(templates): contain local: template id resolution on the read path (#1900) `GET /api/templates/{template_id:path}` handed `local:<name>` straight to `get_local_template`, which joined `<name>` onto the templates root with no validation. The `:path` converter permits `/`, so `local:../<x>`, `local:/<abs>/<x>` and a root-escaping symlink each read `<escaped-dir>/template.yaml` and echoed its contents in an authenticated 200. Reachable by any authenticated principal of any role — including an agent-scoped MCP key, so a prompt-injected agent qualifies. In a container the reachable set includes `/data/deployed-templates/<victim>`, where every user's uploaded template archive lands: a cross-tenant read. Two corrections to the issue's framing, both verified here: * it is NOT arbitrary file read — the filename is fixed (`template.yaml`), it must parse as a YAML mapping, and only a fixed key set is echoed. But those keys' VALUES are arbitrary YAML subtrees, not just strings. * `local:..` alone is not an existence oracle: a directory with no `template.yaml` returns the same 404 as an unknown id. Fix: `contained_template_dir(name, root)` — the two-step barrier the CREATE path has had since #950 (`crud._safe_local_template_path`), brought to the read path. A name allowlist runs BEFORE any path math (this is also what CodeQL recognises as a `py/path-injection` barrier; resolve-only was flagged high-severity twice on this codebase), then `resolve()` on BOTH sides plus `is_relative_to`. `str.startswith` is not equivalent — it passes the sibling escape `<root>-evil`. An escaping id returns `None`, so the router's 404 stays byte-identical to an unknown template: no error code, no path, no root name. A distinct error would be a NEW enumeration oracle, which is what #1759's single-sentence 404 exists to close. Rejections log at DEBUG, sanitized — the endpoint has no rate limit, so a per-rejection WARNING would be an authenticated log-flood primitive. The helper is public: the remote-template-registry work (trinity-enterprise#14) edits this same resolver family in this same module and should import it rather than copy it. Tests: every rejection test PLANTS a real `template.yaml` at the escaped location, because unpatched code returns `None` for any id whose target simply does not exist — a rejection test with nothing planted is green before and after and proves nothing. Each is labelled REPRO (verified red pre-fix) or HYGIENE (cannot be made red; contract only). The router guard lives in `tests/unit/` because no gating CI job collects `tests/test_templates.py`. `test_1900_containment_survives_a_symlinked_root` is the landmine guard for resolving both sides: a half-resolved variant passes all 130 pre-existing tests and only that test catches it. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(templates): stage .mcp.json from the validated template dir, not template name: (#1900) The second traversal sink, found by this issue's own AC #4 audit ("audit the by-name create path for the same join"). It is NOT the create path's `local:` id resolution — that has been contained since #950/#1759 via `crud._safe_local_template_path`, applied at both seams #1759 named. It is the create path's CREDENTIAL STAGING, which threw that validated path away and re-derived a directory from scratch: template_name = template_data.get("name", "") # untrusted mcp_template_path = templates_dir / template_name / ".mcp.json" `name:` comes from an uploaded template.yaml, so any `creator` reaches it via `deploy_local_agent`. `name: ../../data/deployed-templates/<victim>` read another tenant's `.mcp.json` — a credential-bearing file type under Invariant #12 — into the attacker's OWN agent, where they read it at leisure. A victim who hardcoded a token rather than a `${VAR}` placeholder leaks it. Assessed on its own axes, NOT inherited from the read sink: different trigger (`creator` role + an upload + an agent create, vs a bare authenticated GET) and a higher impact ceiling (credential values, not template metadata). Also P2, for different reasons. The derivation was also simply wrong. `name:` is not a directory name — 5 shipped templates declare a display string there ("Test Echo Agent"), so `local:test-echo` resolved to `<curated>/Test Echo Agent/.mcp.json`, which does not exist. That kills the "validate the name" framing: the value should not resolve paths at all. Fix is root-cause, not another guard: `_stage_config_files` already calls `_safe_local_template_path` itself for the `/template` bind decision, so the validated directory is available in the same function. Extract the two-root ladder as `_resolve_local_template_dir` and pass its result as `template_base_path`. The untrusted join is gone from the live path, and the #1759 "seams must agree" property becomes structural across all THREE seams (resolver, bind decision, credential stager) instead of two. Deliberately NOT threaded through `_TemplateResolution` or the return tuple: `_resolve_local_template` returns a 2-tuple that three existing tests depend on, two as monkeypatched `lambda config: ({}, None)` doubles — widening it breaks the test doubles, not just the callers. Its signature, its return arity, `_safe_local_template_path`, `_LOCAL_TEMPLATE_ROOTS`, and everything inside the CodeQL-sensitive `if template_yaml.exists():` block are untouched (#1793 had to revert exactly that reshape). The residual `template_base_path is None` arm is kept and made fail-closed: it is a public function with a `template_base_path=None` default, so a future caller can still reach it. It now contains through the same barrier as the id, which also absorbs a non-string `name:` — `Path(root) / 123` raised TypeError, i.e. an uncaught HTTP 500 during agent creation (the ent#128 bug class, one seam over). One disclosed behaviour change: a deploy-local template that BOTH declares `credentials.mcp_servers` AND ships a `.mcp.json` now gets `${VAR}` substitution, where the old curated-root lookup always missed. Verified no collision with `deploy._prepopulate_workspace_from_template`, which writes the archive's raw copy into the workspace volume: `startup.sh` copies `/generated-creds/.mcp.json` unconditionally (gated only on the directory existing) and AFTER the template-copy block (gated on `.trinity-initialized`), so the substituted file deterministically wins — which is the intended behaviour, the raw copy still carrying unsubstituted placeholders. Not one of the 26 shipped curated templates contains a `.mcp.json`, so the curated rows are provably unchanged. The crud seam tests are mandatory, not decorative: every service-level test calls `generate_credential_files` directly, so an "extracted but never wired" mistake leaves all of them green while deploy-local resolution silently regresses into the fallback arm. Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: record the #1900 containment contracts for template id + credential staging Rule #1 (requirements before implementation) — `core-agent.md`: * §4.1 gains the **read-path resolution contract** as a sibling to the existing create-time contract: `GET /api/templates/{id}` resolves `local:<name>` through the same two-step barrier the create path has had since #950, and a failing name returns a 404 byte-identical to an unknown template (the #1759 non-disclosure rule). Records the deliberate, known asymmetry that `get_local_templates()` still enumerates by `iterdir()` and so could LIST a root-escaping symlink that detail and create both refuse — the listing is the outlier, and planting one needs local filesystem write access, not a request. * §4.3 records that the `credentials.mcp_servers` template lookup now resolves from the validated path rather than the template's own untrusted `name:` field, including the one disclosed behaviour change (deploy-local templates now get `${VAR}` substitution) and why the substituted file wins over the archive's raw copy. `architecture.md` gets one clause on the `templates.py` router catalog entry (the catalog rule caps entries at 2 lines, and no Cross-Cutting Subsystems block is warranted). A bug fix would normally be commit-message-only under the tiered-docs rule; the exception is that this ships a public, importable containment primitive in the exact module and resolver family the remote template registry (trinity-enterprise#14) will edit, and one catalog clause is the cheapest way that author finds it instead of copying the flaw. Not updated, deliberately: no feature-flow doc (no new vertical slice), no user docs (no user-visible change for honest callers), no schema/migration (no DB change, so the dual-track SQLite/Alembic rule does not apply). Refs #1900 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(feature-flows): sync template-processing + local-agent-deploy for #1900 `/sync-feature-flows` was NOT a no-op here — three concrete staleness points in `template-processing.md`, which owns the `local:` resolution surface: * The inlined two-root ladder is now `_resolve_local_template_dir`; the code block showed the pre-extraction form. * "**Two** seams read `_LOCAL_TEMPLATE_ROOTS` and must stay in agreement" was the #1759 claim and is now wrong in the direction that matters: there was always a third seam (the credential-file stager) which did NOT agree — it re-derived the directory from the template's untrusted `name:`. Corrected to three, with the extraction as the structural guarantee. * `generate_credential_files` was cited by stale line range (`:228-299`) and documented none of where the `.mcp.json` template is actually located. Replaced the fragile line-range citation with a symbol reference and added the provenance, the residual fail-closed arm, and the disclosed deploy-local substitution delta. Also documents the read-path containment (`get_local_template` → `contained_template_dir`) beside the existing #1513 catalog-curation note, including the deliberate list-vs-detail asymmetry for a planted symlink. `local-agent-deploy.md` gets one line at the credential-merge step: a deploy-local template's `.mcp.json` now resolves from the deploy-local directory, so a hostile `name:` cannot read another tenant's file and `${VAR}` substitution finally applies to that template. `credential-injection.md` was checked and NOT touched — its `.mcp.json` references are unrelated (credential inject/export/import), and the template lookup live…
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
See Commits and Changes for more details.
Created by
pull[bot] (v2.0.0-alpha.4)
Can you help keep this open source service alive? 💖 Please sponsor : )